creation of the profile editing view - django

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)

Related

clean method not called in modelform

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})

AttributeError at /basic_app/register/ : 'tuple' object has no attribute 'get'

I know this question have been asked alot and most of the time its due to render or HttpResponse in the views.py, i double checked mine but the code looks good to me, dont know where the problem is.
This is a views.py file for a very basic django form but i can't get it to work
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data = request.POST)
profile_form = UserProfileInfoForm(data = request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_from.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit = False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
return (user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request,'basic_app/register.html',{'user_form': user_form,
'profile_form':profile_form,
'registered':registered})
You can not return (user_form.errors, profile_form.errors), since that is not a HttpResponse object. What response should the server return in that case.
Usually in case the form is invalid, the server will rerender the content. The form will, if you render it properly display the errors.
Note that in case the POST request was successful, you usually should redirect to implement the Post/Redirect/Get pattern [wiki]. You furthermore probably want to use a UserCreationForm [Django-doc]. This will set the password of the user in the correct way (with .set_password(..)), and run a password validator if you configured this.
You thus can rewrite your view as follows, but you probably should replace UserForm with UserCreationForm:
from django.shortcuts import redirect
def register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_from.save(commit=False)
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
return redirect('name-of-view')
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(
request,
'basic_app/register.html',
{'user_form': user_form, 'profile_form':profile_form })

Convert function view to class based view

I am trying to write a a Function-based View (FBV) as a Class-based View (CBV), specifically a CreateView. So far I have been able to write the FBV as a generic View but not as a CreateView. How would I go about doing this?
FBV
def register(request):
registered = False
if request.method == 'POST':
user_form = UserCreationForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserCreationForm()
return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})
Converted View
class RegisterView(View):
def get(self, request):
registered = False
user_form = UserCreationForm()
return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})
def post(self, request):
registered = False
user_form = UserCreationForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})
You may follow it
class RegisterView(CreateView):
model = User
form_class = UserCreationForm
template_name = 'accounts/registration.html'
def post(self, request, *args, **kwargs):
registered = False
user_form = UserCreationForm(data=request.POST)
if user_form.is_valid():
user = user_form.save(commit=False)
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
return render(request,'accounts/registration.html', {'user_form':user_form, 'registered':registered})

Django ModelForm exclude data saving

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})

Form not updating values , validation fails but no errors

I have a profile updation form , i have passed the data and instance to the form but the validation fails The scenarios are as follows .
This form is for profile updation , but the validation fails without showing any errors.
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
def clean(self):
return self.cleaned_data
the view is as follows
> The form.is_valid always returns False.
def user_profile(request, params={}):
if request.user.is_staff==False:
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
profile_form = ProfileEditForm(request.POST, instance=profile)
print profile_form.is_bound
print profile_form.is_valid()
if profile_form.is_valid():
profile = profile_form.save()
else:
pass
else:
profile_form = ProfileEditForm( instance=profile)
profile_form = ProfileEditForm( instance=profile)
params['profile_form'] = profile_form
return render_to_response('vec/profile.html', params, context_instance=RequestContext(request))
else:
return render(request, 'base.html')
The following are the outputs :
print profile_form.is_bound - returns True and
print profile_form.is_valid() returns False .Also no erros in {{ profile_form.errors }} {{ profile_form.non_field_errors }}
Appreciate your reply...
Thanks in advance ...
You are resetting profile_form before sending it to template, due to which no errors are shown.
See comments below
def user_profile(request, params={}):
if request.user.is_staff==False:
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
profile_form = ProfileEditForm(request.POST, instance=profile)
print profile_form.is_bound
print profile_form.is_valid()
if profile_form.is_valid():
profile = profile_form.save()
else:
pass
else:
profile_form = ProfileEditForm( instance=profile)
# don't do this, you already have profile_form
#profile_form = ProfileEditForm( instance=profile)
params['profile_form'] = profile_form
return render_to_response('vec/profile.html', params, context_instance=RequestContext(request))
else:
return render(request, 'base.html')
I figured out ...
I just included the fields in the form definition
fields = ('','',)
Thanks.