customer registration not showing in django admin - python

Trying to create customer registration form for ecommerce website . No errors while submitting the form, but details are not shown in django admin . Here are required codes :
models.py
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200)
address = models.CharField(max_length=200, null=True, blank=True)
joined_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.full_name
urls.py
urlpatterns = [path("register",views.register, name="register")]
forms.py
class CustomerRegistrationForm(forms.ModelForm):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
email = forms.CharField(widget=forms.EmailInput())
class Meta:
model = Customer
fields = ["username", "password", "email", "full_name", "address"]
def clean_username(self):
uname = self.cleaned_data.get("username")
if User.objects.filter(username=uname).exists():
raise forms.ValidationError(
"Customer with this username already exists.")
return uname
views.py
def register(request):
form = CustomerRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
user = User.objects.create_user(username, email, password)
form.instance.user = user
return redirect("/")
return render(request,"register.html",{'form':form})
register.html
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<h3>Customer Registration Form</h3><hr>
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}}
<button class="btn btn-primary" >Register as a Customer</button>
</form>
<p> Already have an account? Login here</p>
</div>
</div>
</div>
Thank you in advance:)

In your view, you're creating Users, not Customers.
If you're starting a new project, I would suggest using a custom user model.
If that's not possible, you need to save the form first to generate a Customer instance and then connect it with the appropriate User model:
def register(request):
form = CustomerRegistrationForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
email = form.cleaned_data.get("email")
customer = form.save(commit=False)
user = User.objects.create_user(username, email, password)
customer.user = user
customer.save()
form.instance.user = user
return redirect("/")
return render(request,"register.html",{'form':form})

Related

Django-allauth - Custom Sign Up with OneToOneField

I created a sign up form using two grouped forms and it has been working perfectly, but I would like to use django-allauth because of the features (login only with e-mail, sending confirmation e-mail ...).
However even reading some topics I still couldn't.
forms.py
class ExtendedUserCreationForm(UserCreationForm):
email = forms.EmailField(required=True, label="E-mail")
first_name = forms.CharField(max_length=30, label="Nome")
last_name = forms.CharField(max_length=30, label="Sobrenome")
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email', 'password1', 'password2')
def save(self, commit=True):
user = super().save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
if commit:
user.save()
return user
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim', 'telefone', 'paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram')
CIDADES = []
for i in cidadesReader:
if i[1] not in CIDADES:
CIDADES.append(i[1])
widgets = {
'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}),
}
views.py
def signup(request):
if request.method == 'POST':
form = ExtendedUserCreationForm(request.POST)
profile_form = UserProfileForm(request.POST, request.FILES)
if form.is_valid() and profile_form.is_valid():
user = form.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=password)
#login(request, user)
return redirect('home')
else:
form = ExtendedUserCreationForm()
profile_form = UserProfileForm()
context = {'form': form, 'profile_form' : profile_form}
return render(request, 'registration/signup.html', context)
signup.html
{% extends '_base.html' %}
{% load crispy_forms_tags %}
{% block title %}Cadastrar{% endblock title %}
{% block content %}
<h2>Criar Perfil</h2>
<form novalidate method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
{{ profile_form|crispy }}
<button class="btn btn-success" type="submit">Cadastrar</button>
</form>
{% endblock content %}
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
SEXOS = (
('M', 'Masculino'),
('F', 'Feminino'),
)
sexo = models.CharField(max_length=1, choices=SEXOS)
data_nascimento = models.DateField(validators=[idade_minima])
...
I've tried using the ACCOUNT_SIGNUP_FORM_CLASS and ACCOUNT_FORMS options in settings.py, but it didn't work.
I tried to make some adjustments, as in this topic similar to my question:
Django allauth saving custom user profile fields with signup form
For example, I changed it in models.py and I did migrate:
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name ='profile')
After several attempts, the most common error is:
RelatedObjectDoesNotExist at /accounts/signup/
User has no profile.
Edit:
I changed my slug in UserProfile, because it depends from user (first name). The error changed:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: profiles_userprofile.user_id
But UserProfile has no user continues in the final.
(Using in settings.py: ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.UserProfileForm'. Details from traceback:
...lib/python3.6/site-packages/allauth/account/views.py in dispatch
215 return super(SignupView, self).dispatch(request, *args, **kwargs)
.../lib/python3.6/site-packages/allauth/account/views.py in post
104 response = self.form_valid(form)
...lib/python3.6/site-packages/allauth/account/views.py in form_valid
231 self.user = form.save(self.request)
...lib/python3.6/site-packages/allauth/account/forms.py in save
405 self.custom_signup(request, user)
...lib/python3.6/site-packages/allauth/account/forms.py in custom_signup
359 custom_form.save(user)
...profiles/models.py in save
super(UserProfile, self).save(*args, **kwargs)
▼ Local vars
Variable Value
__class__
<class 'profiles.models.UserProfile'>
args ()
kwargs {}
self Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
slug_name 'nome-sp-260221205510'
Signals
Using signals the error changed. I added it in models.py:
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
Error:
ValueError at /accounts/signup/
The 'foto' attribute has no file associated with it.
Then I tried remove foto field, but the other error happens in another field:
IntegrityError at /accounts/signup/
NOT NULL constraint failed: profiles_userprofile.data_nascimento
Thanks in advance for any help.
The error UserProfile has no user is triggered in UserProfile.save(). You are calling this the first time in your view with commit=False and only afterwards are you setting the user:
# your code from the question
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
I'm guessing that UserProfile.save reads the the user field to create the slug. You could either skip it if commit=False, or maybe it will already work if you change it like this:
profile_form.instance.user = user
profile.save()
Another common solution is, to provide the user when initializing the form, but then you would have to change your current view code quit a bit.
I achieved! No need to use signals. Here are the changes:
forms.py
I needed to use a single class:
class SignupForm(forms.ModelForm):
first_name = forms.CharField(max_length=30, label="Nome")
last_name = forms.CharField(max_length=30, label="Sobrenome")
class Meta:
model = UserProfile
fields = ('sexo', 'data_nascimento', 'foto', 'sobre_mim','telefone','paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram')
CIDADES = []
for i in cidadesReader:
if i[1] not in CIDADES:
CIDADES.append(i[1])
widgets = {
'cidade': floppyforms.widgets.Input(datalist=CIDADES, attrs={'autocomplete': 'off'}),
}
field_order = ['first_name', 'last_name', 'email', 'password1', 'password2',
'sexo', 'data_nascimento', 'foto', 'sobre_mim','telefone','paroquia',
'cidade','estado', 'cep', 'possui_filhos', 'facebook', 'instagram']
def signup(self, request, user):
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
profile, created = models.UserProfile.objects.get_or_create(user=user)
profile.sexo = self.cleaned_data['sexo']
profile.data_nascimento = self.cleaned_data['data_nascimento']
def compressImage(foto):
...
return foto
profile.foto = compressImage (self.cleaned_data['foto'])
profile.sobre_mim = self.cleaned_data['sobre_mim']
profile.telefone = self.cleaned_data['telefone']
profile.paroquia = self.cleaned_data['paroquia']
profile.cidade = self.cleaned_data['cidade']
profile.estado = self.cleaned_data['estado']
profile.cep = self.cleaned_data['cep']
profile.possui_filhos = self.cleaned_data['possui_filhos']
profile.facebook = self.cleaned_data['facebook']
profile.instagram = self.cleaned_data['instagram']
user.save()
profile.save()
Note:
I was using a function to compress images, in models.py.
To correct the error
ValueError at /accounts/signup/
The 'foto' attribute has no file associated with it
I had to bring it to forms.py
settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'profiles.forms.SignupForm'
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name ='profile')
SEXOS = (
('M', 'Masculino'),
('F', 'Feminino'),
)
sexo = models.CharField(max_length=1, choices=SEXOS)
...
Note:
It was necessary to test field by field.
Sometimes there were some errors like NOT NULL constraint failed ou no such table.
The solutions to these problems:
Add null=True in the field (temporarily)
makemigrations and migrate
Delete migrations
signup.html
Only {{ form|crispy }} is necessary (I could delete {{ profile_form|crispy }})
<form novalidate method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-success" type="submit">Cadastrar</button>
</form>
Thank you for your help, #Risadinha.

Django : Why is my submit interest form not submitted. Did I write my view or template wrongly?

Django : Why is my submit interest form not submitted. Did I write my view or template wrongly?
Based on the view I wrote, I dont even get redirected after I click on submit. And when i return to the home page, i Receive a message from here
messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest')
which is why I believe it is because the form is not valid thats why it is not submitting. but wth why is it not valid?? Thanks
views.py
def submit_interest_view(request, slug):
user = request.user
blog_post = BlogPost.objects.get(slug=slug)
num_blogpost = BlogPost.objects.filter(author=request.user).count()
if not user.is_authenticated:
return redirect('must_authenticate')
elif blog_post.author == request.user:
return HttpResponse('You cannot submit interest to your own post.')
interest_requests = Interest.objects.filter(interestsender=request.user, interestreceiver=blog_post.author)
for interest_request in interest_requests:
if interest_request.is_active:
return HttpResponse('You have already submitted your interest to this post.')
if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form)
form = SubmitInterestForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
author = Account.objects.get(email=user.email) # use get if you aim to get a single object not a queryset
obj.author = author
obj.blog_post = blog_post
obj.save()
messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest')
context['success_message'] = "Updated"
if request.META.get('HTTP_REFERER') == request.build_absolute_uri(reverse("HomeFeed:main")):
return redirect(reverse("HomeFeed:main"))
elif request.META.get('HTTP_REFERER') == request.build_absolute_uri(reverse("HomeFeed:detail", kwargs={'slug': slug })):
return redirect(reverse('HomeFeed:detail', kwargs={'slug': slug}))
else:
return redirect(reverse('HomeFeed:main'))
#return redirect(reverse('HomeFeed:detail', kwargs={'slug': slug})) # redirect to your post detail but use reverse to pass kwargs not just redirect
else:
messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest')
else:
form = SubmitInterestForm() # if request.method isnt POST you still need to define your form so it can be displayed
return render(request, "HomeFeed/submitinterest.html", {'form': form,'user': user, 'num_blogpost': num_blogpost, 'blog_post': blog_post}) # context dict
forms.py
HomeFeed: forms.py:
class SubmitInterestForm(forms.ModelForm):
class Meta:
model= Interest
fields = ['my_name', 'my_thoughts','short_file',]
models.py
class Interest(models.Model):
interestsender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='interestsender', on_delete=models.CASCADE)
interestreceiver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='interestreceiver', on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(blank=False, null=False, default=True)
my_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
my_thoughts = models.TextField(max_length=5000, null=False, blank=False)
short_file = models.FileField(upload_to='documents/', null=True, blank=True)
def upload_location(instance, filename):
#you define this variable called file_path. It belongs to the HomeFeed app, and takes in the parameter of author id, title of blog post with the file name that the author uploads it, and you want to format it
file_path = 'HomeFeed/{author_id}/{title}-{filename}'.format(
author_id=str(instance.author.id),title=str(instance.chief_title), filename=filename)
#the above will let you insert the strings, you want to take ID of the user who is uploading and converting it into a string, and also the title and file name, converting them into string
# return file path means where the images is stored, either the local machine/ production environment which will be the name file stored in the content delivery network
return file_path
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, unique=True)
date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published")
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
html:
submit_interest.thml
<form method="post" enctype="multipart/form-data">{% csrf_token %}
<div class="form-group">
<input class="form-control bg-white form-control-plaintext c" rows="10" type="text" name="my_name" id="my_name" placeholder="Name: {{ request.user.username }}" readonly></input>
</div>
<div class="form-group">
<label for="my_thoughts text-dark">thoughts:</label>
<textarea class="form-control" rows="6" type="text" name="my_thoughts" id="my_thoughts" placeholder="My thoughts..." required></textarea >
</div>
<label for="short_file " class="text-dark">Brief file (Optional):</label>
<input type="file" class="btn btn-md btn-light" name="short_file" id="short_file"> <!--<button type="submit" class="btn btn-md btn-info">Upload</button>-->
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
<button class="submit-button btn btn-lg btn-primary mt-3 btn-block col-lg-6 offset-lg-3 " type="submit">Submit Interest</button>
</form>
urls.py
app_name = 'HomeFeed'
urlpatterns = [
path('', home_feed_view , name= "main"),
path('submitinterest/<slug>', submit_interest_view, name= "submitinterest"),
You need to find out why this is not validating. When the form is not valid, send the form instance back to template via context and try to render the errors. For example:
# view
if form.is_valid():
# ...
else:
messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest')
return render(request, "HomeFeed/submitinterest.html", {'form': form,'user': user, 'num_blogpost': num_blogpost, 'blog_post': blog_post}) # context dict
# template
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
For more details on form error rendering, please see the documentation.
BTW some minor optimisation on your code:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
#login_required
def submit_interest_view(request, slug):
user = request.user
blog_post = get_object_or_404(BlogPost, slug=slug)
num_blogpost = BlogPost.objects.filter(author=user).count()
if blog_post.author.email == user.email:
return HttpResponse('You cannot submit interest to your own post.')
interest_requests = Interest.objects.filter(interestsender=user, interestreceiver=blog_post.author, is_active=True)
if interest_requests.exists():
return HttpResponse('You have already submitted your interest to this post.')
if request.method == 'POST': # use request.method == 'POST' to submit POST request (like submitting a form)
form = SubmitInterestForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
author = Account.objects.get(email=user.email) # use 'author = user.account' if there is OneToOne relation between user and account
obj.author = author
obj.blog_post = blog_post
obj.save()
messages.success(request, 'Your interests have been submitted', extra_tags='submittedinterest')
context['success_message'] = "Updated"
if request.META.get('HTTP_REFERER') == request.build_absolute_uri(reverse("HomeFeed:main")):
return redirect(reverse("HomeFeed:main"))
elif request.META.get('HTTP_REFERER') == request.build_absolute_uri(reverse("HomeFeed:detail", kwargs={'slug': slug })):
return redirect(reverse('HomeFeed:detail', kwargs={'slug': slug}))
else:
return redirect(reverse('HomeFeed:main'))
#return redirect(reverse('HomeFeed:detail', kwargs={'slug': slug})) # redirect to your post detail but use reverse to pass kwargs not just redirect
else:
messages.warning(request, 'Something went wrong. Please try again..', extra_tags='wronginterest')
return render(request, "HomeFeed/submitinterest.html", {'form': form,'user': user, 'num_blogpost': num_blogpost, 'blog_post': blog_post})
else:
form = SubmitInterestForm() # if request.method isnt POST you still need to define your form so it can be displayed
return render(request, "HomeFeed/submitinterest.html", {'form': form,'user': user, 'num_blogpost': num_blogpost, 'blog_post': blog_post}) # context dict

'NoneType' object has no attribute 'set_password' in django registration and login

I am entirely new to django.
Trying to create login and registration system.
User registers successfully, saved in database but I get this error after registering.
"'NoneType' object has no attribute 'set_password'"
views.py
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
form.save()
username = form.cleaned_data.get('username')
fullname = form.cleaned_data.get('fullname')
password = form.cleaned_data.get('password1')
user = authenticate(request, username=username, password=password)
messages.success(request, f'Welcome to blaza {fullname}')
user.set_password(password)
user.save()
if user is not None:
login(request, user)
return redirect(reverse('home'))
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})
When I remove "user.set_password" it works but registered users can not login with their credentials even when the username and password is correct, It says incorrect username and password. (only admin account, superuser can login).
So I researched and had to add the user.set_password and user = form.save (I get warning that local variable user value is not used)
forms.py
class SignUpForm(UserCreationForm):
username = forms.CharField(max_length=50)
fullname = forms.CharField(max_length=200)
email = forms.EmailField(max_length=200)
password2 = None
class Meta:
model = User
fields = ('username', 'fullname', 'email', 'password1')
def clean_password1(self):
password1 = self.cleaned_data.get('password1')
try:
password_validation.validate_password(password1, self.instance)
except forms.ValidationError as error:
self.add_error('password1', error)
return password1
Models.py
class CustomUser(AbstractUser):
class Meta:
db_table = 'users'
fullname = models.CharField(max_length=200)
email = models.EmailField(max_length=150)
profile_photo = models.ImageField(upload_to='images/profile_pics', default='images/nophoto.png')
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 "
"digits "
"allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=13, default='')
address = models.CharField(max_length=100, default='')
has_store = models.BooleanField(default=False)
signup.html
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}<br>
{{ field }}
{% if field.help_text %}
<small style="color: grey">{{ field.help_text }}</small>
{% endif %}
{% for error in field.errors %}
<p style="color: red">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<button type="submit">Sign up</button>
</form>
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
path('accounts/', include('users.urls')),
path('accounts/', include('django.contrib.auth.urls')),
]
Or Someone help me with a secured and working registration and login that actually works.
In a simple signup form:
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
fullname = form.cleaned_data.get('fullname')
password = form.cleaned_data.get('password1')
saved_user = form.save(commit=False)
saved_user.set_password(password)
saved_user.save()
user = authenticate(request, username=username, password=password)
messages.success(request, f'Welcome to blaza {fullname}')
if user is not None:
login(request, user)
return redirect(reverse('home'))
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})
The reason you get noneType because you save user after the authenticate() so it return None

Django integrity error and not loading onetoone table on sign up form

Hello everyone thanks for your help.
I have made a sign up form with django. As of now when i fill in all of the fields in the form it allows me to submit, the new user is created, then i get the error below
UNIQUE constraint failed: slug_trade_app_userprofile.user_id
Also in my models (below) i have a onetoone relations with the UserProfile model and for some reason none of that data is stored to the database, it only gets the username/pass/first/last. It appears to me that for some reason it submits the form the trys to submit again causing the UNIQUE issue. Not sure what i did wrong here, thanks for your help.
Blow is my code
views.py
def signup(request):
signed_in = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(request.POST)
print(user_form.is_valid())
print(profile_form.is_valid())
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_picture' in request.FILES:
profile.profile_picture = request.FILES['profile_picture']
profile.save()
signed_in = True
else:
print(user_form.errors, profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request, 'my_app/signup.html',
{'user_form':user_form,
'profile_form':profile_form,
'signed_in':signed_in})
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='static/profile_pictures', blank=True )
bio = models.TextField(max_length=500, blank=True)
on_off_campus = models.CharField(max_length=3,
default="on",
choices=CAMPUS_STATUS)
forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta():
model = User
fields = ('username','first_name', 'last_name', 'email', 'password')
class UserProfileForm(forms.ModelForm):
class Meta():
model = UserProfile
fields = ('profile_picture', 'bio', 'on_off_campus')
signup.html
{% if registered %}
<h1>Thank you for registering!</h1>
{% else %}
<h2>Sign Up</h2>
<form enctype="multipart/form-data" method="post" >
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="" value="Sign Up">
</form>
{% endif %}

form.is_valid() always returns false

I have tried all the solutions given on SO but was not able to slve this
view.py
def signup(request):
form = SignupForm(request.GET)
print("%s"%request.GET['hobby'])
form.errors
#h=SignupForm(request.POST)
if form.is_valid():
email = request.GET['email']
location = request.GET['location'] users=User(username=username,email=email,password=request.GET['password'],location=location)
user_profile = request.user.profile
user_profile.location = location
user_profile.save()
form.save()
return HttpResponseRedirect('mtweet/')
return render(request,'mtweet/signup.html',{'SignupForm':form})
form.py
class SignupForm(UserCreationForm):
username=forms.CharField(label = " Username",required=True)
email = forms.EmailField(label = "Email",required=True)
password = forms.CharField(widget = forms.PasswordInput,required=True)
location=forms.CharField(label="Location",required=False)
class Meta:
model = User
fields = ("username", "email","location")
signup.html
<div id="register">
<form method="post" action="{% url 'mtweet.views.signup' %}">
{% csrf_token %}
<table>
{{ SignupForm.as_p}}
</table>
<input type="submit" value="Submit" />
</form>
</div>
There are a few problems with your code; let me try and re-write it:
class SignupForm(forms.Form):
username=forms.CharField(label = " Username",required=True)
email = forms.EmailField(label = "Email",required=True)
password = forms.CharField(widget=forms.PasswordInput,required=True)
location=forms.CharField(label="Location",required=False)
def signup(request):
form = SignupForm(request.POST, request.FILES)
if form.is_valid():
email = form.cleaned_data['email']
location = form.cleaned_data['location']
password = form.cleaned_data['password']
username = form.cleaned_data['username']
user = User.objects.create_user(username, email, password)
user.save()
user_profile = user.profile
user_profile.location = location
user_profile.save()
return HttpResponseRedirect('mtweet/')
else:
return render(request,'mtweet/signup.html',{'SignupForm':form})
return render(request,'mtweet/signup.html',{'SignupForm':SignupForm()})

Categories