B
B
baterson2015-10-30 00:37:51
Django
baterson, 2015-10-30 00:37:51

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)),
      }

View:
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, }, )

HTML:
<form action="{% url 'cabinet' %}" method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form|crispy }}
      <button class="btn btn-default" type="submit">Submit</button>
      </form>

I display all the form fields on the page and if I want to change only one field, an empty value will be written to the other.
The only solution I see is to create a separate form for each field.
There are more parameters in the form, I removed them so that it can be seen more clearly, so the approach above seems rational

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2015-10-30
@baterson

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.

M
Maxim Dunayevsky, 2015-10-30
@dunmaksim

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.

D
Degibenz, 2015-11-05
@Degibenz

You can do something like this CustomUser.objects.get(pk=request.pk).update(**data)
In this case, you need to create a dict with the values ​​​​that need to be updated.

{
"user_name" : "test_client"
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question