使用更新视图django通过排除字段来编辑模型对象

时间:2022-10-26 22:18:38

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

我正在尝试使用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 %}

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

呈现表单时,即使我在BookEditview中的exclude中提到了作者外部字段仍然显示在页面上

So how to hide that field and submit the form ?

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

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

此外,我尝试通过渲染单个字段,如form.book_name,form.amount等,(我知道这种方法不能解决上述问题,但只是给了一个愚蠢的尝试)。当我提交表格时,其行为可以忽略不计,因为我们没有提交作者外键值,因此表格无效,提交不做任何事情

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将模型渲染为表单时从模型中排除该字段(我在我的代码中做错了吗?)

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 ? )

另外我想知道Updateview的概念,如果我们排除foreignKey字段,那么就不需要提交外键值了吗?(因为只有包含作者外键的每个字段都提交值时,编辑表单才有效?)

1 个解决方案

#1


6  

Define a BookForm that excludes the field,

定义排除该字段的BookForm,

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
    ...

#1


6  

Define a BookForm that excludes the field,

定义排除该字段的BookForm,

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
    ...