"' object has no attribute 'get' Error - python

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

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

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

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

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

Method Not Allowed (POST) using DeleteView

I am new to Django and i using Class based views to add a delete option to my Restaurant List, However when i click the delete button i am getting a blank screen and getting the following error in the console
"Method Not Allowed (POST):"
Below is my code
views.py
from __future__ import unicode_literals
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, ListView, DetailView,
CreateView,DeleteView
from django.urls import reverse_lazy
class RestaurantDeleteView(DeleteView):
model = RestaurantLocation
success_url = reverse_lazy('restaurants:list')
urls.py
from django.conf.urls import url, include
from .views import (
RestaurantListView,
RestaurantDetailView,
RestaurantCreateView,
RestaurantDeleteView,
)
urlpatterns = [
url(r'^create/$', RestaurantCreateView.as_view(), name= 'create'),
url(r'^$',RestaurantListView.as_view(), name= 'list'),
url(r'^(?P<slug>[\w-]+)/$',RestaurantDetailView.as_view(),
name="detail"),
url(r'^(?P<slug>[\w-]+)/delete/$', RestaurantDeleteView.as_view(),
name="restaurant-delete"),
]
delete.html
<form method="post" action="" >{% csrf_token %}
<p>Are you sure you want to delete <strong> {{ obj }}</strong>?</p>
<input type="submit" value="DELETE" />
</form>
method in your delete.html is currently "t", change to "post" and see if that works.
Your form action is pointing to root url that is /.
This route is determined by the RestaurantListViews and it is accesed via GET method.
In your example, you are trying to access this using POST, thus you're getting the error.
To make use of your RestaurantDeleteView change the action property in your form to point to an existing restaurant, like:
<form method="post" action="{your_existing_restaurant_slug}/delete" >
{% csrf_token %}
...
...

NoReverseMatch at /index/

I have been through all of the similar issues and I have gotten nowhere and I have gone through the djangogirls and the officail Django tutorials and as far as I can tell it should be working.
In the polls/templates/index.html file I have this:
[...]
{% if forms %}
<ul>
{% for form in forms %}
<li>
<h1><a href="{% url 'form_detail' pk=form.pk %}">
{{ form.fname }}
</a></h1>
[...]
In my polls/urls.py file I have this:
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
[...]
url(r'^index/$', 'polls.views.site_index'),
[...]
url(r'^form/(?P<pk>\d+)/$', views.form_detail, name='form_detail'),
[...]
In my polls/views.py file I have this:
from django.shortcuts import render, render_to_response, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from .models import Nform, Choice, Question, Post
from django.template import loader
from django.utils import timezone
from django.views import generic
from django.contrib import auth
from django.db import models
from .form import PostForm
def site_index(request):
forms = Nform.objects.order_by('-published_date')
return render_to_response('polls/index.html', {'forms': forms})
def form_detail(request, pk):
current_form = get_object_or_404(Nform, pk=pk)
fame = current_form.fname
latest_question_list = Question.objects.filter(for_form=fame).order_by('-pub_date')
choice_quest_list = []
text_quest_list = []
form = PostForm()
for i in range(len(latest_question_list)):
if len(latest_question_list[i].choice_set.all()) == 0:
text_quest_list.append(latest_question_list[i])
else:
choice_quest_list.append(latest_question_list[i])
return render(request, 'polls/read_only.html', {'choice_quest_list': choice_quest_list, 'text_quest_list': text_quest_list, 'form_name': fame, 'form': form})
[...]
I am assume that I have made a very simple mistake somewhere and I would be very grateful to anyone who finds it.
See this issue for pics.
Here is a link to my code.
Thanks :)
This is happening because you have defined a variable named app_name in your application urls.py.
When you define that variable, it becomes your url namespace.
You either have to reverse your url like this:
<h1><a href="{% url 'polls:form_detail' pk=form.pk %}">
or remove the app_name variable to use the url name directly.
Read more about reversing url names # django-docs

Categories

Resources