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
Related
I tried to make a creation form for vacancy on my job search site, but i faced with problem. I have User model, company model and vacancy model. They are inherited by foreignkeys. And the problem is that user can use all companies for creation a vacancy instead of created by this user companies(User can create several companies). I tried to change creation form and view by filtering, but it didn't work out for me. I am new at django and i dint find anything to resolve my problem.
Model of company:
class Company(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(('Title of Shop'), blank=True, max_length=255)
info = models.TextField(('Information about Shop'), null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.title)
Model of vacancy:
class Vacancies(models.Model):
title = models.CharField(('Title of Vacancy'), blank=True, max_length=255)
city = models.ForeignKey(City, on_delete=models.CASCADE, default='363')
description = models.TextField(('Information about Vacancy'), null=True, blank=True)
employer = models.ForeignKey(Company, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return str(self.title)
Create vacancy view:
#login_required(login_url='login')
def createVacancy(request):
form = VacanciesForm()
cities = City.objects.all()
if request.method == 'POST':
form = VacanciesForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form, 'cities': cities}
return render(request, 'vacancy_form.html', context)
Vacancy form:
class VacanciesForm(ModelForm):
class Meta:
model = Vacancies
fields = '__all__'
What do I need to change to get the correct display of companies in the vacancy
Try this:
#login_required(login_url='login')
def create_vacancy(request):
user = request.user
cities = City.objects.all()
if request.method == 'POST':
form = VacanciesForm(data=request.POST, instance=user)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form, 'cities': cities}
return render(request, 'vacancy_form.html', context)
Also you can use in view:
def create_vacancy(request, logined_user_id):
vacancies = Vacancies.objects.filter(owner=logined_user_id)
...
And you can try some logic here:
class VacanciesForm(ModelForm):
vacancies = [some_logic]
class Meta:
model = Vacancies
fields = '__all__'
Finally, you can read docs:
modelforms
This work:
views
def createVacancy(request):
cities = City.objects.all()
form = VacanciesForm(data=request.POST, request=request)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form, 'cities': cities,}
return render(request, 'vacancy_form.html', context)
forms
class VacanciesForm(ModelForm, forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(VacanciesForm, self).__init__(*args, **kwargs)
self.fields['employer'].queryset = EmployerCard.objects.filter(owner=self.request.user)
class Meta:
model = Vacancies
fields = '__all__'
Im looking to make it so the logged in user that creates a profile is linked to their guestprofile model when they create their profile.
When I create the guest profile while logged in, it successfully creates the guest profile, but in the guest profile admin screen there is no user connected to the guest profile model created. Instead there is a dropdown menu listing all users, which makes the connection process manual. Thanks.
Forms.py
class AddProfileForm(forms.ModelForm):
name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'}))
location = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))
summary = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'}))
profile_pic = forms.ImageField()
class Meta:
model = GuestProfile
fields = ('name', 'location', 'summary', 'profile_pic')
Models.py
class GuestProfile(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
summary = models.TextField(max_length=350)
profile_pic = models.ImageField(null=True, blank=True, upload_to="images/")
def __str__(self):
return str(self.user)
views.py
class AddProfileView(CreateView):
model = GuestProfile
form_class = AddProfileForm
template_name = 'profilemanip/addprofile.html'
success_url = reverse_lazy('home')
def get_object(self):
return self.request.user
Edit: I ended up solving my issue by changing my AddProfileView to the following:
def AddProfileView(request,*args,**kwargs):
form = AddProfileForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
form = AddProfileForm()
return render(request, "profilemanip/addprofile.html", {"form": form})
Try adding this to your AddProfileForm in order to associate the user with the profile:
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user',None)
super(AddProfileForm, self).__init__(*args, **kwargs)
I wrote the following code:
class RegisterForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = CustomUser
fields = ('username', 'email', 'password1', 'password2')
#login_required(login_url="/login")
def index(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
profile = Profile().save()
user = form
user.profile = profile
user.save()
return redirect('users')
else:
print(form.errors)
else:
form = RegisterForm()
user_model = get_user_model()
users = user_model.objects.all()
paginator = Paginator(users, 15)
page = request.GET.get('page')
users = paginator.get_page(page)
return render(request, 'users/index.html', {'users': users, 'form': form})
class Profile(models.Model):
has_premium_until = models.DateTimeField(null=True, blank=True)
has_premium = models.BooleanField(default=False)
has_telegram_premium_until = models.DateTimeField(null=True, blank=True)
has_telegram_premium = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class CustomUser(AbstractUser):
email = models.EmailField(max_length=255, unique=True)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True)
When I'm submitting the form the user as well as the profile is created but the profile is not stored in the user (the profile_id stays null).
Anyone who can help me out?
Change your code to
if form.is_valid():
profile = Profile().save()
user = form.save(commit=False)
user.profile = profile
user.save()
return redirect('users')
This way the user object will be created and then you refer to the profile ju just created and save it.
There is however another way of doing it with signals:
#receiver(models.signals.post_save, sender=CustomUser)
def create_profile_on_user_reg(sender, instance, created,**kwargs):
if created:
instance.profile = Profile()
instance.save()
Check out more on Django signals documentation
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)
In my Django project i create an app to have additional information about registered users. So my model looks like this:
class UserProfile(models.Model):
class Meta:
verbose_name_plural = u'User Profile'
user = models.OneToOneField(User)
birthday = models.DateField(blank=True, null=True)
avatar = models.ImageField(upload_to='media/profile/avatar', blank=True, null=True)
name = models.CharField(blank=True, null=True, max_length=20)
surname = models.CharField(blank=True, null=True, max_length=50)
phone = models.CharField(blank=True, null=True, max_length=12)
def __unicode__(self):
return '%s' % self.user
Here is my registration form:
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'Username'))
email = forms.EmailField(label=(u'Email'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = UserProfile
exclude = ('user',)
fields = ('username', 'email', 'password', 'password1')
def clean_email(self):
email = self.cleaned_data['email']
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError("User with same email already exist, please change your email")
And here is view of my registration form:
def UserProfileRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'])
user.save()
user_profile = UserProfile(user=user)
user_profile.save()
return HttpResponseRedirect('/profile/')
else:
return render(request, 'profiles/registration.html', {'form':form})
else:
form = RegistrationForm()
context = {'form':form}
return render (request, 'profiles/registration.html', context)
In user profile i create modelform where user can fill the fields from UserProfile model:
class ExtraProfileDataForm(ModelForm):
name = forms.CharField(label=(u'Enter your name'))
surname = forms.CharField(label=(u'Enter your surname'))
phone = forms.CharField(label=(u'Enter your phone'))
birthday = forms.DateField(label=(u'Enter birthday'))
avatar = forms.ImageField(label=(u'Enter avatar'))
class Meta:
model = UserProfile
fields = ('name', 'surname', 'phone', 'birthday', 'avatar')
def __init__(self, *args, **kwargs):
super(ExtraProfileDataForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
This is the view of the model form:
#login_required
def UserFullDataForm(request):
if request.method == 'POST':
form = ExtraProfileDataForm(request.POST)
if form.is_valid():
profile_user = request.user
user_profile = UserProfile(user=profile_user)
user_profile.name = form.cleaned_data['name']
user_profile.surname = form.cleaned_data['surname']
user_profile.phone = form.cleaned_data['phone']
user_profile.birthday = form.cleaned_data['birthday']
user_profile.avatar = form.cleaned_data['avatar']
user_profile.save()
return HttpResponseRedirect('/profile/')
else:
return render(request, 'profiles/extra_profile.html', {'form':form})
else:
form = ExtraProfileDataForm()
context = {'form':form}
return render (request, 'profiles/extra_profile.html', context)
But when I fill this form I got the error:
duplicate key value violates unique constraint "profiles_userprofile_user_id_key" DETAIL: Key (user_id)=(23) already exists.
On the traceback i see that error in this line user_profile.save(). As i understand it happens because this script create new item with same id but not update it. What i have to change on my code to update existing item but not to create. Thank you.
You need to use get_or_create, which will return an existing item if it was found; otherwise create a new instance of the model.
In your user profile update view:
user_profile, created = UserProfile.objects.get_or_create(user=profile.user)
Now, instead of creating a new profile each time - you are updating if a profile for that user already exists.