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.
Related
I'm trying to get form data using a POST request and save the form data to my database which was created using a django model, which is InfoModel. I'm getting the data from the POST request, but I don't know how to save all of it at once so that it all saves to the same row in the db. The way I'm doing it now, each object from the form saves to a different row of the database which is obviously not useful at all. I expect the answer is simple, but I haven't seen this in the docs.
views.py:
def home(request):
if request.method == 'POST':
# if POST request, validate the data
form = InfoForm(request.POST)
if form.is_valid():
# if the form is valid, collect the data, submit to db, and thank the user
valid = True
form_data = request.POST
f = InfoModel(fname=form_data['fname'])
f.save()
l = InfoModel(lname=form_data['lname'])
l.save()
e = InfoModel(email=form_data['email'])
e.save()
p = InfoModel(phone=form_data['phone'])
p.save()
return render(request, 'form_db/home.html', {'form': form, 'valid': valid})
else:
# if the form is invalid, populate the form with the entered data and show error message
valid = False
form = InfoForm(request.POST)
return render(request, 'form_db/home.html', {'form': form, 'valid': valid})
else:
# if GET request, return blank form as normal
form = InfoForm()
return render(request, 'form_db/home.html', {'form': form})
You can simply, give all fields' names of your InfoModel at once in the following way:
if form.is_valid():
valid=True
fName=form.cleaned_data['fname']
lname=form.cleaned_data['lname']
email=form.cleaned_data['email']
phone=form.cleaned_data['phone']
instance=InfoModel(fname=fName,lname=lname,email=email,phone=phone)
instance.save()
return render(request,"form_db/home.html",{'form': form,'valid':valid})
Note: Models in django doesn't require model to be the suffix, so it will be better if you only give model name Info rather than InfoModel.
Every time you call f = InfoModel() you are instantiating a new instance, and then saving it using f.save(), which is why you are getting so many rows. All this is unnecessary since a form has it's own save() method, which will save all the fields at once into ONE row.
The best way to handle forms is to use the classic Post/Redirect/Get method where if the form data comes in as Post, then you process it and redirect, usually back to the same view, but it can be another view as well. If it is a Get, then you render the blank form.
def home(request):
if request.method == 'POST':
form = InfoForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('home')
return render(request, 'form_db/home.html', {'form':form})
Note the form = InfoForm(request.POST or None), which is handy since it will create a blank form with the None if it is not a Post request, but if it is will fill the form with the data request.POST if it's a Post request.
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
After submit a form, I want to redirect to an specific view passing one flag=True in order to activate a popup like:
def view1(request):
if request.method == 'POST':
form = Form(request.POST)
if form.is_valid():
form.save()
return redirect('new_view') # Here I need to send flag=True
else:
form = Form()
return render(request, 'template.html', {'form': form})
How can I do this?
It's not quite clear on what you mean by arguments if it should be in the query string or arguments to a view.
Either way, below is both solutions;
redirect accepts args and kwargs
redirect('new_view', flag='show') # This is the argument of a view
or
redirect('{}?flag=True'.format(reverse('new_view'))
Then you can access it in the view like so
show_flag = bool(request.GET.get('flag', False))
for a given url pattern such as
url(r'^random/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', views.random, name="urlname")
or
url(r'^argfree/', views.random2, name="urlname2
from django.http import HttpResponseRedirect
from django.urls import reverse
def view(request):
# do your thing
if something:
return HttpResponseRedirect(reverse("urlname", args=["this_is_arg1", "this_is_arg2"]))
else:
return HttpResponseRedirect(reverse("urlname"))
There is a django-url-params module to help you in this situation. Just add
request.cparam = {'flag': True}
return param_redirect(request, viewname)
from django.urls import reverse
response = redirect(f"{reverse('search')}?query='How to redirect with arguments'")
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():
....