【问题标题】:Django form view to create and update object modelDjango 表单视图创建和更新对象模型
【发布时间】:2022-10-14 07:44:56
【问题描述】:

我有一个名为 RecordsCategory 的模型,它在以下两个地址上只有一个名为 name 的字段

  1. record_category/create/

  2. record_category/update/

    我怎么写我的窗体视图更新和创建?

    模型.py

    class RecordsCategory(models.Model):
        name = models.CharField(max_length=255, blank=True)
    

    视图.py

    class RecordCategoryView(FormView):
        ?
    

【问题讨论】:

    标签: django django-models django-views django-forms


    【解决方案1】:

    使用 django 通用的 UpdateView 和 CreateView。

    视图.py

    class RecordCategoryCreateView(CreateView):
        model = RecordsCategory
        fields = ['field name']
    

    对 UpdateView 重复相同的操作,确保在此过程中进行正确的更改。

    【讨论】:

    • 有没有办法在使用 FormView 时将数据保存到数据库
    • 抱歉,我无法帮你。但是,除非您真的需要为您的模型制作自定义 FormView,尤其是在开始时,我建议您坚持使用 Django 提供的内容,原因有很多。
    【解决方案2】:

    好吧,让我们考虑一个场景,我们创造RecordsCategory更新/编辑RecordsCategory 使用 Django 表单。

    假设你有一个模型如下:

    class RecordsCategory(models.Model):
        name = models.CharField(max_length=255, blank=True)
    

    现在,让我们添加表单:

    class RecordsCategoryForm(forms.ModelForm):
        class Meta:
            model = RecordsCategory
            fields = '__all__'
    
    
        def save(self):
            record_category = super(RecordsCategoryForm, self).save(commit=False)
            record_category.save()
            return record_category
    

    如果您观察保存方法,我们首先尝试获取记录类别对象而不将其保存到数据库中(通过commit=False)。这是为了确保应用程序不会引发IntegrityError(这意味着我们正在尝试保存到数据库而不输入/填写必填字段)。然后我们将它保存到数据库中。

    让我们为create new record category 添加视图:

    from django.views.generic import FormView
    
    class NewRecordsCategoryView(FormView):
        template_name = "blob/blob.html"
        form_class = RecordsCategoryForm
    
        def form_valid(self, form):
            form.save()
            return super(NewRecordCategoryView, self).form_valid(form)
    
        def get_success_url(self, *args, **kwargs):
            return reverse("some url name")
    

    我们已经将NewRecordsCategoryViewform_valid 方法覆盖为我们在上面覆盖的save() 方法。特别是由于我们无法访问模型/表单中的请求对象,我们需要传递给save() 方法。(我们也可以传递给__init__ 形式的方法,这是另一种方式)。

    现在,让我们添加另一个视图来更新记录类别对象:

    
    class EditRecordsCategoryView(UpdateView) #Note that we are using UpdateView and not FormView
        model = RecordsCategory
        form_class = RecordsCategoryForm
        template_name = "blob/blob.html"
    
        def form_valid(self, form): # here you should be redirected to the id which you want to change it.
            form.save()
            return super(EditRecordsCategoryView, self).form_valid(form)
    
        def get_success_url(self, *args, **kwargs):
            return reverse("some url name")
    

    并使用这些网址:

        ...
        path('record_category/create/', NewUserProfileView.as_view(), name="new-user-profile"),
        path('record_category/(?P<pk>d+)/update/', EditUserProfileView.as_view(), name="edit-user-profile"),
        ...
    

    以及使上述表单工作的基本 Django 模板:

    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
    
      <input type=submit value="submit" />
    </form>
    

    参考:

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 1970-01-01
      相关资源
      最近更新 更多