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)
Related
This is my views function,
def studentcreate(request):
reg = StudentForm()
string = "Give Information"
if request.method == "POST":
reg = StudentForm(request.POST)
string = "Not Currect Information"
if reg.is_valid():
reg.save()
return render('http://localhost:8000/accounts/login/')
context = {
'form':reg,
'string': string,
}
return render(request, 'student.html', context)
Here first we store form in reg variable then also we write reg = StudentForm(request.POST) why?
acutally why we write this?
I can't tell you why you are writing this. Maybe only you know. It does not make much sense. I would recommend reading the Django documentation on this at https://docs.djangoproject.com/en/4.0/topics/forms/#the-view
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
You read from data if the request is a POST. Otherwise, return an empty form.
You could think of the "request.POST" as a parameter passed onto the form in the view. This tells the view that the form mentioned has POST data from the form in name.html. Otherwise it is just an empty form.
I want to create an update form. When a user enters this page the form should be filled with information so that the user can edit what they want to fix. I try to use instance in views but didn't work. The fields are still empty. How can I do it?
views.py
def setup_settings(request):
user = request.user
data = get_object_or_404(DashboardData, user=user)
# print(data) --> DashboardData object (45)
form = SetupForm(request.POST or None, instance=data)
if request.method == 'POST':
if form.is_valid():
form.save()
else:
form = SetupForm()
context = {
'form': form,
}
return render(request, 'update_setup.html', context)
Basically, in your else block, you have overwritten form with the empty object SetupForm(). When the user will visit the page, it will hit a GET request and your else block will make your form empty, try again after removing it.
I'm making a url shortener with django. I have a form that has a long_url attribute. I'm trying to get the long_url and add it to a redirect view with a HttpResponseRedirect.
# Form
from .models import ShortURL
from django import forms
class CreateNewShortURL(forms.ModelForm):
class Meta:
model=ShortURL
fields = {'long_url'}
widgets = {
'long_url': forms.URLInput(attrs={'class': 'form-control'})
}
# View
def page_redirect(request, url):
if request.method == 'GET':
form = CreateNewShortURL(request.GET)
if form.is_valid():
original_website = form.cleaned_data['long_url']
return HttpResponseRedirect(original_website)
When I go to the link, it gives me The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead. Does anyone know why this is happening?
It is not returning because there is no valid form, you need to redirect to a form for the user to enter data first, you will then get that data from the form to perform your redirect. additionally because a user is returning data you will need to get the data from request.POST.
def page_redirect(request, url):
if request.method == 'GET':
form = CreateNewShortURL(request.POST)
if form.is_valid():
original_website = form.cleaned_data['long_url']
return HttpResponseRedirect(original_website)
return render(request,'template') # this is the form for the user to enter the url
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():
....
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.