I'm trying to make a really basic site in Django.
Right now you just have to enter your name and it gets saved.
But even though I followed the instructions here
it throws the error 'WSGIRequest' object has no attribute 'get'
My views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.http import HttpResponse
from .forms import NameForm
from django.views.decorators.csrf import csrf_protect
#csrf_protect
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():
with open("name.txt" , "w") as f:
f.write(form.cleaned_data)
return HttpResponseRedirect('/nmindex/')
#csrf_protect
def vote_page(request):
return render(request, 'name.html', {'form': NameForm(request)})
forms.py:
from django import forms
from django.views.decorators.csrf import csrf_protect
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
urls.py:
from django.contrib import admin
from django.urls import path, include
from nmindex import views
urlpatterns = [
path('data/', views.get_name),
path('vote/', views.vote_page),
path('admin/', admin.site.urls),
]
And the template name.html:
<form action="/data/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
But when I open http://localhost:8000/vote/:
AttributeError at /vote/
'WSGIRequest' object has no attribute 'get'
Request Method: GET
Request URL: http://localhost:8000/vote/
Django Version: 3.0.5
Exception Type: AttributeError
Exception Value:
'WSGIRequest' object has no attribute 'get'
Exception Location: C:\Users\Sid\Envs\namesproj\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 258
Python Executable: C:\Users\Sid\Envs\namesproj\Scripts\python.exe
Python Version: 3.8.2
Python Path:
['C:\\Users\\Sid\\names',
'C:\\Users\\Sid\\Envs\\namesproj\\Scripts\\python38.zip',
'c:\\users\\sid\\appdata\\local\\programs\\python\\python38-32\\DLLs',
'c:\\users\\sid\\appdata\\local\\programs\\python\\python38-32\\lib',
'c:\\users\\sid\\appdata\\local\\programs\\python\\python38-32',
'C:\\Users\\Sid\\Envs\\namesproj',
'C:\\Users\\Sid\\Envs\\namesproj\\lib\\site-packages']
Server time: Sat, 2 May 2020 08:00:03 +0000
Error during template rendering
In template C:\Users\Sid\names\templates\name.html, error at line 3
'WSGIRequest' object has no attribute 'get'
1 <form action="/data/" method="post">
2 {% csrf_token %}
3 {{ form }}
4 <input type="submit" value="Submit">
5 </form>
Any help would be greatly appreciated.
The problem is in your vote_page method. You can not instantiate a form with request as data. It expects a dictionary-like object like a QueryDict, for example with request.POST or request.GET, so NameForm(request) will not work.
def vote_page(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
# …
return redirect('name-of-some-view')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Related
I'm using Django to create a simple HTML input page, right now I am just using the tutorial for Django Forms but I get the error AttributeError: module 'polls.views' has no attribute 'index'
Here are all the relevant files:
This is where the Error is happening:
$ mysite/polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
This is views.py:
$ polls/views.py
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})
and this is forms.py
$ /polls/forms.py
from Django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Here is name.html:
$ /polls/name.html
<html>
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
<html>
I am so confused as to why this is happening because when I used it with the Writing your first Django app tutorial it worked but when I use a form it doesn't
Thanks in advance
Your view name is not index but get_name
urlpatterns = [
path('', views.get_name, name='index'),
]
Your polls/urls.py:
from django.urls import path
from . import views
app_name = 'polls' # add this line
urlpatterns = [
path('', views.index, name='index'),
]
Every time I try to edit any entry through a form, it gives Attribute Error.
I have only one model that is BlogPost
models.py
from django.db import models
# Create your models here.
class BlogPost(models.Model):
""" A title and text for a blog entry"""
title = models.CharField(max_length=200)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
""" return a string representation of the model."""
return self.title
This is views file
views.py
from django.shortcuts import render, redirect
from .models import BlogPost
from .forms import BlogPostForm
def edit_post(request, post_id):
""" edit an entry"""
title = BlogPost.objects.get(id=post_id)
post = title.text
if request.method != 'POST':
form = BlogPostForm(instance=post)
else:
form = BlogPostForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:index', post_id=title.id)
context = {'title': title, 'post': post, 'form': form}
return render(request, 'blogs/edit_post.html', context)
This is edit post file
edit_post.html
{extends 'blogs/base.html'}
{% block content %}
<p>Edit Form:</p>
<p>{{ title }}:</p>
<form action="{% url 'blogs:edit_post' title.id %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Save changes</button>
</form>
{% endblock content %}
forms.py
from django import forms
from .models import BlogPost
class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['title', 'text']
labels = {'title':'Title', 'text': 'Post'}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
urls.py
# defines urls patterns for the blogs app
from django.urls import path
from . import views
app_name = 'blogs'
urlpatterns = [
# Home page
path('', views.index, name='index'),
# To add new post
path('new_post/', views.new_post, name='new_post'),
# To edit post
path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'),
]
I'm using Django 2.2.6 and python 3.7.4.
I guess there is a problem with my URL patterns or with the paths of the request.
This is the error it generates
TypeError at /edit_post/1/
edit_post() got an unexpected keyword argument 'post_id'
Request Method: GET Request URL: http://localhost:8000/edit_post/1/
Django Version: 2.2.6 Exception Type: TypeError Exception Value:
edit_post() got an unexpected keyword argument 'post_id'
Exception Location:
C:\Users\nouma\Desktop\blog_folder\ll_env\lib\site-packages\django\core\handlers\base.py
in _get_response, line 113 Python Executable:
C:\Users\nouma\Desktop\blog_folder\ll_env\Scripts\python.exe Python
Version: 3.7.4
**
I've got my answer. The problem was that in views file I was giving unnecessary argument.
i-e
return redirect('blogs:index', post_id=title.id)
this second argument was not needed
i am trying to create a basic form using python which has only one field your_name in the table NameForm. But i am getting the error AttributeError: 'module' object has no attribute 'Name'. I dont understand where this error comes from. Could anyone help me with it? I am using django 1.11.
models.py
from __future__ import unicode_literals
from django.db import models
class NameForm(models.Model):
your_name = models.CharField(max_length=200)
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.views import generic
from .models import NameForm
class NameView(generic.NameView):
model = NameForm
template_name = 'home/name.html'
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
urls.py
from django.conf.urls import url
from . import views
app_name = 'home'
urlpatterns = [
url(r'^$', views.NameView.as_view(), name='name'),
]
template/home/name.html
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
You need to add generic.View Instead of generic.NameView, like this
from django.views import generic
class NameView(generic.View)
# you code ...
I am beginner to python Django. And trying build an posting article website with the help of tutorials. I got stuck at UserCreationForm. I have created a form using UserCreationForm, but when I am submitting the form I am not able to neither submit the form nor getting any error message on the page.
My views.py code
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.template.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
print args
return render_to_response('register.html', args)
def register_success(request):
return render_to_response('register_success.html')
register.html
{% extends "base.html" %}
{% block content %}
<h2>Register</h2>
<form action="/accounts/register/" method="post"> {% csrf_token %}
{{form}}
<input type="submit" value="Register"/>
</form>
{% endblock %}
register_success.html
{% extends "base.hml" %}
{% block content %}
<h2>You have registered!</h2>
<p>Click Here to login again</p>
{% endblock %}
The problem is that you are always creating a blank form.
args['form'] = UserCreationForm()
This means that you do not see any errors for POST requests when the form is invalid.
Instead, you should only create the blank form for GET requests.
from django.shortcuts import render
def register_user(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'register.html', args)
Note that I have simplified the view by using render instead of the obsolete render_to_response. That means you don't need to handle csrf manually.
You can use Django Generic Views, specifically CreateView, it will make your life a lot easier. You can use it like so:
from django.views.generic import CreateView
class CreateUserView(CreateView):
template_name = 'register.html'
form_class = UserCreationForm
success_url = '/accounts/register_success'
Add this to your urls.py and you are good to go:
from mysite.views import CreateUserView
# add this url pattern
url(r'^sign_up/$', CreateUserView.as_view(), name='signup'),
Have stuck here for 2 days. Hoping to get some enlightenment. The error code here is "'inputform' object has no attribute 'get'". I highly suspect the error is because of the forms.py. I want to make a dynammic choice field list there.
Model.py
from django import forms
from django.forms import ModelForm
from django.db import models
from dupont.models import dupont
class input(models.Model):
...
Region=models.CharField(max_length=100)
Forms.py
from django import forms
from django.forms import ModelForm
from .models import input
from anothermodel.models import A
from django.contrib.auth.models import User
import Queue
class inputform(forms.ModelForm):
regionlist = forms.ChoiceField(label=u'Region',choices=())
def __init__(self,*args,**kwargs):
super(inputform,self).__init__(*args,**kwargs)
self.fields['regionlist'] = forms.ModelChoiceField(queryset=anothermodel.objects.values('Region').distinct())
views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import inputform
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def input(request):
if request.method == 'POST':
form = inputform(request.POST)
if form.is_valid():
return HttpResponseRedirect('templates/About')
else:
form = inputform()
return render_to_response('inputform.html', {
'form': form,
})
Part of html
<body>
<script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<form action="" method="post">{% csrf_token %}
{{ form.regionlist }}
{% for region in form.regionlist.choices %}
<option value="{{ val }}" {% ifequal data.val val %}selected {% endifequal %}>
{% endfor %}
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from metrics import views
from django.views.generic.list import ListView
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from inputform.views import input,ifglobal
admin.autodiscover()
urlpatterns = patterns('',
url(r'^login/',include('login.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^input', 'inputform.views.inputform'),
)
The trackback
Traceback:
File "C:\Python27\lib\site-packages\django-1.8.3 py2.7.egg\django\core\handlers\base.py" in get_response
223. response = middleware_method(request, response)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\middleware\clickjacking.py" in process_response
31. if response.get('X-Frame-Options', None) is not None:
Exception Type: AttributeError at /input
Exception Value: 'inputform' object has no attribute 'get'
The error is indeed in your URLs. Your pattern is pointing at 'inputform.views.inputform', ie the form, not the view. It should be 'inputform.views.input'.