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
Related
I am trying to customize the signup redirect url using allauth in django 3. I am getting this error, instead:
NoReverseMatch at /accounts/candidate-signup/
Reverse for 'candidate_profile' with no arguments not found. 1 pattern(s) tried: ['accounts/profile/(?P<username>[^/]+)/$']
views.py
from django.shortcuts import render
from django.views import View
from .models import CandidateProfile
from .forms import CandidateProfileForm
from allauth.account import app_settings
from allauth.account.views import SignupView
from allauth.account.utils import complete_signup
from allauth.exceptions import ImmediateHttpResponse
class CandidateSignUpView(SignupView, View):
def get(self, request, *args, **kwargs):
form = self.form_class(request.POST)
return render(request, self.template_name, {'form': form})
def form_valid(self, form):
self.user = form.save(self.request)
self.user.is_candidate = True
self.user.save()
success_url = f'profile/{self.user.username}/'
try:
return complete_signup(
self.request,
self.user,
app_settings.EMAIL_VERIFICATION,
self.success_url,
)
except ImmediateHttpResponse as e:
return e.response
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('candidate-signup/', views.CandidateSignUpView.as_view(), name='candidate_signup'),
path('company-signup/', views.CompanySignUpView.as_view(), name='company_signup'),
path('profile/<str:username>/', views.CandidateProfileView.as_view(), name='candidate_profile'),
]
django/conf/global_settings.py
LOGIN_REDIRECT_URL = 'candidate_profile'
html
<form class="signup" id="signup_form" method="post" action="{% url 'candidate_signup' %}">
{% csrf_token %}
{{ form.as_p }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
A working solution would redirect from the signup page to /accounts/profile/<str:username>/
You have two issues in CandidateSignUpView:
You're passing self.success_url to complete_signup, instead of passing success_url, which is defined locally in form_valid method. As self.success_url is None (it is defined in SignupView and inherited in your CandidateSignUpView), complete_signup is receiving None for success_url parameter, so it uses default success_url after login.
You should better not construct urls manually. For this you'd better use reverse and pass view name and according arguments, so instead of success_url = f'profile/{self.user.username}/' you'd better use success_url = reverse('candidate_profile',kwargs={'username':self.user.username}). See more about reverse here.
So, your CandidateSignUpView should be something like this:
from django.shortcuts import render
from django.views import View
from .models import CandidateProfile
from .forms import CandidateProfileForm
from allauth.account.views import SignupView
from allauth.account.utils import complete_signup
from allauth.exceptions import ImmediateHttpResponse
from django.http.response import HttpResponse
from django.urls.base import reverse
class CandidateSignUpView(SignupView, View):
def get(self, request, *args, **kwargs):
form = self.form_class(request.POST)
return render(request, self.template_name, {'form': form})
def form_valid(self, form):
self.user = form.save(self.request)
self.user.is_candidate = True
self.user.save()
# success_url = f'profile/{self.user.username}/'
success_url = reverse('candidate_profile',kwargs={'username':self.user.username})
try:
return complete_signup(
self.request,
self.user,
app_settings.EMAIL_VERIFICATION,
# self.success_url,
success_url
)
except ImmediateHttpResponse as e:
return e.response
I have a one page app with a form and a data table. The page load fine, but the problem is the Form is not working when I press the "SUBMIT" Button.
When I press the "SUBMIT" Button it give me this error Method Not Allowed (POST): /home/
Thanks you for the help guys!
views.py
def _get_form(request, formcls, prefix):
data = request.POST if prefix in request.POST else None
return formcls(data, prefix=prefix)
all_items = List.objects.all
class Myview(TemplateView):
template_name = 'data_list/home.html'
all_items = List.objects.all
def get(self, request, *args, **kwargs):
return self.render_to_response({'scrape': Scrape(prefix="scrape_pre"), 'all_items': all_items})
def scrape(self, request, *args, **kwargs):
scrape = _get_form(request, Scrape, 'scrape_pre')
if request.method == "POST":
scrape = _get_form(request, Scrape, 'scrape_pre')
if scrape.is_valid():
print("Worked")
return self.render_to_response({'scrape': scrape})
def home(self, request, *args, **kwargs):
all_items = List.objects.all
return render(request, "data_list/home.html", {"all_items": all_items})
forms.py
class Scrape(forms.ModelForm):
url = forms.CharField()
class Meta:
model = List
fields = ["item", "site"]
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path("", views.add, name="add"),
path("scrape/", views.scrape, name="scrape"),
path("home/", views.Myview.as_view(), name="home"),
path("delete/<list_id>", views.delete, name="delete"),
path("datacontent/<list_id>", views.datacontent, name="datacontent")
]
home.html
<div>
<form action="" method="post" >
{% csrf_token %}
{{ scrape|crispy }}
<pre></pre>
<button class="btn btn-outline-info" type="submit" value="Submit">SUBMIT</button>
<pre></pre><pre></pre><pre></pre><pre></pre>
</form>
</div>
<table class="table">
.....
You can't send a post request (method='post' in the form definition) if your backend doesn't implement the post function, which is responsible for responding the post requests. You should change your 'scrape' function to 'post'.
Upon providing valid data and submitting a form, I get the following: Forbidden (CSRF cookie not set.): /membership/success/. I have a {% csrf_token %} in my template and my settings.py middleware is configured for CSRF.
#urls.py
from django.contrib import admin
from django.urls import path, include
from membership import views as ms_views
membership_patterns = ([
path("", ms_views.RegistrationPage.as_view(), name="register"),
path("success/", ms_views.SuccessPage.as_view(), name="success")
], 'membership')
urlpatterns = [
path('admin/', admin.site.urls),
path('membership/', include(membership_patterns, namespace="new_members"))
]
# membership/views.py
from django.shortcuts import render
from django.template.loader import get_template
from django.views import View
from django.http import HttpResponse, HttpResponseRedirect
from membership.forms import RegisterForm
from django.urls import reverse
# Create your views here.
class RegistrationPage(View):
def get(self, request):
register_page = get_template('membership/signup.html')
register_form = RegisterForm()
return HttpResponse(register_page.render({'form' : register_form}))
def post(self, request):
submitted_form = RegisterForm(request.POST)
if submitted_form.is_valid():
return HttpResponseRedirect(reverse('membership:success'))
return HttpResponse(reverse('membership:register'))
class SuccessPage(View):
def get(self, request):
return HttpResponse("Success")
# signup.html
{% extends 'index.html' %}
{% block content %}
<form action="{% url 'membership:success' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
Once the form is submitted and valid, I'm expecting a 302 to occur. Like I said though I get 403 forbidden.
Since your success page has no logic, you can choose to exempt CSRF token for that.
Import the following module
from django.views.decorators.csrf import csrf_exempt
and put #csrf_exempt at the start of function
#csrf_exempt
def get(self, request):
return HttpResponse("Success")
Refer to https://docs.djangoproject.com/en/2.2/ref/csrf/
However, it is better to include {% csrf_token %} for each template you use to ensure consistent passing around of CSRF token
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.
I have a problem with my template tag url. The redirect not work when i click on button.
Django version => 1.9
Python version => 2.7
In my urls.py(main) i have:
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from memoryposts.views import home, profile, preregistration
urlpatterns = [
url(r'^$', home, name="home"),
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', admin.site.urls),
url(r'^memory/', include("memoryposts.urls", namespace="memory")),
url(r'^avatar/', include('avatar.urls')),
url(r'^accounts/', include('registration.backends.hmac.urls')),
url(r'^preregistration/', preregistration, name="preregistration"),
url(r'^profile/', profile, name="profile"),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In my urls.py(apps) i have:
from django.conf.urls import url
from django.contrib import admin
from .views import (
memory_list,
memory_create,
memory_detail,
memory_update,
memory_delete,
)
urlpatterns = [
url(r'^$', memory_list, name='list'),
url(r'^create/$', memory_create, name='create'),
url(r'^(?P<slug>[-\w]+)/$', memory_detail, name='detail'),
url(r'^(?P<slug>[-\w]+)/edit/$', memory_update, name='update'),
url(r'^(?P<slug>[-\w]+)/delete/$', memory_delete, name='delete'),
]
In my views.py(apps) i have:
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post
from .forms import PostForm
def home(request):
return render(request, "base.html")
def profile(request):
return render(request, "profile.html")
def preregistration(request):
return render(request, "preregistration.html")
def memory_create(request):
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Succès !")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "memory_create.html", context)
def memory_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
context = {
"title":instance.title,
"instance":instance,
}
return render(request, "memory_detail.html", context)
def memory_list(request):
queryset = Post.objects.all()
context = {
"object_list": queryset,
}
return render(request, "memory_list.html", context)
def memory_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Mis à jour !")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title":instance.title,
"instance":instance,
"form": form,
}
return render(request, "memory_create.html", context)
def memory_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Supprimer !")
return redirect("posts:list")
In my template html i have:
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' %}"> Update</a></button>
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:delete' %}"> Delete</a></button>
The redirect not work with this template tag.
can you help me please :) ?
From doc here URL dispatcher
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' %}"> Update</a></button>
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:delete' %}"> Delete</a></button>
You should put what you 'slug' in your button, like this (if slug is 200)
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' 200 %}"> Update</a></button>
Usually will look like this:
{% for slug in slug_list %}
<button type="button" class="btn btn-primary"><a id="back-profile" href="{% url 'memory:update' slug %}"> Update</a></button>
{% endfor %}