Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing the model object with update view django by excluding fields

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 %}

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 ?

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

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

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

like image 494
Shiva Krishna Bavandla Avatar asked Jul 29 '13 07:07

Shiva Krishna Bavandla


1 Answers

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
    ...
like image 173
Alasdair Avatar answered Sep 20 '22 20:09

Alasdair