简体   繁体   中英

Am I able to create a form that is able to add a new django.contrib.auth User without logging in to the admin panel?

Have created a form but unsure if is right and also unable to add a user, it will show TypeError/ This is how the form I want it to look like

The following is my coding:

 class Form_Add_User(forms.Form): name=forms.CharField(label="Name", max_length=50) dateofbirth=forms.DateField(label="Date of Birth", widget=forms.widgets.DateInput(format="%m/%d/%Y")) contactnum=forms.CharField(label="Contact Number", max_length=9) def adduser(request): if len(request.POST)>0: form=Form_Add_User(request.POST) if(form.is_valid()): name=form.cleaned_data['name'] dateofbirth=form.cleaned_data['dateofbirth'] contactnum=form.cleaned_data['contactnum'] new_user=User(name=name,dateofbirth=dateofbirth,contactnum=contactnum) new_user.save() return redirect('/adduser') else: return render(request,'adduser.html',{'form':form}) else: form=Form_Add_User return render(request,'adduser.html',{'form':form}) 

First off: it's always very useful to also post a full error message if you have one. The more info you give us, the easier (and quicker!) is answering your question.

I assume, your User model is not actually django's auth User model (see, if you had posted the model, I wouldn't have to guess). The form you pass to your template was not instantiated:

#...
else:
    form=Form_Add_User() #!!
    return render(request,'adduser.html',{'form':form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM