Answer the question
In order to leave comments, you need to log in
How to automatically increment a value in a form?
Good afternoon, I shoveled all the documentation, tried many ways, but I still can’t get the desired result.
There is a form that is bound to the User model. The User model has a "term" attribute that should be incremented by 1 each time a submit is clicked.
Here is what I wrote:
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.forms import ModelForm
class User(AbstractUser):
term = models.IntegerField(default=1)
from django import forms
from .models import User
class UserProfile(forms.ModelForm):
term = forms.IntegerField()
class Meta:
model = User
fields = ['term']
def main(request):
args = {}
args.update(csrf(request))
args['term'] = auth.get_user(request).term
if request.method == 'POST':
a = User.objects.get(pk = 1)
form = UserProfile(request.POST or None, instance = a)
if form.is_valid():
term = auth.get_user(request).term
term += 1
form.save()
return redirect ('/base/main.html')
else:
args['form'] = form
return render_to_response('base/main.html', RequestContext(request, args))
Answer the question
In order to leave comments, you need to log in
Why does meta.fields need term at all if it is incremented?
user = form.save(commit=False) # Получаем обновлённую модель юзера из формы.
user.term += 1
user.save()
from django.views.generic import *
class YourFormView(FormView):
form_class = UserProfile
template_name = 'path/to/your_template.html'
def form_valid(self, form): # Вызывается, если форма is_valid
user = form.save(commit=False)
user.term += 1
user.save()
return # Чего вы хотите вернуть (обычно это редирект)
def form_invalid(self, form):
# Что-то делаем, если форма невалидна. По-умолчанию, джанго возвращает
# на ту же страницу и показывает ошибки в форме.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question