Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

django - Using modelForm with CreateView

I have a problem with CreateView. My code is a bit of a frankenstein monster with code from various tutorials, docs, and stackoverflow. I feel like I have misunderstood some fundamental step in the workflow.

Here is the models.py:

class Customer(models.Model):
    name = models.CharField(max_length=200, null=False, blank=False)
    phone = models.CharField(max_length=50, null=False, blank=True)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, 
                                   related_name='customers')

Here is the forms.py:

class CustomerForm(forms.ModelForm):

    def clean(self):
        super().clean()
        name = form.cleaned_data['name'].upper()
        form.cleaned_data['name'] = name

    class Meta:
        model = Customer

        fields = ['name', 'phone']
        widgets = {
            'name': forms.TextInput(attrs={"class": "form-control"}),
            'phone': forms.TextInput(attrs={"class": "form-control"}),}

Here is the views.py:

class CustomerCreateView(LoginRequiredMixin, CreateView):
    model = Customer
    form_class = CustomerForm
    context_object_name = 'customer_create'
    template_name = 'customers/customer-create.html'
    login_url = 'account_login'

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)

And lastly here is the template:

<form method="post">
  {% csrf_token %}

  {{ form.as_p }}
  <input type="submit" value="Save">
</form>

The problem is that when I hit save the page just refreshes and the new object is not created. What am I doing wrong?

UPDATE: changing form_valid method to this fixed the problem:

    def form_valid(self, form):
        form.instance = form.save(commit=False)
        form.instance.created_by = self.request.user
        form.instance.save()
        return super().form_valid(form)
question from:https://stackoverflow.com/questions/65941967/using-modelform-with-createview

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In forms.py fields = ['name', 'phone'] should be replaced by fields = ('name', 'phone')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...