How to write a Django message into your views code - python

I'm reading the documentation on how to display a message to the user with Django messages. It says that in order to add a message in your views to call:
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
I'm not sure where to put the second the second line, this is my view:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
return HttpResponse('Thank you')
else:
return HttpResponse('That text is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
I want the message to appear and thank the user for signing up and display their input as well.

Bearing, in mind that it's customary to redirect to a success url on valid form submission, your code ought to look like this:
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
ID = post.id_text
messages.add_message(request, messages.INFO, 'Hello world.')
return HttpResponseRedirect('/thank-you-page/')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
note that this also results in the user being told why exactly his form is invalid (assuming that you have set up the template propertly). It's always good to say what the problem is rather than to say there is a problem.

You can put the second line in view with example:
def contact(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
textarea = request.POST.get('textarea')
contact = Contact(name = name,email = email,password = password,textarea = textarea,date=datetime.today())
contact.save()
messages.success(request, 'Form has submitted')
return render(request,"contact.html")

Related

how to assign a value to new user in django

i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and i have tried diffrent solutions to fix this
views.py
def register(request):
reviews = Review.objects.filter(status='published')
info = Announcements.objects.all()
categories = Category.objects.all()
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
obj = request.user
get_membership = Membership.objects.get(membership_type='Free')
# error is showing "instance" is not access using visual studio code
instance = UserMembership.objects.create(user=obj, membership=get_membership)
messages.success(request, f'Account Successfully created for {username}! You can Login In Now')
return redirect('userauths:login')
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
context = {
'reviews': reviews,
'form': form,
'info': info,
'categories': categories
}
return render(request, 'userauths/register.html', context)
indentation error here:
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()
You only need to tab once. Not twice.
elif request.user.is_authenticated:
return redirect('elements:home')
else:
form = UserRegisterForm()

when i refresh the page the form data automatically adding due to GET method when i remove it it show doesn't return httpresponse obj

how can i use is_valid() with POST method to get inputs from user
my views.py i also use return redirect() and HttpResponseRedirect() but it doesn't work
#login_required
def about(request):
data= userdata.objects.all()
form=student(request.POST)
if request.method =='POST' or 'GET':
if form.is_valid():
name = request.POST.get('name')
email= request.POST.get('email')
password =request.POST.get('password')
fm = userdata(name=name,email=email,password=password)
fm.save()
form =student()
else:
form=student()
return render(request,'about.html',{'form':form ,'data':data})
try the code below
#login_required
def about(request):
# i think you don't need 'data' and thus pass it in the context with 'form'
# data= userdata.objects.all()
if request.method =='POST': # POST request
form=student(request.POST)
if form.is_valid():
name = request.POST.get('name')
email= request.POST.get('email')
password = request.POST.get('password')
fm = userdata(name=name,email=email,password=password)
fm.save()
# Add flash message and then redirect
messages.success(request, 'SUCCESS !')
return redirect(reverse_lazy('home'))
else:
messages.error(request, 'Please correct the errors below.')
# if 'form.is_valid()' return false you will get all errors in 'form.errors' bag
else: # GET request
form=student()
return render(request,'about.html',{'form':form})
refer to :
https://docs.djangoproject.com/fr/3.1/topics/forms/#the-view
https://www.django-antipatterns.com/antipatterns/rendering_content_after_a_successful_post_request.html

how can i restrict users to some specific urls

I want to restrict users to access the payment and checkout pages by typing the url in address bar like "home/shop/checkout/" and "home/shop/payment/"
I want to make these pages accessible only if either buy_now form is valid or items_buy_now form is valid
urls.py
path('payment/',views.payment,name='payment'),
path('checkout/', views.checkout, name="checkout"),
views.py
def checkout(request):
request.session.pop('data', None)
messages.success(request,'Done.Thanks for using our services.')
return redirect("shop:mycart")
def payment(request):
return render(request,'shop/payment.html')
def buy_now(request,slug):
if not request.user.is_authenticated:
messages.info(request, 'You have to logged in first.')
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
product = Product.objects.get(active=True, slug=slug)
if request.method == "POST":
form = BuyerDeliveryForm(request.POST)
if form.is_valid():
buyer = form.save(commit=False)
buyer.save()
return redirect('shop:payment')
else:
form = BuyerDeliveryForm()
return render(request, 'shop/delivery_form.html', {'form': form, 'products': product})
def items_buy_now(request):
if not request.user.is_authenticated:
messages.info(request, 'You have to logged in first.')
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
if request.method == "POST":
form = BuyerDeliveryForm(request.POST)
if form.is_valid():
buyer = form.save(commit=False)
buyer.save()
return redirect('shop:payment')
else:
form = BuyerDeliveryForm()
return render(request, 'shop/delivery_form.html', {'form': form})
The best way to do it is to :
Create a Mixin that manager either items_buy or items_buy
For all the views that have to handle the restriction, subclass it from the respective mixin.
In the get function of the subclass call the method to check if the user has the authorization to access to that page.

How to solve the did not return httpresonse error with django?

I have a problem in registration with django, here is my views code:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)
,but i always get:
ValueError at /user/register/ The view Users.views.register didn't
return an HttpResponse object. It returned None instead. Request
Method: POST Request URL: http://127.0.0.1:3001/user/register/ Django
Version: 2.0.2 Exception Type: ValueError Exception Value: The view
Users.views.register didn't return an HttpResponse object. It returned
None instead. Exception
Location: /home/iah/.local/lib/python3.5/site-packages/django/core/handlers/base.py
in _get_response, line 139
Check you code and ask yourself what happens if you have a POST request and the form doesn't validate - you'll find out that in this case you have no explicit return path, so the function implicitely returns None.
The fix is dead simple : deindent the last two line of your function, so you when the form doesn't validate you return the rendered template too:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
form = RegistrationForm()
# MAKE SURE WE ALWAYS RETURN A RESPONSE:
# we end up here when it's a GET request
# AND when it's a POST request and the form
# did not validate
args = {'form': form}
return render(request, 'users/reg_form.html', args)
You have to return response from the inner else block:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
# here
...
Make sure you return something if the form is not valid and your form.is_valid() fails.
Example:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/') # or render(...)/whatever you need to redirect to
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)
Hope this helps!
You are missing the else code. Your if statement says: If the form is valid, save the form. But what if the form is not valid, What if the username is all special characters(ex: !##$%%%^^) or what if the username is only 1 Character long ex: (username:A). Or what if the password is only 3 characters long (ex: pas) In all these scenarios, the user should get the blank form back. You should also consider using class based views for registration This link will help
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
**if form.is_valid():**
# What if the form is not valid you haven't accounted for that
form.save()
return redirect('/')
else:
# Adding a else solves this problem. The user gets a blank form back
form = RegistrationForm()
args = {'form': form}
return render(request, 'users/reg_form.html', args)**

Django form data isn't being inserted into postgres but there are no errors

I am trying to insert data from a Django form into a Postgres table. There are no errors but it's not being inserted and the redirect to the thank you page is happening so it appears to be going through the method without an issue.
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
city = form.cleaned_data['city']
m = MyUser(email=email, city=city, registration_date=datetime.now())
m.save()
return redirect('thanks')
return render(request, "email.html", {'form': form})

Categories

Resources