Can't update user profile in my Django app Django - python

I have created a Edit Profile form in my Django app but it doesn't save in the database.
This is the profile model:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile', primary_key=True) #Each User is related to only one User Profile
city_search_text = models.CharField(blank=True, max_length=300)#user picks a city from autocomplete and in the view I get or create a City object
city = models.ForeignKey(City, blank=True, null=True, related_name='city') #Each User Profile must be related to one city.
prof_pic = models.ImageField(blank=True, upload_to='profile_pictures')
dob = models.DateField(blank=True, null=True)
def __str__(self):
return self.user.first_name
This is the form:
class EditProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('dob',)#I'm testing to update this field only
def save(self, commit=True):
profile = super(EditProfileForm, self).save(commit=False)
if commit:
profile.save()
return profile
This is the view:
def editprofile(request):
if request.method == 'POST':
edit_profile_form = EditProfileForm(request.POST, instance=request.user)
if edit_profile_form.is_valid():
profile = edit_profile_form.save(commit=False)
profile.save()
if 'next' in request.GET:
return redirect(request.GET['next'])
else:
print (profile_form.errors)
else:
edit_profile_form = EditProfileForm(instance=request.user.profile)
return render(request, 'excurj/editprofile.html', {'edit_profile_form':edit_profile_form,})
After I submit the form it forwards me to index page okay but the values remain the same in the user's profile.

Seems like
if edit_profile_form.is_valid():
isn't getting called at all, and your data is not saved. That means your form has invalid data, and you should check for form errors to detect those.
Also, you are trying to print form errors if the request isn't POST, which makes no sense and won't help you printing form errors. Try using this way;
if edit_profile_form.is_valid():
profile = edit_profile_form.save(commit=False)
profile.save()
else:
print (profile_form.errors)
And check your form for errors.

I figured it out eventually. In the view I should have passed an instance of the profile not the User object. So it needs to be like this:
edit_profile_form = EditProfileForm(request.POST, instance=request.user.*profile*)

Related

How to automatically get user in django admin through form

I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves.
Here's the model.py file:
class Requestpayment (models.Model):
username= models.ForeignKey(User, on_delete= models.CASCADE, null=True)
useremail= models.CharField(max_length=100)
accountmail= models.CharField(max_length=100)
accountphonenumber=models.CharField(max_length=15)
coinsrequested=models.ForeignKey(Requestamount, on_delete= models.SET_NULL, null=True)
created= models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.accountmail
the forms.py:
class Requestpaymentform (ModelForm):
class Meta:
model = Requestpayment
fields = '__all__'
and the views.py:
#login_required(login_url='login')
def redeemcoins (request):
form = Requestpaymentform
if request.method =='POST':
form = Requestpaymentform(request.POST)
if form.is_valid():
form = form.save(commit=False)
username = request.user
form.save()
return redirect ('home')
I am pretty sure something is wrong but i don't know what it is (I'm very new at django) anyway the form always shows all the users in the website for the current user to pick who they are.
redeem coins page
I also tried excluding that part of the form but it didn't work it just shows up empty in the admin.
thank you.
You need to assign it to the instance wrapped in the form, so:
#login_required(login_url='login')
def redeemcoins(request):
form = Requestpaymentform()
if request.method == 'POST':
form = Requestpaymentform(request.POST)
if form.is_valid():
form.instance.username = request.user
form.save()
return redirect('home')
# …
It makes more sense however to name this field user than username. In the model you can also make the username field non-editable, such that it does not appear in the form:
from django.conf import settings
class Requestpayment(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, editable=False, on_delete=models.CASCADE
)
# …
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
When you use username= models.ForeignKey(User, on_delete= models.CASCADE, null=True), Django add a field named user_id in your database which allow django to find User object for Requestpayment.
You can use user_id field to add a User object in Requestpayment.
You don't need to pass username field in your fields list if you want to get user in view.
class Requestpaymentform (ModelForm):
class Meta:
model = Requestpayment
#fields = '__all__'
fields = ['useremail',
'accountmail',
'accountphonenumber',
'coinsrequested',
'created']
Now do this to get user in your view.
#login_required(login_url='login')
def redeemcoins(request):
form = Requestpaymentform()
if request.method == 'POST':
form = Requestpaymentform(request.POST)
if form.is_valid():
requestpayment = form.save(commit=False)
requestpayment.user_id = request.user.id
requestpayment.save()
return redirect('home')
And it's great to use user instead username because it's a User object and not a simple field.
Please for my English !!!

Save form as foreign key's object

There is 2 models with a ForeignKey Relationship, Profile model and Article model, I would like to save the connected user as profile.user when an Article object is created.
Here is the error I get with the code below :
'NoneType' object has no attribute 'user'
models.py :
class Profile(models.Model):
name = models.CharField(max_length=120)
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
class Gig(models.Model):
profile = models.ForeignKey(Profile, null=True)
title = models.CharField(max_length=100, unique=True)
Here is my view for where I want to save profile.user
if request.method == 'POST':
form = GigForm(request.POST, request.FILES)
if form.is_valid():
save_it = form.save()
save_it.profile.user = request.user #error occured here.
save_it.save()
return redirect(reverse('own_gigs_details'))
else:
form = GigForm()
Forms.py
class GigForm(forms.ModelForm):
class Meta:
model = Gig
fields = ['title', 'image', 'body', 'price']
What am I doing wrong ?
When you first create a Gig by saving the form, there is no profile linked to it (because it wasn't declared in your form). So, your error occurs because save_it.profile has no value.
I think you are trying to link a Gig to the Profile of the user logged in. To do this, I think you can do
save_it.profile = request.user.profile
save_it.save()
instead of assigning the user itself.
OneToOneField lets you reference objects in both directions. So you can do user.profile and profile.user.

Save data in associative model using one query in django

I am working on registration module in django project. for registering user i am using auth_user table for extending this table i have created one more model Profile
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
start_date = models.DateField()
phone_number = models.CharField(max_length=12)
address = models.CharField(max_length=225)
subscription = models.BooleanField(default=False)
Profile table has been created successfully. Now what i want to do is when i submit the registration form, the fields related to Profile model within registration form should be inserted automatically after inserting fields related to auth_user model.
Means i don't want to first insert data in auth_user model and then after getting it's id again insert data in Profile table.
I want to insert complete record in one query. Is it possible ?
I think you can define a registration form and override the form save method to save the Profile when creating the User model. Sample code for your reference:
class RegistrationForm(forms.ModelForm):
start_date = forms.DateField()
phone_number = forms.CharField()
address = forms.CharField()
subscription = forms.BooleanField()
class Meta:
model = User
def save(self, commit=True):
instance = super(RegistrationForm, self).save(commit=commit)
profile = Profile(user=instance, start_date=self.cleaned_data['start_date'], phone_number=self.cleaned_data['phone_number'], address=self.cleaned_data['address'], subscription=self.cleaned_data['subscription'])
profile.save()
return instance
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
# do anything after user created
else:
raise Error('form validate failed')
else:
# handling the GET method

Django 1.9 using django sessions in two page forms

How can I use Django sessions to have a user be able to start a form on one page, and move to the next page and have them complete the form?
I have looked into pagination and wizard forms, but I don't get them at all.
When I have one page with a small portion of a model I'm using - in forms - and another page with the rest of the model - forms.py with the rest of the model info - I can use the first form perfectly.
But when I move to the next page, I get an error saying (1048, "Column 'user_id' cannot be null").
My best guess is to use Django sessions to fix this issue. I don't want the user to have to put in their username and password a second time to get this to work. Any ideas?
my models/forms.py:
class Contact(models.Model):
user = models.OneToOneField(User)
subject = models.CharField(max_length=100, blank=True)
sender = models.EmailField(max_length=100, blank=True)
message = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.user.username
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = Contact
fields = ('username', 'password', 'email')
class ContactForm1(forms.Form):
class Meta:
model = Contact
fields = ('subject', 'sender')
class ContactForm2(forms.Form):
message = forms.CharField(widget=forms.Textarea)
class Meta:
model = Contact
fields = ('message',)
views:
def contact(request):
registered = False
if request.method =='POST':
user = UserForm(request.POST)
contact = ContactForm1(request.POST)
if user.is_valid() and contact.is_valid():
user = user.save()
user.set_password(user.password)
user.save()
contact = contact.save(commit=False)
contact.user = user
registered = True
return render(request, 'mysite/contact.html', {'user': user, 'contact': contact, 'registered': registered})
def contact_second(request):
if request.method =='POST':
contact = ContactForm2(request.POST)
if contact.is_valid():
contact = contact.save(commit=False)
contact.save()
return render(request, 'mysite/contact_two.html', {'contact': contact}
I think it's a good idea to use sessions to store the forms because you don't want on each page to store the user input into the database because what if s/he change mind in the 3rd page and s/he wants to discard the registration or whatever it is?
I think is better to store the forms in session until you get in the last page, you ensure that everything is valid and then save the data in the database.
So let's say that the bellow code is in one of the view that will serve the first form/page. You retrieve the data from the POST request and you check if the given data are valid using the form.is_valid(), you then store the form.cleaned_data (which contains the user's validated data) to a session variable.
form = CustomForm(request.POST)
...
if form.is_valid():
request.session['form_data_page_1'] = form.cleaned_data
Note here that you may need to add code to redirect the user to the next page if form.is_valid() is true, something like this:
if form.is_valid():
request.session['form_data_page_1'] = form.cleaned_data
return HttpResponseRedirect(reverse('url-name-of-second-page'))
Then in any other view let's say in the view that is going to serve the second page you can retreive the from data from the first page like this:
first_page_data = request.session['form_data_page_1']
And you can do whatever you want with them as if it was after you executed the form.is_valid() in the first view.

Django : Filter, limit and display file filed dynamicly with generic inlineformset

I need your help, because I'm stuck in a project with no idea about how to continue.
I need to implement a simple "generic" document management app to integrate it in my project. I can have many kind of documents that are defined by "utilisation_type" in "DocumentType" model.
At the end, I need to display a page with an inline form, with only one of each "DocumentType" with (in this case) "utilisation_type"= "USER".
Like this, the user will get, for exemple, a page with 3 buttons, each button corresponding to only one DocumentType with "utilisation_type"= "USER" and he will be able to upload only one of each requested document.
Here are my models :
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
UTILISATION_TYPE_CHOICES = (
("USER", _(u"User")),
("PROJECT", _(u"Project")),
("TEAM", _(u"Team")),
("ALL", _(u"All")),
)
class DocumentType(models.Model):
document_type = models.CharField(max_length=40, choices=DOCUMENT_TYPE_CHOICES)
title = models.CharField(_(u'Titre'), max_length=255, blank=False, null=True)
utilisation_type = models.CharField(max_length=15, choices=UTILISATION_TYPE_CHOICES)
class Document(models.Model):
document_type = models.ForeignKey(DocumentType)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
document = models.FileField(_(u"Document"), upload_to='upload/documents', null=True, blank=True)
class MyUserManager(BaseUserManager):
first_name = models.CharField(_(u'Firstname'), max_length=90, blank=False)
last_name = models.CharField(_(u'Lastname'), max_length=90, blank=False)
Here is my view :
#login_required
def documents(request):
"""
User's documents edition
"""
user = request.user
DocumentInlineFormSet = generic_inlineformset_factory(Document)
if request.method == 'POST':
formset = DocumentInlineFormSet(request.POST, request.FILES, instance=user)
if formset.is_valid():
formset.save()
messages.success(request, _(u'Profil updated'), fail_silently=True)
return redirect('users.views.documents')
else:
formset = DocumentInlineFormSet(instance=user)
return render_to_response('users/user_documents.html', {'formEditDocumentFormset': formset,}, context_instance=RequestContext(request))
I hope I've been clear enough in my explanation. Do not hesitate to ask more details if needed.
I think the most simple way is to check the type of every single document on it's saving. if you allow to save each doctype only once you will get only different doctypes for each user. In that case you do not need to use double filtering or whatever.
You can rewrite the save() method for each form in a formset by creating your CustomInlineFormSet. Here is the link: https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#overriding-methods-on-an-inlineformset.
It could be smth like this for example:
from django.forms.models import BaseInlineFormSet
class DocumentInlineFormSet(BaseInlineFormSet):
def clean(self):
super(DocumentInlineFormSet, self).clean()
for form in self.forms:
document = form.save(commit=False)
#check your document here
document.save()

Categories