Accessing data in GET form and posting to results page (Django) - python

I'm trying to create a form that takes inputs and uses these inputs to create an output that's posted to a results page. I've searched everywhere and can't understand how to post the data (in the case below, 'country' and 'culture') to the results_view.
# view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from form.forms import InputForm
def get_list(request):
if request.method == 'GET':
form = InputForm(request.GET)
if form.is_valid():
country = form.cleaned_data['country']
culture = form.cleaned_data['culture']
return results_view(form)
else:
form = InputForm()
return render(request, 'form/index.html', {'form': form})
def results_view(form):
text = form.restaurant
c = {'output' : text}
return render(form, 'form/results.html', c)
and
# forms.py
from django import forms
class InputForm(forms.Form):
country = forms.CharField(label='country', max_length=100)
cuisine = forms.CharField(label='cuisine', max_length=100)
How can I access the inputs and use them as the text in 'results_view'? Additionally, if I want to pass these results as an input argument for another python function (say a function that maps country name to latitude and longitude), how can I incorporate this into views.py? Thanks a lot!

You don't need to redirect to another function, just render this another template
# view.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from form.forms import InputForm
def get_list(request):
if request.method == 'POST':
form = InputForm(request.POST)
if form.is_valid():
country = form.cleaned_data['country']
culture = form.cleaned_data['culture']
c = {'country' : country, 'culture'... whatever you get}
return render(form, 'form/results.html', c)
else:
form = InputForm()
return render(request, 'form/index.html', {'form': form})

Related

Django "type object X has no attribute POST"

For some reason, I cannot do this without result in an error. How does TodoForm have no attribute to POST? All the other example shows it's valid.
from django.shortcuts import render
from .models import Todo
from .forms import TodoForm
def index(request):
return render(request, 'home.html')
def todoPanel(request):
if request.method == 'POST':
form = TodoForm.POST(request.POST)
if form.is_valid():
print('steve')
else:
form = TodoForm()
return render(request, 'todo_panel.html', {'form': form})
Try to change your line
form = TodoForm.POST(request.POST)
to:
form = TodoForm(request.POST)

Initial value not showing up in DecimalField

I have a form with a DecimalField and I have set the initial value like so:
class RawProductForm(forms.Form):
title = forms.CharField(label="")
description = forms.CharField(required=False)
price = forms.DecimalField(initial=199.99)
Here is the view:
from django.shortcuts import render
from .forms import ProductForm, RawProductForm
from .models import Product
def product_create_view(request):
form = RawProductForm(request.GET)
if request.method == "POST":
form = RawProductForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
Product.objects.create(**form.cleaned_data)
else:
print(form.errors)
context = {
"form": form
}
return render(request, "products/product_create.html", context)
However, the initial value is not showing up when I render the page:
What could be the issue?
You should not use request.GET here as a source of data, since then it will try to parse the data out of a (likely non-existing) querystring. If you want to create an empty non-bounded form, you construct it without data:
def product_create_view(request):
if request.method == "POST":
form = RawProductForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
Product.objects.create(**form.cleaned_data)
else:
print(form.errors)
else:
form = RawProductForm()
context = {
"form": form
}
return render(request, "products/product_create.html", context)
That being said, your code has some additional problems. If the creation is successful with a POST request, it is better to redirect, and implement the Post/Redirect/Get pattern [wiki]. Furthermore you probably here should use a ModelForm, this will ensure that the creation of the model object (here a Product) is done correctly.

Convert Function Based View to Class Based View

I have a Django 2.1 views.py that I wanted to convert to Class Based View, I am NOT Django advanced user, and I know that I did translate the Functions the wrong way. The code was ment to serve a Bootstrap Modal Ajax form, and don't ask me to go see some solution already built out there, I tried everything, even the ones that worked fine in standalone, they are not compatible/conflict with my template (Maybe jquery or ..). I did convert List View and so far Create View, but I keep getting this Error :
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
"A {% csrf_token %} was used in a template, but the context "
Here's my views.py that I want to convert to CBV :
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.template.loader import render_to_string
from .models import Book
from .forms import BookForm
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
#The Old function List view
#def book_list(request):
# books = Book.objects.all()
# return render(request, 'books/book_list.html', {'books': books})
#The New Class List view
class Book_list(ListView):
template_name = 'books/book_list.html'
model = Book
def save_book_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def book_create(request):
if request.method == 'POST':
form = BookForm(request.POST)
else:
form = BookForm()
return save_book_form(request, form, 'books/includes/partial_book_create.html')
def book_update(request, pk):
book = get_object_or_404(Book, pk=pk)
if request.method == 'POST':
form = BookForm(request.POST, instance=book)
else:
form = BookForm(instance=book)
return save_book_form(request, form, 'books/includes/partial_book_update.html')
def book_delete(request, pk):
book = get_object_or_404(Book, pk=pk)
data = dict()
if request.method == 'POST':
book.delete()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
context = {'book': book}
data['html_form'] = render_to_string('books/includes/partial_book_delete.html', context, request=request)
return JsonResponse(data)
I've been strugling since 9 days now. asking around, asked even the developper of that code ... no answer..
I really appreciate it, thank you guys
You can try this to change you view's to class based view's
class BookList(ListView):
template_name = 'books/book_list.html'
model = Book
class BookCreate(CreateView):
template_name = "books/includes/partial_book_list.html"
model = Book
form_class = BookForm
success_url = 'success' #name of url you want to redirect to
class BookUpdate(UpdateView):
model = Book
form_class = BookForm
fields = ['name',] #field's you want to update
template_name = 'books/includes/partial_book_update.html'
success_url = 'success' #name of url you want to redirect to
class BookDelete(DeleteView):
model = Book
template_name = 'books/includes/partial_book_delete.html'
success_url = 'success'

How can I get the id of the particular modelform?

I am new to Django. I am just learning to use forms and modelforms. Here I used modelforms to get two charfields(username and password) and saving it. What I wanted to do is to get the model id of that username. Below is the code. But I can't get the id.
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from reg.models import registration, registrationform
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
p = registration.objects.all()
for loop in p:
if loop.username == username:
id = loop.id
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id)))
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
def thanks(request, id):
p = get_object_or_404(registration, pk=id)
return render_to_response('thanks.html', {'reg': p)
One more question. What is the model field for password?
Thanks.
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
data =form.save()
#...
id = data.id
#...
return HttpResponseRedirect(reverse('reg.views.thanks', args=(id)))
user = form.save(commit=False)
user.first_name = u'First name'
user.last_name = u'Last name'
user.save()
For password use password1 field
Please could you paste your urls.py?
I recently had a problem almost exactly the same as this - it was just a typo there, I had the wrong value in in second field of the url function:
url(r'^people/thanks/(?P<person_id>\d+)$', 'people.views.thanks'),
Should have been:
url(r'^people/thanks/(?P<person_id>\d+)$', 'people.views.new'),
How about changing your registration function to this:
def registration(request):
if request.method == 'POST':
form = registrationform(request.POST)
if form.is_valid():
userdetails = form.save()
user = userdetails.username
val = registration.objects.get(username = user)
return HttpResponseRedirect(reverse('reg.views.thanks', args=(val.id)))
else:
form = registrationform()
return render_to_response('registration.html', {'form' : form}, context_instance=RequestContext(request))
I suggest you read this: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

Django: Model Form "object has no attribute 'cleaned_data'"

I am trying to make a search form for one of my classes. The model of the form is:
from django import forms
from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField
from books.models import Book, Author, Category
class SearchForm(forms.ModelForm):
authors = ModelMultipleChoiceField(queryset=Author.objects.all(),required=False)
category = ModelChoiceField (queryset=Category.objects.all(),required=False)
class Meta:
model = Book
fields = ["title"]
And the view I'm using is:
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from books.models import Book,Author
from books.forms import BookForm, SearchForm
from users.models import User
def search_book(request):
if request.method == "POST":
form = SearchForm(request.POST)
if form.is_valid():
form = SearchForm(request.POST)
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
else:
form = SearchForm()
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
The form shows up fine, but when I submit it I get an error: 'SearchForm' object has no attribute 'cleaned_data'
I'm not sure what's going on, can someone help me out? Thanks!
For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST) and all should be well.
I would write the code like this:
def search_book(request):
form = SearchForm(request.POST or None)
if request.method == "POST" and form.is_valid():
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
return HttpResponseRedirect('/thanks/')
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
Pretty much like the documentation.
I was facing the same problem,
I changed the code like this
if request.method == "POST":
form = forms.RegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
fname = form.cleaned_data.get('fname')
lname = form.cleaned_data.get('lname')
email = form.cleaned_data.get('email')
pass1 = form.cleaned_data.get('pass1')
pass2 = form.cleaned_data.get('pass2')
At times, if we forget the
return self.cleaned_data
in the clean function of django forms, we will not have any data though the form.is_valid() will return True.

Categories

Resources