I’m using a ModelForm, but not using Django’s auth system. I am also trying to set a random password, but have commented out that bit because I’m not sure if it is causing issues.
Currently, the following will return ‘success’, but will not save to the database.
def registration(request):
if request.POST:
data = request.POST.copy()
data['date_joined'] = datetime.date.today()
data['last_login'] = datetime.datetime.now()
form = UserForm(data)
if form.is_valid():
try:
User.objects.get(username=form.cleaned_data['username'])
except User.DoesNotExist:
#ran_pw = User.objects.make_random_password(length=12)
#user.set_password(ran_pw)
user = User()
user.username = form.cleaned_data['username']
user.first_name = form.cleaned_data['first_name']
user.m_init = form.cleaned_data['m_init']
user.last_name = form.cleaned_data['last_name']
user.institution = form.cleaned_data['institution']
user.department = form.cleaned_data['department']
user.phone = form.cleaned_data['phone']
user.email = form.cleaned_data['email']
user.save()
return HttpResponse('success')
else:
return HttpResponse(form.errors)
else:
form = UserForm()
return HttpResponse(form.non_field_errors)
Presumably this happens when the user already exists in the database. That’s because you only actually set the data when the user doesn’t exist. Move all the field setting code back one indentation level.
Actually, you shouldn’t set the fields manually at all – the whole point of using a ModelForm is that you do
form = UserForm(data, instance=user)and then if the form is valid you just doform.save().