通过排除字段使用更新视图 django 编辑模型对象 [英] Editing the model object with update view django by excluding fields

查看:33
本文介绍了通过排除字段使用更新视图 django 编辑模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 django Updateview

I am trying to Edit/Update a model object(record) using django Updateview

model.py

from django.db import models
from myapp.models import Author

class Book(models.Model):
    author = models.ForeignKey(Author)
    book_name = models.CharField(max_length=260)
    amount = models.DecimalField(
        max_digits=10, decimal_places=2, default=0.00)

    description = models.TextField()

views.py

class BookEditView(generic.UpdateView):
    model = Book
    template_name_suffix = '_update_form'
    exclude = ('author',)

    def get_success_url(self):
        return reverse("books:list_of_books")

books_update_from.html

{% extends "base.html" %}
{% block main_title %}Edit Book{% endblock %}
{% block content %}
  <form method="post" action="" class="form-horizontal">
     {{form.as_p}}
  </form>
{% endblock %}

当表单呈现时,Author 外部字段仍然显示在页面上,即使我在 BookEditviewexclude 中提到过它如上

When the form is rendered, the Author foreign field is still displaying on the page even though i had mentioned it in exclude in BookEditview as above

那么如何隐藏该字段并提交表单?

So how to hide that field and submit the form ?

我也尝试通过呈现form.book_nameform.amount等个别字段,(我知道这种方法不能解决上述问题,但只是给了一个愚蠢的尝试).当我提交表单时,它的动作可以忽略不计并且什么都不做,因为我们没有提交作者外键值,因此表单无效并且提交什么都不做

Also i tried by rendering individual fields like form.book_name, form.amount etc.,(I know this approach does n't solve the above issue but just given a foolish try). when i submit the form, its action is negligable and does nothing because we are not submitting the author foreign key value and hence the form is invalid and submit does n't do anything

所以我想知道的是如何在使用 UpdateView 将其呈现为表单时如何从模型中排除该字段以编辑模型(我在上面的代码中是否做错了什么?)

So what i want to know is how to exclude the field from the model when rendering it as a form using UpdateView to edit the model(Am i done something wrong above in my code ?)

我还想知道 Updateview 的概念,如果我们排除 foreignKey 字段,则不需要提交外键值?(因为编辑表单将仅当包括 Author Foreign Key 在内的每个字段都提交了值时才有效?)

Also i want know the concept of Updateview that if we exclude the foreignKey field then there is no need to submit the foreign Key value ?(Because the Edit form will be valid only if every field including the Author Foreign Key is submitted with value ? )

推荐答案

定义一个排除字段的 BookForm,

Define a BookForm that excludes the field,

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        exclude = ('author',)

然后在您的视图中使用此表单

then use this form in your view

class BookEditView(generic.UpdateView):
    model = Book
    form_class = BookForm
    ...

这篇关于通过排除字段使用更新视图 django 编辑模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆