Answer the question
In order to leave comments, you need to log in
Django. How to change individual fields in a form?
Hello, I can’t figure out how to make a form for my user model so that I can change individual fields, and not all at once.
The form:
class ProfileForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ('avatar', 'firstname', 'lastname',
'date_of_birth',)
widgets = {
'date_of_birth': SelectDateWidget(years=range(1920, 2015)),
}
def cabinet(request):
profile = CustomUser.objects.get(pk = request.user.pk)
profile_user = CustomUser.objects.filter(pk = request.user.pk)
form = ProfileForm(request.POST, request.FILES or None, instance=profile)
if request.POST and form.is_valid():
obj = form.save(commit=False)
obj.profile_user = CustomUser.objects.get(pk=request.user.pk)
obj.save()
return redirect(reverse(cabinet))
return render(request, 'cabinet.html',
{'form':form, 'profile_user': profile_user, }, )
<form action="{% url 'cabinet' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-default" type="submit">Submit</button>
</form>
Answer the question
In order to leave comments, you need to log in
This is how the form fields are filled with values.
This is how to turn the model into a dictionary for initial.
You can also use UpdateView (CBV) and you don't even have to do any of the above.
Use a partial update() instead of a full save() : https://docs.djangoproject.com/en/1.8/ref/models/q...
It's
better to set the request header to PATCH instead of POST.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question