Well, Let's consider a scenario where we create a RecordsCategory
and update/edit the RecordsCategory
using Django forms.
Suppose you have a certain model as follows:
class RecordsCategory(models.Model):
name = models.CharField(max_length=255, blank=True)
Now, let's add forms:
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
If you observe the save method, we are first trying to get the record category object without saving it to the database (via commit=False
). This is to make sure that the application doesn't raise IntegrityError
(which means we are trying to save to DB without entering/filling mandatory fields). Then we are saving it to the database.
Let's add views for 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")
We have overridden form_valid
method of NewRecordsCategoryView
to save()
method that we have overridden above. Specially since we can't access request objects in models/forms, we need to pass to save()
method.(we can also pass to __init__
method of form, that's another way).
Now, let's add another view to update the record category object:
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")
And with these urls:
...
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"),
...
And the basic Django template to make the above forms work:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type=submit value="submit" />
</form>
References: