Django, redirect to another view with data - python

I'm sending a form. So if it's valid i'm setting a variable message with a message. So if the form is valid, I would like to redirect to another view but also pass the message variable. It should be a syntax issue.
On successful submission, it redirects to a view with a url membership/enroll/studies.views.dashboard which of course is wrong.
views.py
def enroll(request):
user = request.user
if request.method == 'POST':
form = SelectCourseYear(request.POST)
if form.is_valid():
student = form.save(commit=False)
student.user = request.user
student.save()
message = 'Successfully Enrolled'
return redirect('studies.views.dashboard', {'message': message,})
else:
form = SelectCourseYear()
return render(request, 'registration/step3.html',)

Consider making use of sessions to store arbitrary data between requests: https://docs.djangoproject.com/en/dev/topics/http/sessions/
request.session['message'] = 'Successfully Enrolled'
Alternatively, if you just want to display a message to the user, you might be happy with the contrib.messages framework: https://docs.djangoproject.com/en/dev/ref/contrib/messages/
from django.contrib import messages
messages.success(request, 'Successfully Enrolled')
Based on your use case above, I'm guessing that contrib.messages is more appropriate for your scenario.

Related

Is it possible to feed data from a React POST request into a Django form without rendering that form on the frontend?

I am working on a basic login form for a hybrid React/Django web app. I would like to use the built in data-cleaning and validating methods of the Django Form models, but our frontend is pure React. Everything works as far as logging in, but I am feeding the raw body data into the authenticate function as shown here.
def login_view(request):
if request.method == "POST":
form_data = json.loads(request.body.decode('utf-8'))
user = authenticate(request, email=form_data["username"], password=form_data["password"])
if user == None:
request.session["invalid_user"] = 1
logging.warning("Login form contains no user")
login(request, user)
My question is, is there any way to feed this form_data into the Django native LoginForm when I instantiate it? I would prefer to not recode all of the input validation that Django does already.
I've tried instantiating a LoginForm like so:
form = LoginForm(data=form_data)
And then tried running form.full_clean(), but it doesn't seem to work. Any help would be greatly appreciated, thank you!
The issue was actually a difference in the variable names between the rendered React form and the Django LoginForm I had defined. One was username and password, the other email and password. With that in mind the usual way of working with forms works great!
if request.method == "POST":
form_data = json.loads(request.body.decode('utf-8'))
form = LoginForm(data=form_data)
if form.is_valid():
email = form.cleaned_data["email"]
password = form.cleaned_data["password"]
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)

Why do we need to login user in signup_view an login_view function? Django

So I need a theoretical answer here, not practical, I've been following this tutorial on Django anf everything seems quite understandable, but I'm not sure about one thing, so here are the views for signup page and login page:
def signup_view(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
#log the user in
login(request, user)
return redirect("articles:list")
else:
form = UserCreationForm()
return render(request, 'account/signup.html', {"form": form})
def login_view(request):
if request.method == "POST":
form = AuthenticationForm(data = request.POST)
if form.is_valid():
#log in the user
user = form.get_user()
login(request, user)
return redirect('articles:list')
else:
form = AuthenticationForm()
return render(request, "account/login.html", {"form":form})
So my question is, why do I need to write login(request, user) twice, isn't the signup function saving the user in database and log in function simply logging it in?
In the code, for post request and valid forms, the response is always a redirect to articles:list page.
If we assume the view articles:list as login required, users need to have an active session in order to view the page.
In the login_view function after authenticate is quite obvious that next step is to log the user in and redirect to articles:list
In the signup_view the logic might be, add user to database and redirect to articles:list, but since articles:list is login required, we need to log the user in.
Maybe that's the way they thought the logic for the example, it all depends on what you need since is not a rule to log the user in after register.

How to reload the current page when form was sent?

Hey,
after the form was sent the page needs to be automatically reloaded / refreshed. Either just the current page is going to be reloaded or the variable slug_title (which would be part of the current page url) needs to be passed into the (' ') from HttpResponseRedirect.
Do you have any suggestions? I would really appreciate it. :)
views.py
def posts(request, slug_titel):
post = get_object_or_404(Thread, slug_titel=slug_titel)
form = ThreadForm()
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(' ') # <- here I need to put in slug_title from above
You can redirect to a view with variables that way:
from django.shortcuts import redirect
return redirect('some-view-name', slug=slug_titel)
Well if the form is valid, you have access to cleaned_data, from there you can fetch the slug value entered by user:
if form.is_valid:
slug = form.cleaned_data.get(“slug_titel”)
return redirect(“your-view”, slug = slug)

Django Sending Modelform as an email

I created a site where my techs submit their inventory using model forms. Everything is working as intended but I would like to add the function of sending the whole form as an email when they submit their inventory. This would allow for my inventory team to verify counts without having to log in and check the website.
Here is my view.py I know it works if I remove the email bits and saves to my models. Currently returns an error:
'dict' object has no attribute 'splitlines'
form = Inventory_Form()
if request.method == 'POST':
form = Inventory_Form(request.POST)
tech_field = form.save(commit=False)
tech_field.technician = request.user
tech_field.save()
if form.is_valid():
form.save()
name = form.cleaned_data['initials_date']
from_email = 'operations#imbadatthis.com'
subject = 'Weekly Inventory', form.cleaned_data['initials_date']
message = form.cleaned_data
try:
send_mail(subject, message, from_email, ['myemail#n00b.com'], name)
except BadHeaderError:
return HttpResponse('Invalid header found.')
return response, redirect('inventory_submitted')
return render(request, 'inventory.html', {'form': form})
Would it be better to save the form to a csv then attach it as an email? I looked at this and also had issues with that part.
I guess the error is raised at the send_mail because of
message = form.cleaned_data
Because this is a dict and the send_mail from django expects the message to be a string.
You have to convert the dict to a string.
Maybe this helps to make a nice looking email. (documentation)

Verify submitted Django form in view

I have a view, which expects a POST request. The post request should contain data submitted through a Django form.
The Django form looks something like this:
class SubmitForm(forms.Form):
title = forms.CharField(max_length=100)
comment = forms.CharField(max_length=255)
I know I have access to the submitted data with request.POST["title"] and request.POST["comment"]. So I can theoretically check if they're set and valid manually.
But is there a way to use .is_valid() (Link to Django documentation), to validate the submitted form?
One possibility would be to create a form in the view, fill it with the submitted data and then check it for validity.
data = {'title': request.POST["title"],
'comment': request.POST["comment"]}
f = SubmitForm(data)
f.is_valid()
# True/False
Is there a direct way to use is_valid() on a submitted Django form?
You can write view as below:
def verify_view(request):
if request.method == "POST":
form = SubmitForm(request.POST)
if form.is_valid():
# code here if form is valid
else:
form = SubmitForm() # returns empty form to be fill if not post request
return render(request, 'template_form.html', {'form': form})
if request.method == 'POST':
form = PostForm(request.POST or None)
if form.is_valid():
// do your save work
You can pass request.POST as Form argument directly:
form = PostForm(request.POST or None)
if form.is_valid():
....

Categories