Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 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 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...