As written in the title, the form gets validated whatever happens, I don't understand why are my clean and clean_ methods are not called. Used forms for quite some time but here I am puzzled on what I am forgetting.
Thanks
simplified forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ["workcity", "post_address", "billing_address", "country", "phone"]
def clean(self):
#not called
cleaned_data = super().clean()
billing_address = cleaned_data.get('billing_address')
post_address= cleaned_data.get('post_adress')
if not billing_address == post_address:
do some raising validation error
def clean_workcity(self, *args, **kwargs):
#not called
workcity= self.cleaned_data.get("workcity")
if xxx:
do some raising validation error
return workcity
simplified views.py
def profileform(request):
if request.method =='POST':
form = ProfileForm(request.POST)
if form.is_valid():
form.instance.user = request.user
form.save()
messages.success(request, 'Profile created successfully')
return redirect('profile')
else :
handle errors
else:
form = ProfileForm()
return render(request, "CORE/home.html", {"form": form})
Related
This is my code for my view:
def edit(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
else:
if form.is_valid():
user = form.save()
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
And here is the code for the form:
class EditProfileForm(UserChangeForm):
edit ='social/edit.html'
class Meta:
model = UserProfile
fields = ('description', 'image')
Here is the model:
class UserProfile(models.Model):
description = models.CharField(max_length=300, default=' ', blank=True)
image = models.ImageField(upload_to='profile_image', blank=True)
if you need any more information to help I would be more than gladly to give it to you
The problem is with the view function.
Every View must return some sort of response (HTTP Response in General)
you have an if else statement in your view if its a post it will just execute
form = EditProfileForm(request.POST, instance=request.user)
and then it doesn't return anything.
I think you have to do is,
For GET Request (when you visit the url, it has to render the form)
if request.method == 'GET':
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
For POST request (when you send POST to this view or different one)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
user = form.save()
# use render/redirect as needed. make sure it returns an HTTP Response
# note that render method also return HTTP Response
return HttpResponse('Done')
Make sure Form class is simply this
class EditProfileForm(UserChangeForm):
class Meta:
model = UserProfile
fields = ('description', 'image')
hello everyone it's been a while since I haven't coded but I noticed some pref changes so I have some problem with the profile application edited the profile my code
views
#login_required
def edit_profile(request):
if request.method =='POST':
user_form =UserEditForm(data=request.POST or None, instance=request.user)
profile_form=ProfileEditForm(data=request.POST or None, instance=request.user.profile ,files =request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
else:
user_form=UserEditForm(instance=request.user)
profile_form=ProfileEditForm(instance=request.user.profile)
context ={
'user_form':user_form,
'profile_form':profile_form,
}
return render(request,'accounts/edit_profile.html',context)
form
class UserEditForm(forms.ModelForm):
class Meta:
model=User
fields=('username', 'email')
class ProfileEditForm(forms.ModelForm):
class Meta:
model=Profile
fields=('description', 'image')
another try to see the same error
form
class EditProfileForm(UserChangeForm):
class Meta:
model=User
fields=('username', 'email')
view
#login_required
def edit_profile(request):
if request.method =='POST':
form= EditProfileForm(request.POST,instance=request.user)
if form.is_valid():
form.save()
return redirect("/profile/")
else:
form=EditProfileForm(instance=request.user)
args={'form': form}
return render(request,'accounts/edit_profile.html',args)
error
The view accounts.views.edit_profile didn't return an HttpResponse object. It returned None instead.
As the error says the view did not return a response.
Your return render... was indented under your POST method:
#login_required
def edit_profile(request):
# You need to define these before the POST method
user_form=UserEditForm(instance=request.user)
profile_form=ProfileEditForm(instance=request.user.profile)
if request.method =='POST':
user_form =UserEditForm(data=request.POST or None, instance=request.user)
profile_form=ProfileEditForm(data=request.POST or None, instance=request.user.profile ,files =request.FILES)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
# I would return a success message here
else:
# Inform the user their form was not valid
context = {
'user_form':user_form,
'profile_form':profile_form,
}
return render(request,'accounts/edit_profile.html',context)
I have my response form and view like this
class ResponseForm(ModelForm):
class Meta:
model = ResponseModel
exclude = ('author', 'title','submit_count')
# help_texts = {
# 'ans1': user.q1.value,
# }
#login_required
def ResponseFormView(request):
if request.method == "POST":
form = ResponseForm(request.POST)
if form.is_valid():
submission = form.save(commit=False)
submission.author = request.user
submission.save()
return render(request, 'thanks.html', {})
else:
form = ResponseForm()
return render(request, 'response_tem.html', {'form': form})
I want the help text for 'ans1' field to be the value of q1 field of request.user. How do I do it?
You can do it like this:
class ResponseForm(ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None) # popping user from known arguments
super(ResponseForm, self).__init__(*args, **kwargs)
if user:
self.fields['ans1'].help_text = "Help Text for {}".format(user.username)
class Meta:
model = ResponseModel
exclude = ('author', 'title','submit_count')
#login_required
def ResponseFormView(request):
if request.method == "POST":
form = ResponseForm(request.POST)
if form.is_valid():
submission = form.save(commit=False)
submission.author = request.user
submission.save()
return render(request, 'thanks.html', {})
else:
form = ResponseForm(user=request.user) # passing user as known argument
return render(request, 'response_tem.html', {'form': form})
Here, in the view I am passing the request.user as known argument when I am initiating Form Class's Object (marked with comment). Then in the Form, I am catching the user sent from view and updating the field's help text.
Trying to save data with login user. Tried as below.
models.py
class MyModel(TimeStamped):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=250)
forms.py
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
exclude = ['user']
views.py
def add(request):
if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=False)
form.save()
messages.success(request, 'Message Sent Successfully')
redirect('home')
return render(request, "add.html", {'form': form})
It saved data. But problem is user is not setting to login user. Tried adding in view form.user = request.user. still is not saving.
Try this.
def add(request):
if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
messages.success(request, 'Message Sent Successfully')
redirect('home')
return render(request, "add.html", {'form': form})
I have a strange issue when saving a model form. I have a form, which consists of two model forms and I am trying to save them at the same time. For clarity, below is my code
Views.py
def create_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
my_user_form = MyUsersForm(request.POST)
if user_form.is_valid() and my_user_form.is_valid():
us = user_form.save()
my_us = my_user_form.save(commit=False)
my_us.user = us
my_us.save()
return HttpResponse('You have successfully created a user')
else:
return HttpResponse(' My_user_form is not validated')
else:
user_form = UserForm()
my_user_form = MyUsersForm(user=request.user)
return render(request, 'create_user.html', {'user_form': user_form, 'my_user_form': my_user_form})
my_user_form is not validated when I override the init method of MyUsersForm to filter the queryset of the foreign key(created_by) but when I don"t filter the queryset, my_user_form is validated and the form is saved.
What I don't understand is when I don"t filter the query set how come my_user_form is validated?
The data which is sent via the request.post to my_user_form is somehow lost (when I filter the queryset). any clue in the right direction is highly appreciated. Thank you for your valuable inputs.
Forms.py
class MyUsersForm(ModelForm):
class Meta:
model = MyUsers
fields = ['created_by', ]
def __init__(self, user=None, **kwargs):
super(MyUsersForm, self).__init__(**kwargs)
if user is not None:
self.fields['created_by'].queryset = User.objects.filter(username=user)
Models.py
class MyUsers(models.Model):
user = models.OneToOneField(User, blank=True, null=True)
created_by = models.ForeignKey(User, related_name="created_by", blank=True, null=True)
def create_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
my_user_form = MyUsersForm(request.POST)
if user_form.is_valid() and my_user_form.is_valid() and User.objects.filter(username=request.POST.get('user')).exists():
us = user_form.save()
my_us = my_user_form.save(commit=False)
my_us.user = us
my_us.save()
return HttpResponse('You have successfully created a user')
else:
return HttpResponse(' My_user_form is not validated')
else:
user_form = UserForm()
my_user_form = MyUsersForm(user=request.user)
return render(request, 'create_user.html', {'user_form': user_form, 'my_user_form': my_user_form})
why my_user_form is not validated and saved. instead of modifying the queryset in the init i did it in the view itself using the statement
my_user_form.fields['created_by'] = forms.ModelChoiceField(User.objects.filter(username=request.user))
and this solves my problem. but i still don't know why it didn't work in the init method of the MyUsersForm?.