AttributeError: 'module' object has no attribute 'Name' - python

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 ...

Related

Pylint errors in Django, Pylint(E0611:no-name-in-module) and Pylint(E1101:no-member)

It seems like my models.py, forms.py, urls.py and views.py are not recognizing the elements in each other and I don't understand what could be going wrong. I'm just starting the project (CS50W Project4-Network) and I noticed the problem when I tried to render the model form and the textarea field of the form linked to the model wouldn't show on the browser, it only shows when I click submit, as a missing field to be filled, I'm not sure if its because of the same pylint errors I'm getting or something else.
Here is my models:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Post(models.Model):
body = models.TextField()
date = models.DateTimeField(auto_now_add = True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=None)
def __str__(self):
return f"{self.body} by {self.author} at {self.date}"
The forms.py:
from django import forms
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ["body"]
widgets = {
"body": forms.Textarea(attrs={'class': 'form-control col-md-5 col-lg-6'}),
}
The views
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import PostForm
from .models import User, Post
**I left out logging in routes**
#login_required(login_url='login')
def create_post_page(request):
return render(request, "network/create_post.html")
def create_post(request):
posted = False
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return HttpResponseRedirect("/create_post?posted=True")
else:
form = PostForm()
if "posted" in request.GET:
posted = True
return render(request, "network/create_post.html", {
"posted": posted,
"form": form
})
The urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("create_post", views.create_post, name="create_post"),
path("create_post_page", views.create_post_page, name="create_post_page")
]
The template code where the form is not showing, only showing when I click submit as a missing field to be field
{% extends "network/layout.html" %}
{% block body %}
{% if posted %}
{% else %}
<h2>Create a new post</h2>
<form action="{% url 'create_post' %}" method = "POST">
{% csrf_token %}
{{ form.as_p }}
<input class="btn btn-secondary" type="submit" value="Post">
</form>
{% endif%}
{% endblock %}
The problems vscode keep raising:
No name 'Post' in module 'network.models'Pylint(E0611:no-name-in-module)
Module 'network.views' has no 'create_post' memberPylint(E1101:no-member)
Module 'network.views' has no 'create_post_page' memberPylint(E1101:no-member)
Somebody help me please, I feel like its a small problem but its driving me nuts because I can't figure out why.
Make sure you load the plugin "pylint_django" when pylint is called, and that you pass it the correct value for django-settings-module. To do this, create a file pylintrc in your project folder and give it the following contents:
[MAIN]
load-plugins = pylint_django,
django-settings-module = mysite.settings

Django - 'WSGIRequest' object has no attribute 'get'

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.

how to handle httpresponseredirect

test2/urls.py
from django.conf.urls import url
from .import views
from .forms import forms
urlpatterns=[
url(r'^$',views.index,name='index'),
url(r'^thankyou/$',views.thankyou,name='thankyou')
]
test1/urls.py
from django.contrib import admin
from django.conf.urls import url , include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test2/',include('test2.urls')),
]
views.py
this view should redirect to /test2/thankyou/ but why it is going to /thankyou
and what to do enable the view given by redirect method
from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from .forms import Get_name
# Create your views here.
def index(request):
if request.method == 'POST':
form = Get_name(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thankyou/')
else:
form = Get_name()
return render(request, 'test2/name.html' , {'form':form})
def thankyou(request):
return HttpResponse('sai chaitanya')
name.html
after submitting the form it should redirect to test2/thankyou but it is going to /thankyou.
<form action="/thankyou/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')]
class Get_name(forms.Form):
user_name = forms.CharField(label='user name',max_length='50',required=True)
pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password')
pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password')
email = forms.EmailField(label='email',max_length='100')
mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10')
address = forms.CharField(label='Address',max_length='100')
user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice))
It is going to /thankyou/ because you have hardcoded the URL /thankyou/:
return HttpResponseRedirect('/thankyou/')
You can redirect to /test2/thankyou/ by changing the code to:
return HttpResponseRedirect('/test2/thankyou/')
However the best practice is to reverse the URL instead of hardcoding it:
from django.urls import reverse
return HttpResponseRedirect(reverse('thankyou'))
This can be simplified using the redirect shortcut:
from django.shortcuts import redirect
return redirect('thankyou')

Django: Search Engine

I am trying to make a search engine of sorts in Django, where the user enters a query via a form and gets an output if the query exists in the database. Here's my code:
urls.py:
from django.conf.urls import url
from django.contrib import admin
from Search import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', views.form),
url(r'^search/', views.data,name='search'),
]
models.py:
from __future__ import unicode_literals
from abc import ABCMeta
from django.db import models
# Create your models here.
class Album(models.Model):
artist = models.CharField(max_length=100)
album_title = models.CharField(max_length=100)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=100)
def __str__(self):
return self.album_title + "-" + self.artist
views.py:
from django.http import HttpResponse,Http404
from models import Album
from forms import FormQuery
from django.shortcuts import render
from django.template import loader
from . import *
def data(request):
if request.method=='POST':
form=FormQuery(request.POST)
data=form.cleaned_data
value=data['query']
if form.is_valid():
try:
album1 = Album.objects.get(artist__contains=value)
return render(request,'Search/form.html',{'album':album1})
except:
raise Http404("Does not exist.")
else:
return render(request,'Search/form.html')
forms.py:
from django import forms
class FormQuery(forms.Form):
query=forms.CharField()
form.html:
<form action="{% url 'search' %}" method="POST">{% csrf_token %}
<fieldset>
Enter an album:<br>
<input type="text" name="query" ><br>
<input type="submit" value="Submit for Search >>">
</fieldset>
</form>
{% if album %}
<h1>{{ album }}</h1>
{% endif %}
However, when I type the query, I see the url change ,but the page remains the same and my result(album name) is not displayed. I am new to Django.
form.is_valid() must be called before accessing to cleaned_data.

"' object has no attribute 'get' Error

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'.

Categories

Resources