I have two models:
class Checklist(models.Model):
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
client_name = models.ForeignKey(Client, on_delete=models.CASCADE,
related_name='details')
fieldA = models.CharField(max_length=25, blank=True, null=True)
fieldA_Check= models.BooleanField(default=False)
fieldB = models.CharField(max_length=25, blank=True, null=True)
fieldB_Check= models.BooleanField(default=False)
class Client(models.Model):
client_fieldA = models.CharField(max_length=25)
client_fieldB = models.CharField(max_length=25)
client_fieldC = models.CharField(max_length=25)
Now I trying to change Client instance fields values via Checklist using following code:
@login_required
def create_order(request, pk):
instance = get_object_or_404(CheckList, id=pk)
form = myForm(request.POST or None, instance=instance)
if form.is_valid():
form.save()
messages.success(request, 'Test message')
return get_PDF_order(request, pk)
return render(request, 'templates/create_order.html', {'form': form})
here is my form:
class myForm(forms.ModelForm):
class Meta:
model = Client
fields = ('client_fieldA', 'client_fieldB', 'client_fieldC')
widgets = {
'client_fieldA': forms.TextInput(attrs={'class': 'form-control'}),
'client_fieldB': forms.TextInput(attrs={'class': 'form-control'}),
'client_fieldC': forms.TextInput(attrs={'class': 'form-control'}),
}
And it's works but only once. Data saved and I get a pdf file with this data, but subsequent attempts do not change anything. The field value still the same. I'm guessing that it is because I working with the Checklist instance but not Client. So, my questions are: 1) How I can get an access to all Client fields (a queryset of all Client fileds) via Checklist? 2) Although my code is incorrect - why does it work (once)? I mean why does it save first time?
Thank you all in advance!
CodePudding user response:
To formalize the answer, the instance is actually an instance of the model the form is based on. Thus, in your case, you cannot pass a CheckList instance to a form based on Client
Anyway, as far as you have the CheckList id, you can easily obtain the Client, and the code for your view will be:
@login_required
def create_order(request, pk):
instance = get_object_or_404(CheckList, id=pk)
form = myForm(request.POST or None, instance=instance.client_name)
if form.is_valid():
form.save()
messages.success(request, 'Test message')
return get_PDF_order(request, pk)
return render(request, 'templates/create_order.html', {'form': form})
CodePudding user response:
You pass it always the same instance, so what happens is that you are probably overwriting the same record over and over. I would recommend you to split this using the django-provided generic class-based views CreateView and UpdateView.
Stop reinventing the wheel, use class-based views. It'll pay off big time in the long term.
