'method' object has no attribute 'inner_html' - python

I have made a web site by seeing django tutorial. https://docs.djangoproject.com/en/1.11/intro/
I got an error
AttributeError at /polls/1/
'method' object has no attribute 'inner_html' .
Traceback says
Traceback:
File "/Users/XXX/django/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
130. response = self.process_exception_by_middleware(e, request)
File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
128. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/XXX/djangostudy/polls/views.py" in detail
40. form = VoteForm(question=obj)
File "/Users/XXX/djangostudy/polls/forms.py" in __init__
21. self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}<br>'
Exception Type: AttributeError at /polls/1/
Exception Value: 'method' object has no attribute 'inner_html'
My forms.py is like
from django import forms
class MyForm(forms.Form):
text = forms.CharField(max_length=100,required=False,label='テキスト')
class VoteForm(forms.Form):
choice = forms.ModelChoiceField(
queryset=None,
label='選択',
widget=forms.RadioSelect,
empty_label=None,
error_messages={
'required':"You didn't select a choice.",
'invalid_choice':"invalid choice.",
},
)
def __init__(self,question,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['choice'].queryset = question.choice_set.all()
self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}<br>'
Setting of radio button is written in detail.html,like
<!DOCTYPE html>
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'poll_vote' question.id %}" method="post">
<!--<form action="" method="post">-->
{% csrf_token %}
{% for choice in question.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<!--{{ form }}-->
<input type="submit" value="Vote" />
</form>
</html>
views.py is
from django.shortcuts import render
from django.utils.html import mark_safe
from .models import Question
from django.http import HttpResponse
from django.shortcuts import Http404
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from django.views.generic import TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from .forms import MyForm
from .forms import VoteForm
# Create your views here.
def index(request):
return render(request,'polls/index.html',{
'questions': Question.objects.all(),
})
def detail(request,pk):
obj = get_object_or_404(Question,pk=pk)
if request.method == "POST":
form = VoteForm(question=obj,data=request.POST)
if form.is_valid():
return redirect('polls:results',pk)
else:
form = VoteForm(question=obj)
return render(request,'templates/polls/detail.html',{
'form':form,
'question': obj,
})
def vote(request,pk):
pass
def results(request,pk):
obj = get_object_or_404(Question,pk=pk)
return render(request,'polls/results.html',{
'question':obj,
})
def form_test(request):
if request.method == "POST":
#request.POST???
form = MyForm(data=request.POST)
if form.is_valid():
pass
else:
form = MyForm()
return render(request,'polls/form.html',{
'form':form,
})
I do not know how to fix it.I cannot understand why this error happen. WHat should I do to fix this?
The tutorial had inner_html,so I think it is necessary to do something needed.But,is it useless?
I wanna show the page like
in this part
self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}'
I wanna make this page is radio button page.

Related

TypeError at / __init__() takes 1 positional argument but 2 were given

I copied this code from maxg203 https://github.com/maxg203/Django-Tutorials
I had another errors but I managed to solve them but when it came to this one I stayed for a solid 4 hours trying to solve it and until now I didn't manage to
I am still a beginner in Django
My Models.py:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
post = models.CharField(max_length=500)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Friend(models.Model):
users = models.ManyToManyField(User)
current_user = models.ForeignKey(User, related_name='owner', null=True, on_delete=models.CASCADE)
#classmethod
def make_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create(
current_user=current_user
)
friend.users.add(new_friend)
#classmethod
def lose_friend(cls, current_user, new_friend):
friend, created = cls.objects.get_or_create(
current_user=current_user
)
friend.users.remove(new_friend)
my Views.py:
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from home.forms import HomeForm
from home.models import Post, Friend
class HomeView(TemplateView):
template_name = 'home/home.html'
def get(self, request):
form = HomeForm()
posts = Post.objects.all().order_by('-created')
users = User.objects.exclude(id=request.user.id)
friend = Friend.objects.filter(current_user=request.user)
friends = friend.users.all()
args = {
'form': form, 'posts': posts, 'users': users, 'friends': friends
}
return render(request, self.template_name, args)
def post(self, request):
form = HomeForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user
post.save()
text = form.cleaned_data['post']
form = HomeForm()
return redirect('home:home')
args = {'form': form, 'text': text}
return render(request, self.template_name, args)
def change_friends(request, operation, pk):
friend = User.objects.get(pk=pk)
if operation == 'add':
Friend.make_friend(request.user, friend)
elif operation == 'remove':
Friend.lose_friend(request.user, friend)
return redirect('home:home')
My Forms.py
from django import forms
from home.models import Post
class HomeForm(forms.ModelForm):
post = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Write a post...'
}
))
class Meta:
model = Post
fields = ('post',)
My urls.py
from django.conf.urls import url
from home.views import HomeView
from . import views
urlpatterns = [
url('', views.HomeView.as_view(), name='home'),
url('connect/(?P<operation>.+)/(P<pk>\d+)/', views.change_friends, name='change_friends')
]
My Html:
{% extends 'base.html' %}
{% block content %}
<div class="container">
<div class="col-md-8">
<h2>Home</h2>
<form method="post">
{% csrf_token %}
{{ form.post }}
<br>
<button type="submit">Submit</button>
</form>
<h2>{{ text }}</h2>
{% for post in posts %}
<h1>{{ post.post }}</h1>
<p>Posted by {{ post.user.get_full_name }} on {{ post.created }}</p>
{% endfor %}
</div>
<div class="col-md-4">
<h2>Other People</h2>
{% for user in users %}
<a href="{% url 'accounts:view_profile_with_pk' pk=user.pk %}">
<h3>{{ user.username }}</h3>
</a>
{% if not user in friends %}
<a href="{% url 'home:change_friends' operation='add' pk=user.pk %}">
<button type="button" class="btn btn-success">Add Friend</button>
</a>
{% endif %}
{% endfor %}
<h2>Friends</h2>
{% for friend in friends %}
<a href="{% url 'accounts:view_profile_with_pk' pk=friend.pk %}">
<h3>{{ friend.username }}</h3>
</a>
<a href="{% url 'home:change_friends' operation='remove' pk=friend.pk %}">
<button type="button" class="btn btn-default">Remove Friend</button>
</a>
{% endfor %}
</div>
</div>
{% endblock %}
Traceback:
Traceback (most recent call last):
File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\core\handlers\exception.py", line 47,
in inner
response = get_response(request)
File "C:\Users\daghe\anaconda3\envs\env\lib\site-packages\django\core\handlers\base.py", line 179, in
_get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
[30/Sep/2020 16:45:25] "GET / HTTP/1.1" 500 60123
i am getting TypeError at /
init() takes 1 positional argument but 2 were given
Finally, I solved it by putting _as.view in my project's home URL

I Want to store the form data to the database

I want store the form data into database ('subject_code' is the table name or model name) but when I press the submit button its throwing an error
the error is
TypeError at /subjectnamewithcode/
_wrapped_view() missing 1 required positional argument: 'request'
please help me.
this is my view.py
from django.conf.urls import url, include
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import User
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
from .models import signupform, Universityname, facultyhours, subject_code, class_number
def home(request):
count=User.objects.count()
return render(request, 'home.html', {
'count':count
})
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
usernamedb=request.POST['username']
passworddb=request.POST['password1']
emaildb=request.POST['email']
signup_info=signupform(usernamedb=usernamedb,passworddb=passworddb,emaildb=emaildb)
signup_info.save()
form.save()
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'registration/signup.html', {
'form': form
})
#login_required()
def secret_page(request):
return render(request, 'secret_page.html')
class SecretPage(LoginRequiredMixin,TemplateView):
template_name = 'secret_page.html'
#login_required()
def University_names(request):
return render(request, 'createtimetable/university_or_collegename.html')
#login_required()
def universityNames_store_in_database(request):
university_name=request.POST["universityname"]
Department_id=request.POST["departmentid"]
Department_name=request.POST["departmentname"]
university_dept_info=Universityname(university_name=university_name,Department_id=Department_id,Department_name=Department_name)
university_dept_info.save()
return redirect('/faculty_hours/')
#login_required()
def faculty_hours(request):
return render(request, 'createtimetable/faculty_hours.html',)
#login_required()
def map_faculty_with_hours(request):
faculty_name=request.POST["facultyname"]
faculty_unique_name=request.POST["facultyuniquname"]
faculty_total_hours_in_a_week=request.POST["facultytotalnumberofhours"]
map_faculty_with_hours_db=facultyhours(faculty_name = faculty_name, faculty_unique_name = faculty_unique_name, faculty_total_hours_in_a_week = faculty_total_hours_in_a_week)
map_faculty_with_hours_db.save()
return render(request, 'createtimetable/faculty_hours.html')
#login_required()
def subject_code(request):
return render(request, 'createtimetable/subjects_code.html')
def subjectnamewithcode(request):
subject_name=request.POST["subjectname"]
subject_id=request.POST["subjectcode"]
subjectnamewithcodedb=subject_code(subject_name = subject_name, subject_id = subject_id)
subjectnamewithcodedb.save()
return render(request, 'createtimetable/subjects_code.html')
#login_required()
def class_number(request):
return render(request, 'createtimetable/class_number.html')
#login_required()
def class_with_numbers(request):
class_name=request.POST["classname"]
class_number1=request.POST["classroomnumber"]
class_with_number_db=class_number(class_name=class_name,class_number=class_number1)
class_with_number_db.save()
return render(request, 'createtimetable/class_number.html')
#login_required()
def userdetails(request):
# allusers=signupform.objects.all()
return render(request, "secret_page.html")#, {'uusers': allusers})
this is my model.py
from django.db import models
# Create your models here.
class signupform(models.Model):
usernamedb=models.CharField(max_length=250)
passworddb=models.CharField(max_length=250)
emaildb=models.CharField(max_length=250)
class Universityname(models.Model):
university_name=models.CharField(max_length=250)
Department_name=models.CharField(max_length=250)
Department_id=models.CharField(max_length=250)
class facultyhours(models.Model):
faculty_name=models.CharField(max_length=250)
faculty_unique_name=models.CharField(max_length=250)
faculty_total_hours_in_a_week=models.CharField(max_length=250)
class subject_code(models.Model):
subject_name=models.CharField(max_length=250)
subject_id=models.CharField(max_length=250)
class class_number(models.Model):
class_name=models.CharField(max_length=250)
class_number=models.CharField(max_length=250)
this is my urls.py
from django.contrib import admin
from django.urls import path, include
from mysite.core import views
urlpatterns = [
path('', views.home, name='home'),
path('signup/', views.signup, name='signup'),
path('secret/',views.secret_page, name='secret' ),
path('secret2/', views.SecretPage.as_view(), name='secret2'),
path('accounts/', include('django.contrib.auth.urls')),
path('University_names/', views.University_names, name='University_names'),
path('universityNames_store_in_database/', views.universityNames_store_in_database, name='universityNames_store_in_database'),
path('faculty_hours/', views.faculty_hours, name='faculty_hours'),
path('map_faculty_with_hours/', views.map_faculty_with_hours, name='map_faculty_with_hours'),
path('subject_code/', views.subject_code, name='subject_code'),
path('subjectnamewithcode/', views.subjectnamewithcode, name='subjectnamewithcode'),
path('class_number/', views.class_number, name='class_number'),
path('class_with_numbers/', views.class_with_numbers, name='class_with_numbers'),
path('admin/', admin.site.urls),
]
this is my html form
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row justify-content-center">
<div class="col-6">
<div class="card">
<div class="card-body">
<h2>Mapping Subject And Code</h2>
<form method="post" action="/subjectnamewithcode/">
{% csrf_token %}
{{ form|crispy }}
<label>Add Subject</label><br>
<input type="text" name="subjectname" required class="textinput textInput form-control"><br>
<label>Subject Code</label><br>
<input type="text" name="subjectcode" required class="textinput textInput form-control"><br>
<button type="submit" class="btn btn-primary">ADD</button>
NEXT
</form>
</div>
</div>
</div>
</div>
{% endblock %}
This error I am getting
TypeError at /subjectnamewithcode/
_wrapped_view() missing 1 required positional argument: 'request'
Request Method: POST
Request URL: http://127.0.0.1:8000/subjectnamewithcode/
Django Version: 2.2.4
Exception Type: TypeError
Exception Value:
_wrapped_view() missing 1 required positional argument: 'request'
Exception Location: /Users/vajra/Documents/DJANGO/mysite/core/views.py in subjectnamewithcode, line 88
Python Executable: /Users/vajra/Documents/DJANGO/venv/bin/python
Python Version: 3.7.3
Python Path:
['/Users/vajra/Documents/DJANGO',
'//miniconda3/lib/python37.zip',
'//miniconda3/lib/python3.7',
'//miniconda3/lib/python3.7/lib-dynload',
'/Users/vajra/Documents/DJANGO/venv/lib/python3.7/site-packages']
Server time: Wed, 4 Sep 2019 17:40:43 +0000
Traceback Switch to copy-and-paste view
/Users/vajra/Documents/DJANGO/venv/lib/python3.7/site-packages/django/core/handlers/exception.py in inner
response = get_response(request) …
▶ Local vars
/Users/vajra/Documents/DJANGO/venv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response
response = self.process_exception_by_middleware(e, request) …
▶ Local vars
/Users/vajra/Documents/DJANGO/venv/lib/python3.7/site-packages/django/core/handlers/base.py in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
/Users/vajra/Documents/DJANGO/mysite/core/views.py in subjectnamewithcode
subjectnamewithcodedb=subject_code(subject_name = subject_name, subject_id = subject_id) …
▶ Local vars

Form validation error not being raised in django

I cannot get my Django form to raise a ValidationError when I try to create a custom field validation. I can see the new hidden input field, but when I try to enter a value it doesn't seem to detect an error.
I also tried def clean(self) instead of clean_honeypot() and that didn't work either.
What am I doing wrong?
forms.py:
from django import forms
class SuggestionForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
suggestion = forms.CharField(widget=forms.Textarea)
honeypot = forms.CharField(required=False, widget=forms.HiddenInput, label="Leave Empty")
def clean_honeypot(self):
honeypot = self.cleaned_data['honeypot']
if len(honeypot) > 0:
raise forms.ValidationError(
'Honeypot should be left empty. Bad bot!'
)
return cleaned_data
views.py:
from django.contrib import messages
from django.core.mail import send_mail
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from . import forms
def hello_world(request):
return render(request, 'home.html')
def suggestion_view(request):
form = forms.SuggestionForm()
if request.method == 'POST':
form = forms.SuggestionForm(request.POST)
if form.is_valid():
send_mail(
'Suggestion from {}'.format(form.cleaned_data['name']),
form.cleaned_data['suggestion'],
'{name} <{email}>'.format(**form.cleaned_data),
['leigh.christopher2#gmail.com'])
messages.add_message(request, messages.SUCCESS,
"Thanks for your suggestion")
return HttpResponseRedirect(reverse('suggestion'))
return render(request, 'suggestion_form.html', {'form': form})
template:
{% extends "layout.html" %}
{% load static %}
{% block title %}Suggest an idea!{% endblock %}
{% block content %}
<div class="container">
<div class="row">
<form action="" method="POST">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class="button">
</form>
</div>
</div>
{% endblock %}

Django: after submitting the form, why the redirected url is an empty page

After submitting the form (input), it will redirect to another page(result).
The thing is it will indeed go to the desired url, but the content is empty. (It is not empty if I open it separately). Thanks for your suggestion in advance.
input -- url
from inputform import views
from django.views.generic.list import ListView
from inputform.views import input
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^result_list/$',ResultView.as_view(),name='result'),
(r'^input/$', RedirectView.as_view(url='/result_list/')),
}
input --views
from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import Inputform
from inputform.models import Input
from dupont.models import Result
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.list import ListView
#csrf_exempt
def input(request):
if request.method == 'POST':
form = Inputform(request.POST)
if form.is_valid():
cd = form.cleaned_data
print (cd['company'])
form.save()
return redirect(reverse,('','result_list'))
Result --views.py
class ResultView(ListView):
context_object_name = 'result_list'
template_name = 'result_list.html'
queryset = Result.objects.all()
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
context['input'] = Input.objects.all()
return context
Result -- html
<form action="result_list/" method="post">{% csrf_token %}
<div class="field" >
<label> Select the Region:
{{ form.regionlist }}
{% for region in form.regionlist.choices %}
<option value="{{ val }}" {% ifequal data.val val %}selected {% endifequal %}></option>
{% endfor %}
</label>
</div>
<div class="fieldWrapper">
<p><input type="submit" value="Submit" /></p></div>
</form>
As mentioned in the comments the correct parameter to pass to reverse() is 'result', i.e the name of the url.
If you're using django 1.7 or higher you can skip the reverse part and django will do it automatically for you.
def input(request):
if request.method == 'POST':
form = Inputform(request.POST)
if form.is_valid():
cd = form.cleaned_data
print (cd['company'])
form.save()
return redirect('result')
should work for you

Django do not render ModelForm

I am working on a little project on Django, I have had some issues on rendering ModelForm. In main.html tag {{form.ad_p}} doesn't seem working. I only see "Save" button and don't see any ModelForm fields.
If I put below code to shell
form = AddPath()
form.as_p()
I see:
form.as_p()
u'<p><label for="id_name">Name:</label> <input id="id_name" maxlength="200" name="name" type="text" /></p>\n<p><label for="id_route_data">Route data:</label> <textarea cols="40" id="id_route_data" name="route_data" rows="10">\r\n</textarea></p>'
Can you explain, what am I doing wrong?
I already searched on stackoverflow, but same problem hasn't been resolved. I hope, I'll be more lucky
models.py:
from django.db import models
from django.contrib.auth.models import User
class Path(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length='200')
route_data = models.TextField()
def __unicode__(self):
return self.name
views.py:
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core.context_processors import csrf
from google_maps.forms import AddPath
def index(request):
args = {}
args.update(csrf(request))
form = AddPath()
return render_to_response('main.html', args)
def add_path(request):
#me = request.user
me = 'test'
if request.method == 'POST':
form = AddPath(request.POST)
if form.is_valid():
tmpForm = form.save(commit=False)
tmpForm.user = me
tmpForm.save()
return HttpResponse('Saved')
else:
return HttpResponse(form.errors)
main.html
{% extends 'basis.html' %}
{% block leftbar %}
<form action={% url 'add_path' %} method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="hidden", id="coordinate" name="coordinate"/>
<input type="submit" name="submit" value="Save"/>
</form>
{% endblock %}

Categories

Resources