This is supposed to be a trial run of a sign up form but the database is not storing the username and password. The error I'm getting is "The User could not be created because the data didn't validate".
views.py
def add_model(request):
if request.method=="POST":
form=UserForm(request.POST)
if form.is_valid:
model_instance=form.save(commit=False)
model_instance.save()
forms.py
class UserForm(forms.ModelForm):
class Meta:
model=User
fields=['username','password']
models.py
class User(models.Model):
username=models.CharField(max_length=25, primary_key=True,default="")
password=models.CharField(max_length=15,default="")
def __str__(self):
return self.username
It should be if form.is_valid()
instead of if form.is_valid
.
And "the data didn't validate" basically means you are trying to save()
an invalid form.
forms.py
class UserForm(forms.ModelForm):
class Meta:
model=User
fields=['username','password']
def clean_username(self):
username = self.cleaned_data.get('username')
def clean_password(self):
password = self.cleaned_data.get('password')
views.py
def add_model(request):
if request.method=="POST":
form=UserForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
new_user = User()
new_user.username = username
new_user.password = password
new_user.save()
I think This should be working correctly for your purpose.
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.