Django file upload form constructor explained - python

As I go through Django tutorial, I'm confused about the way the form is constructed, here is the link where the following code is from:
forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import UploadFileForm
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form': form})
Question: Where can I find the constructor declaration of UploadFileForm?

here is the constructor declaration: https://github.com/django/django/blob/master/django/forms/forms.py#L72-L98
Question answered?

Related

AttributeError: 'WSGIRequest' object has no attribute 'Get'

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Quote
from .forms import QuoteForm
from pages.models import Page
def quote_req(request):
submitted = False
if request.method == 'POST':
form = QuoteForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/quote/?submitted=True')
else:
form = QuoteForm()
if 'submitted' in request.Get:
submitted = True
return render(request, 'quotes/quote.html', {'form': form, 'page_list': Page.objects.all(), 'submitted':submitted})
Context: This is the views.py code the code looks correct but clicking on the quote link on the html local host gives the aforementioned error
You have just a typo:
if 'submitted' in request.Get:
Use request.GET instead.
i know it been a while, but i can help others that run into the same issue
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Quote
from .forms import QuoteForm
from pages.models import Page
def quote_req(request):
submitted = False
if request.method == 'POST':
form = QuoteForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/quote/?submitted=True')
else:
form = QuoteForm()
if 'submitted' in request.Get:
submitted = True
return render(request, 'quotes/quote.html', {'form': form, 'page_list': Page.objects.all(), 'submitted':submitted})
This is what i did.
Make sure the second else that is below ``` if request.method == "POST":

How do i pass a forms "text" input into another variable that is in views.py

In my Django project, I have to take the input from forms and pass it as an argument for a function that is in views.py. How do I do it?
My views.py code
from django.shortcuts import render,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from search_engine import query
from .forms import SearchForm
def query_input(request):
if request.method == "POST":
form = SearchForm(request.POST)
else:
form = SearchForm()
return render(request, 'search.html', {'form': form})
def search_results(request):
search_results = query.results(# text input from forms)
a = "<br /><br />".join(word for word in search_results)
return HttpResponse(a)
My forms.py code
from django import forms
class SearchForm(forms.Form):
your_query = forms.CharField(max_length=100)
After you checked that the request method is a POST you can validate the form and then access its attributes like this
In views.py:
if request.method = "POST":
form = SearchForm(request.POST)
if form.is_valid():
search_text = form.cleaned_data['search_text']
# code from search_results function to return HTTP Response
Check out the documentation on forms and view here for more information.

HttpResponse won't display `post` information when submitting a form

I'm working my way through Django and I'm creating an app that will allow users to use an ID number to sign-in to a system. So I have two views, one for users to log-in, and the other to sign-up. The former view works just fine, I can get it to display the information the user has submitted. However I can't get the second view to display the POST data to the user:
from .forms import NameForm, IdForm
from django.shortcuts import render
from django.http import HttpResponse
def sign_in(request):
if request.method == "POST":
#here will construct the form with the POST data
form = NameForm(request.POST)
#the next part is to check that the information submitted is valid
if form.is_valid():
post = form.save()
post.save()
return HttpResponse(post)
else:
return HttpResponse("Form is invalid")
else:
form = NameForm()
return render(request, 'checkin/base.html', {'form': form})
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
return HttpResponse(post)
else:
return HttpResponse('Form is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
Basically I want to make the response to be "thank you, your ID number is: post".
Here is the class for my model:
from __future__ import unicode_literals
from django.db import models
from django import forms
from django.forms import ModelForm
# Create your models here.
class Question(models.Model):
question_text = models.CharField("What is your ID?", max_length=200)
id_text = models.CharField("Enter a new identification
number",max_length=200, null=True)
def __str__(self):
return self.question_text
And here are the form classes for both views:
from django.forms import ModelForm
from .models import Question
#put the form here
class NameForm(ModelForm):
class Meta:
model = Question
fields = ['question_text']
class IdForm(ModelForm):
class Meta:
model = Question
fields = ['id_text']
It's not generally acceptable to display the POST data as the respnose to the user. That's not HTML, merely a dictionary which the average user will not understand. The standard way of using forms in Django (and indeed almost any web framework) is to display the form validation errors to the user so that he may rectify it.
The right way
def sign_up(request):
if request.method == "POST":
form = IdForm(request.POST)
if form.is_valid():
post = form.save()
post.save()
return HttpResponseRedirect('/succes_url')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})
The problem is in line return HttpResponse(post),You are passing a whole form into HttpResponse,but as you mentioned,you just need id_text field of the IdForm.
So the updated code should be :
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, your ID number is: '+id)
else:
return HttpResponse('Form is invalid')
else:
form = IdForm()
return render(request, 'checkin/base.html', {'form': form})

Django. Unbound method in urls

I trying to accept localhost:8000/upload file and run into this problem
unbound method upload_file() must be called with Upload instance as first argument (got WSGIRequest instance instead)
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from upload.views import Upload
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^upload/$', Upload.upload_file),
url(r'^thanks/$', Upload.thanks),
]
views.py
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from upload.forms import FileForm
from upload.models import upFile
class Upload():
def upload_file(request):
if request.method == "POST":
form = FileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks')
else:
form = FileForm()
return render_to_response('temp1.html', {'form': form}, context_instance = RequestContext(request))
def thanks(request):
return render_to_response('temp2.html')
Your view is not inheriting from a Django class based view: https://docs.djangoproject.com/en/1.8/topics/class-based-views/intro/
from django.views.generic import View
class Upload(View):
def upload_file(self, request):
if request.method == "POST":
form = FileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks')
else:
form = FileForm()
return render_to_response('temp1.html', {'form': form}, context_instance = RequestContext(request))
def thanks(self, request):
return render_to_response('temp2.html')
You need to inherit form one of these view classes otherwise Django will treat your view as a normal class which is why you are getting that error.
you also need to adjust your urls.py:
urlpatterns = [
url(r'^upload/', Upload.as_view()),
]
After looking through the docs and at the structure of your vie I'm not sure you are structuring your views properly for class based views. You may want to read through the docs some more and adjust your structure accordingly.
I believe you will want somethign that looks more like this:
class Upload(View):
def get(self, request):
form = FileForm()
return render_to_response('temp1.html', {'form': form}, context_instance = RequestContext(request))
def post(self, request):
form = FileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks')
else:
return render_to_response('temp2.html')
I don't understand why you have the Upload class at all. Python is not Java, there's no need to put everything into classes. Put upload_file and thanks at the module level, and refer to them directly in the url patterns.

'CategoryForm' object has no attribute 'save'

Working with tutorial tango with django(fun with forms) ,error is showing 'CategoryForm' object has no attribute 'save' pls help
The project tango_withDjango has a app rango in it p.s. identation are correct in my program unlike here...and using ModelForm will show error
views.py is
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category
from rango.models import Page
from rango.forms import CategoryForm
def add_category(request):
# Get the context from the request.
context = RequestContext(request)
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
form.save()
# Now call the index() view.
# The user will be shown the homepage.
#return index(request)
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render_to_response('rango/add_category.html', {'form': form}, context)
models.py`
from django.db import models
class Category(models.Model):
name=models.CharField(max_length=128,unique=True)
def __unicode__(self):
return self.name
class Page(models.Model):
category=models.ForeignKey(Category)
title=models.CharField(max_length=128)
url=models.URLField()
views=models.IntegerField(default=0)
def __unicode__(self):
return self.title
forms.py
from django import forms
from rango.models import Page,Category
class CategoryForm(forms.Form):
name=forms.CharField(max_length=128,help_text="Please enter Category name")
views=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
likes=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta:
model=Category
class PageForm(forms.ModelForm) :
title=forms.CharField(max_length=128,help_text="Please enter title of the Pages")
url=forms.URLField(max_length=200,help_text="please enter url of the page")
views=forms.IntegerField(widget=forms.HiddenInput(),initial=0)
class Meta :
model=Page
fields=('title','url','views')
CategoryForm should extend the ModelForm, not the Form.
And btw, class Meta does not exist for Form

Categories

Resources