The meaning of objects in Django - python

def signup(request):
if request.method == 'POST':
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.get(username=request.POST['username'])
return render(request, 'accounts/signup.html', {'error':'Username has already been taken'})
except User.DoesNotExist:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
login(request, user)
return render(request, 'accounts/signup.html')
else:
return render(request, 'accounts/signup.html', {'error':'Passwords didn\'t match'})
else:
return render(request, 'accounts/signup.html')
In the following program, the line
user = User.objects.get(username=request.POST['username'])
is confusing me in some point. I know that if I have the dictionary d = {word1 : definition1, word2 : definition2}, then d.get[word1] will output definition1 (the id of word1). So User.objects is a dictionary, because of the structure dict.get(). I have a little problem with this part of the line.
Could anyone be able to explain to me what is the meaning of objects?
Thanks in advance!

objects is a reference to the model's Manager, whos sole purpose is to handle the database queries to retrieve the required data from a database.
Although it has a method get that shares the same name as the get method of a dictionary, they do not do the same thing internally in respect to where the data is retrieved from.

Related

Django show error in form that comes from another function

I am trying to post a ModelForm, but after the is_valid() function, I run another validation coming from another function.
What I want to do is, if the result of the other function is false, the form should raise an error, above the form as in the case "your password cannot be the same".
Since the function runs during the process, I cannot use a clean method in model.
Thanks in advance!
function
def somefunction():
.
.
print ("NOT WORKING")
return False
views.py
def index(request):
form = SomeForm(request.POST)
if request.method == "POST":
if form.is_valid():
if somefunction() == True:
form.save()
return HttpResponseRedirect("/contact/")
else:
form
else:
form
return render(request, "home.html", {'form': form})
You can use add_error method to add error to form manually like this.
form.add_error('<FIELD_NAME>)', 'your password cannot be the same')
But I suggest you to override clean method of form instead.

Why calling method inside views.py after successful submission of forms doesn't clear the form?

Views.py
def form_name_view(request):
form = FormName()
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
return render(request, 'first_app/form_page.html', {'form': form})
When I use HttpResponseRedirect to get back to my index page, then everything works correct, but the concern is if I use calling index method instead of HttpResponseRedirect then the behavior is a little bit insane:
After reaching index page if I hit refresh then alert appears says:
The page that you're looking for used information that you entered.
Returning to that page might cause any action you took to be
repeated. Do you want to continue?
If i want to get back to the same form page, by calling that same method again like
return form_name_view(request)
The new form is already filled with previous inserted data, with the message on the form
Topic with this Topic name already exists.
The question is what is the reason, calling method results like this?
def form_name_view(request):
if request.method == "POST":
form = FormName(request.POST)
if form.is_valid():
form.save(commit=True)
return HttpResponseRedirect('/') # return index(request)
else:
print('INVALID FORM INPUTS')
else:
form = FormName()
return render(request, 'first_app/form_page.html', {'form': form})
use this

Django - didn't return an HTTPResponse Object

Sorry if my english is bad, but if you need question, i'm here :)
I saw many answers about this subject of HttpResponse object in Django, but i can't resolve it.
Normally the user insert his email address in order to recieve an email for his new password.
def forgottenPwdEmail(request):
if request.method == 'POST':
form = PasswordResetRequestForm(request.POST)
user = User.objects.get(username=request.user.username)
user.confirmed = True
user.save()
sendResetPasswordMail(user, request.META['HTTP_HOST'])
else:
form = PasswordResetRequestForm()
return render(request, 'front/reset_password_form.html', {'form': form})
After these error is displayed : "View" didn't return an HttpResponse object. It returned None instead. I can recieve the mail anyway, so the problem is in this function but i can't resolve it.
If you have some ideas, i am open :)
You are missing a return in your if statement.
def forgottenPwdEmail(request):
if request.method == 'POST':
form = PasswordResetRequestForm(request.POST)
user = User.objects.get(username=request.user.username)
user.confirmed = True
user.save()
return sendResetPasswordMail(user, request.META['HTTP_HOST'])
else:
form = PasswordResetRequestForm()
return render(request, 'front/reset_password_form.html', {'form': form})
I am assuming that the sendResetPasswordMail is also returning a HttpResponse
Hope this helps
It is happening because your view doesn't return a response for a POST request.
You should add something like redirect page when the email is successfully sent, something like this:
def forgottenPwdEmail(request):
if request.method == 'POST':
form = PasswordResetRequestForm(request.POST)
user = User.objects.get(username=request.user.username)
user.confirmed = True
user.save()
sendResetPasswordMail(user, request.META['HTTP_HOST'])
return redirect('/password-reset-email-sent/')
......

Django view doesnt seems to have any request object

I am trying to get request.user but even printing request doesn't works.But nothing is printing
view.py
def flower_add(request):
print request
print request.method
if request.method == 'POST':
print 'xxxx'
form = FlowerAddForm(request.POST)
if form.is_valid():
print "form is is_valid"
form.save()
context= {'form':FlowerAddForm()}
return render(request, 'farmer/flower_add.html',context)
else:
form = FlowerAddForm()
return render(request, 'farmer/flower_add.html', {
'form': form,
})
Your view here may be working but you likely won't get any output to the console using print in the manner you are using it.
Try calling print() as a function with request explicitly passed.
Also, print() is ideal for string objects (as well as int, etc) but no so much for more complex types such as dictionaries, lists and other structured objects.
Try using pprint() instead:
pprint(request)
print(request.method)
https://docs.python.org/2/library/pprint.html

Django self.cleaned_data not working

I'm new to the technology, so I apologyze in advance if the question is too simple.
I'm using self.cleaned_data to get the selected data entered by the user. And it works when clean is called, but not on my save method.
Here is the code
Forms.py
def clean_account_type(self):
if self.cleaned_data["account_type"] == "select": # **here it works**
raise forms.ValidationError("Select account type.")
def save(self):
acc_type = self.cleaned_data["account_type"] # **here it doesn't, (NONE)**
if acc_type == "test1":
doSomeStuff()
Any ideas why that's not working when I call save?
Here is my views.py
def SignUp(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
Thanks in advance.
The clean_<field_name methods on the form must return the clean value or raise a ValidationError. From the docs https://docs.djangoproject.com/en/1.4/ref/forms/validation/
Just like the general field clean() method, above, this method should
return the cleaned data, regardless of whether it changed anything or
not.
The simple change would be
def clean_account_type(self):
account_type = self.cleaned_data["account_type"]
if account_type == "select":
raise forms.ValidationError("Select account type.")
return account_type

Categories

Resources