Having a problem with my user registration form in django, the form wont submit the data and register the information, the registration form just clears out and loads the page again, with an empty form. Any ideas as too what I am doing wrong?
Forms.py
class RegisterForm(forms.Form):
real_name=forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Real Name','required':True}))
birthday=forms.DateField(label=_(u"birthdate(mm/dd/yy)"),widget=extras.SelectDateWidget(years=range(1900, now[0]+1)),required=False)
city=forms.CharField(max_length=30, widget=forms.TextInput(attrs={'placeholder': 'City','required':True}))
state=forms.CharField(max_length=2, widget=forms.TextInput(attrs={'placeholder': 'State','required':True}))
image = forms.ImageField(required=False)
class Meta:
""" To Specify the fields from User model and the extension of the user model from django, and to prevent abstraction"""
fields = ['real_name', 'birthday','city','state','image']
def clean_real_name(self):
last_name = self.cleaned_data['real_name']
return real_name
def clean_birthday_name(self):
birthday = self.cleaned_data['birthday']
return birthday
def clean_city(self):
city = self.cleaned_data['city']
return city
def clean_state(self):
state = self.cleaned_data['state']
return state
def clean_image(self):
image = self.cleaned_data['image']
return image
Views.py
def register(request):
template_var={}
form = RegisterForm()
if request.user.is_authenticated():
if request.method=="POST":
form=RegisterForm(request.POST.copy(),request.FILES)
if form.is_valid():
user=request.user
real_name=form.cleaned_data["real_name"]
birthday=form.cleaned_data["birthday"]
city = form.cleaned_data["city"]
state = form.cleaned_data["state"]
reqfile = request.FILES["image"]
resgisteruser=ProfileUser.objects.create( birthday=birthday, user_title='Fashionista', user_points=0,
city=city, state=state, image=reqfile)
resgisteruser.save()
return HttpResponseRedirect(reverse("dashboard"))
template_var["form"]=form
return render_to_response("registration/register.html",template_var,context_instance=RequestContext(request))
Related
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE)
name = models.CharField(max_length=200,null=True)
## phone = models.IntegerField(null=True)
email = models.EmailField(max_length=250)
profile_pic = models.ImageField(default='default_pic.png',null=True,blank=True)
date_created = models.DateTimeField(auto_now_add=True,null=True)
def __str__(self):
return self.name
class Task(models.Model):
customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True)
title = models.CharField(max_length=200)
description = models.TextField(null=True,blank=True)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
ordering = ['complete']
views.py
#login_required(login_url='login')
def taskCreate(request):
if request.method == 'POST':
form = TaskForm(request.POST or None)
if form.is_valid():
form.instance.customer = request.user
form.save()
return redirect('tasks')
else:
form = TaskForm()
context = {'form':form}
return render(request,'todo_list/task_create.html',context)
Error:
ValueError at /create_task/
Cannot assign "<SimpleLazyObject: <User: Dominic>>": "Task.customer" must be a "Customer" instance.
I am trying to link the username in the user account to be shown on the model Task.customer that represents the post is created by that user. May I ask any methods could be done in order to specify the customer in the model Task? Also I do not understand the error message in detail because my admin panel already has the current username in the Customer model. However if I used request.user.customer the username does not show up instead returning None so how to solve this issue?
I don't know form.instance.customer = request.user
but I think I understood what you meant and the below code does the same thing
#login_required(login_url='login')
def taskCreate(request):
if request.method == 'POST':
form = TaskForm(request.POST or None)
if form.is_valid():
t = form.save(commit = False)
t.customer = request.user # assigning current user to created task.customer
t.save()
return redirect('tasks')
else:
form = TaskForm()
context = {'form':form}
return render(request,'todo_list/task_create.html',context)
if the code is still not working then try changing your line
customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) to
customer = models.ForeignKey(User,on_delete=models.CASCADE,null=True) in your models.py
The error comes from the following snippet
form.instance.customer = request.user
request.user is not a Customer instance, you can try extracting the information from request.user and create a Customer object from it and then assign it back
How can I rise the error and information, if user is puting only "dummy date" without "#"?
Email model is email = models.EmailField(max_length=254) but is only preventing passsing empty field, and nothing else. Can someone advice ?
def addContact(request):
form = ContactForm
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect('/contact')
context = {'form': form}
return render(request, 'contact/new.html', context)
Forms:
class ContactForm(ModelForm):
class Meta:
model = Contact
fields = '__all__'
Models:
class Contact(models.Model):
full_name = models.CharField(max_length=500)
relationship = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
phone_number = models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __str__(self):
return self.full_name
If you use EmailField then it has a built-in validator. Here is the code (https://docs.djangoproject.com/en/3.1/ref/validators/#emailvalidator)
You can use this validator to check the user input.
Here is the source code: https://docs.djangoproject.com/en/2.2/_modules/django/core/validators/#EmailValidator
Trying to implement a file upload for a user profile page. I am recieving the following error:
null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (35,
profile/{now:%Y/%m/YmdHMSext_xg2iZ6M, null, null).
I've read that it probably has something to do with the User_ID, I tried passing form.user = request.user, but that didn't work. There are also two nulls, not just one.
Models.py
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True,
max_length=255)
#accepted_terms_of_service = models.Booleanfield()
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username':
self.username})
# Profile Image
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,
on_delete='CASCADE', related_name='user_profile')
school = models.CharField(max_length=30, null=True, blank=True)
image = models.ImageField(_("Picture"), upload_to=upload_to,
null=True, blank=True)
def __str__(self):
return self.user.username
views.py
#login_required
def add_image(request):
form = ProfileImageForm()
#form.user = request.user
if request.method == "POST":
form = ProfileImageForm(data=request.POST, files=request.FILES)
if form.is_valid():
form.save()
return redirect('userPage')
else:
return render(request, "users/user_image_form.html", {"form": form
})
forms.py
class ProfileImageForm(forms.ModelForm):
class Meta:
model = Profile
fields = ["image"]
This is because in your Profile model you add user column as ForeignKey which enforce to NOT NULL so the error throw.
To solve this you need to modify add_image method something like this
#login_required
def add_image(request):
form = ProfileImageForm()
#form.user = request.user
if request.method == "POST":
form = ProfileImageForm(data=request.POST, files=request.FILES)
if form.is_valid():
form = form.save(commit=False) # change is here
form.user=request.user.pk # change is here
form.save()
return redirect('userPage')
else:
return render(request, "users/user_image_form.html", {"form": form
The request.user.pk value get if you are logged in. But if you are logged in you need to assisn form.user = your_specified_id which id exists in User table.
If your case is, you are admin and you need to add an image to other users, so that you need to pass the user id in your add_image method.
Add in ProfileImageForm.py
add user in field list
I think its not necessary to have both Profile Model and Custom User Model. Because, as you are customizing the User model already, why not put Profile model's fields to User model as well. You can approach like this:
# model
def upload_to(instance, filename):
now = timezone_now()
base, ext = os.path.splitext(filename)
ext = ext.lower()
return "profile/{now:%Y/%m/%Y%m%d%H%M%S}{ext}"
class User(AbstractUser):
name = models.CharField(_('Name of User'), blank=True,
max_length=255)
school = models.CharField(max_length=30, null=True, blank=True)
image = models.ImageField(_("Picture"), upload_to=upload_to,
null=True, blank=True)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username':
self.username})
# views
#login_required
def add_image(request):
form = ProfileImageForm(data=request.POST or None, file=request.FILES or None, instance=request.user)
if request.method == "POST":
if form.is_valid():
form.save()
return redirect('userPage')
return render(request, "users/user_image_form.html", {"form": form
})
# forms.py
class ProfileImageForm(forms.ModelForm):
class Meta:
model = User
fields = ["image"]
Update
You can create a post_save signal, which will create a Profile Instance after each User is created.
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile = Profile(user=instance)
profile.save()
post_save.connect(create_user_profile,
sender=User,
dispatch_uid="profilecreation-signal")
Now in your form, you can directly pass this Profile instance:
#login_required
def add_image(request):
form = ProfileImageForm(data=request.POST, files=request.FILES, instance=request.user.profile)
if request.method == "POST":
if form.is_valid():
form.save()
return redirect('userPage')
else:
return render(request, "users/user_image_form.html", {"form": form
})
For existing user, you can create Profile from shell:
for user in User.objects.all():
Profile.objects.get_or_create(user=user)
I am currently trying to impliment a registration form but everytime I test it out, the new registrant replaces the old registration. So I am unable to have more than one user at a time.
any help would be great because I do not know what to do. Thanks.
My views:
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
new_user = bitcoinUser(first_name=cd['first_name'],
last_name=cd['last_name'],
phone_number=cd['phone_number'])
new_user.save()
my models:
class bitcoinUser(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone_number = models.IntegerField(primary_key=True)
I honestly don't know why that didn't work (I think it is because you are saving the object 'new_user' and not the form), but i will recommend the way that i do forms in Django:
models.py:
from django.forms import ModelForm
class Bitcoinuser(models.Model):
first_name = models.CharField(max_length=36)
last_name = models.CharField(max_length=36)
phone = models.IntegerField(primary_key=True)
def __str__(self):
return self.name
class BitcoinuserForm(ModelForm):
class Meta:
model = Bitcoinuser
fields = ['first_name', 'last_name', 'phone']
views.py:
from .models import BitcoinuserForm
def get_bitcoinuser(request):
if request.method == 'POST':
form = BitcoinuserForm(request.POST)
if form.is_valid():
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
phone = form.cleaned_data['phone']
form.save()
return HttpResponseRedirect('/database/')
else:
form = BitcoinuserForm()
return render(request, 'appname/get_bitcoinuser.html', {'form': form})
It's simple, straigthfoward and works fine.
When my users create a profile, their image gets saved fine but when they update it it doesn't get saved. I also don't know how to pull the pic so that they can see it before updating it.
This is the form:
class UpdateProfileForm(forms.ModelForm):
city = models.ForeignKey(City)
class Meta:
model = UserProfile
fields = ('city', 'profilepic')
def save(self, commit=True):
profile = super(UpdateProfileForm, self).save(commit=False)
if commit:
profile.save()
return profile
This is the view:
def updateprofile(request):
if request.method == 'POST':
update_user_form = UpdateUserForm(request.POST, instance=request.user)
update_profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)
if update_user_form.is_valid() and update_profile_form.is_valid():
update_user_form.save()
'''************************************************'''
profile = update_profile_form.save(commit=False)
if 'profilepic' in request.FILES:
profile.profilepic = request.FILES['profilepic']
profile.save()
'''************************************************'''
return HttpResponseRedirect(reverse('index'))
else:
update_user_form = UpdateUserForm(instance=request.user)
update_profile_form = UpdateProfileForm(instance=request.user.profile)
return render(request, 'updateprofile.html', {'update_user_form' : update_user_form, 'update_profile_form' : update_profile_form})
And this is model:
# this is model for user
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
hobbies = models.ManyToManyField(Hobby)
languages = models.ManyToManyField(Language)
profilepic = models.ImageField(upload_to='static/images/Profile Pictures', blank=True)
city = models.ForeignKey(City)
slug = models.SlugField(unique=True)
average_rating = models.IntegerField(default=0)
ratings_count = models.IntegerField(default=0)
def save(self, *args, **kwargs):
# Uncomment if you don't want the slug to change every time the name changes
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)
def __unicode__(self):
return self.user.username
Thank you.
Add request.FILES to the form:
update_profile_form = UpdateProfileForm(request.POST, request.FILES,
instance=request.user)
By default django doesn't includes files in request.POST
Also, I think instance for UserProfile model should be request.user.profile instead of request.user or am I missing something here?
Follow instructions from django-docs