views.py
def userlogout(request):
logout(request)
return HttpResponseRedirect(reverse('userlogin'))
def Search(request):
if request.method == 'POST':
search=request.GET['srch']
if search:
match=Blog.objects.filter(Q( blog_title_icontains=search)|
Q( blog_description_icontains=search)|
Q(blogcategories_icontains=search) )
if match:
return render (request,"search.html",{"sr":match})
else:
messages.error(request,"no results found")
else:
return HttpResponseRedirect('/search/')
return render (request,'index.html')
#
index.html
<form action="{%url 'search' %}" method="post" class="form-inline my-2 my-lg-0 header-search">
{% csrf_token %}
<input class="form-control mr-sm-2" type="search" placeholder="Search here..." name="Search" required="">
<button class="btn btn1 my-2 my-sm-0" type="submit">
<i class="fas fa-search"></i>
</button>
</form>
blog/urls.py
path('search/', views.Search, name='search'),
*****it gives me error:
Exception Type: MultiValueDictKeyError
Exception Value:
'srch'
please help me how can i search in my blog by using existing template.
You have several errors.
Your search field is called Search, not srch. I don't know where you got srch from since you never use it in the template.
Your form is being submitted by POST, but you are trying to get the data from the GET.
But in fact a search form should be submitted by GET, not POST, since it is not making changes in the backend and could conceivably be cached.
So you need:
<form action="{%url 'search' %}" method="get" class="form-inline my-2 my-lg-0 header-search">
...
def Search(request):
search=request.GET['Search']
if search:
Related
I am using this code for a register form. But the post request doesn't work and give me an error :
ValueError at /register/
The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead.
views.py
class RegisterView(View):
def get(self,request):
register_form = RegisterForm()
return render(request, 'register.html',{'register_form':register_form})
def post(self,request):
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get("email", "") user_psw = request.POST.get("password", "")
user_profile=UserProfile()
user_profile.username = user_name
user_profile.email = user_name
user_profile.password=make_password(user_psw)
user_profile.save()
send_register_email(user_name,"register")
pass
urls.py
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
import xadmin
from users.views import LoginView , RegisterView
import xadmin
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('',TemplateView.as_view(template_name="index.html"),name="index"),
path('login/',LoginView.as_view(),name="login"),
path('register/',RegisterView.as_view(),name="register"),
path("captcha/", include('captcha.urls'))
]
forms.py
class RegisterForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True, min_length=5)
captcha = CaptchaField(error_messages={"invalid":"please input correctly"})
register.html
<div class="tab-form">
<form id="email_register_form" method="post" action="{% url 'register' %}" autocomplete="off">
<input type='hidden' name='csrfmiddlewaretoken' value='gTZljXgnpvxn0fKZ1XkWrM1PrCGSjiCZ' />
<div class="form-group marb20 ">
<label>邮 箱</label>
<input type="text" id="id_email" name="email" value="None" placeholder="请输入您的邮箱地址" />
</div>
<div class="form-group marb8 ">
<label>密 码</label>
<input type="password" id="id_password" name="password" value="None" placeholder="请输入6-20位非中文字符密码" />
</div>
<div class="form-group marb8 captcha1 ">
<label>验 证 码</label>
{{ register_form.captcha }}
<img src="/captcha/image/2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011/" alt="captcha" class="captcha" /> <input id="id_captcha_0" name="captcha_0" type="hidden" value="2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011" /> <input autocomplete="off" id="id_captcha_1" name="captcha_1" type="text" />
</div>
<div class="error btns" id="jsEmailTips"></div>
<div class="auto-box marb8">
</div>
<input class="btn btn-green" id="jsEmailRegBtn" type="submit" value="注册并登录" />
<input type='hidden' name='csrfmiddlewaretoken' value='5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy' />
{% csrf_token %}
</form>
</div>
request information
Request information
USER
AnonymousUser
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'9dQylxY3htVbBMNFunnYwgnarkfjSVioz5rhu0uADk0ShssTFGl9144OEwJoUlPX'
email
'1#1.com'
password
'123456'
captcha_0
'2f3f82e5f7a054bf5caa93b9b0bb6cc308fb7011'
captcha_1
''
FILES
No FILES data
no matter whether the verification code I input is wrong or right, the error is always The view users.views.RegisterView didn't return an HttpResponse object. It returned None instead.
Django's view should return some response.
From doc:
A view function, or view for short, is simply a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image . . . or anything, really.
So you need to add return statement to post() method, e.g. like this:
def post(self,request):
...
return render(request, 'register.html',{'register_form':register_form})
Hi im trying to pass a name from a form to a view in django using POST. There are no errors in the execution but its passing nothing from the template and dont know if i doing something wrong here. Im starting with django so i can have newbie errors. If u need more information tell me pls.
Views.py
def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
form = EmpModelForm(data=request.POST)
if form.is_valid():
empresa_selec = form.cleaned_data['nombre']
#"empresa_selec" that's the empty variable
Models.py
class Empresa_modelo(models.Model):
nombre = models.CharField(max_length=100,blank=True,null=True)
Forms.py
class EmpModelForm(forms.ModelForm):
class Meta:
model = Empresa_modelo
fields = ["nombre"]
template.html
<div class="container-fluid">
<form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
<p>Empresa</p>
<input type="text" name="empresa">
<br>
<button type="submit">Subir</button>
</form>
<br>
<a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
</div>
You haven't got a field called nombre in your template; you only have empresa.
That's presumably because you don't ouput your EmpModelForm in the template. You don't show your render call in the view, but assuming you pass it as form, you should just do {{ form.as_p }} in the template.
Try using:
<input type="text" name="nombre">
There is no field named empresa.
Had a look at your code,there are a couple of issues.First you are not using the model form defined in your forms.py file in your template. Second you have defined an input text box with the name that you are not referring in your views. Either use the model form or use the same name of your input text box in your views.
def crear_pdf(request):
empresa_selec = ""
form = EmpModelForm()
if request.method == 'POST':
form = EmpModelForm(data=request.POST)
if form.is_valid():
empresa_selec = form.cleaned_data['nombre']
else:
return render(request,"template.html",{"form":form})
And in your template you can edit as such:
<div class="container-fluid">
<form method="POST" enctype="multipart/form-data" action="{% url 'crear_pdf' %}">{% csrf_token %}
{{ form.as_p }}
<br>
<button type="submit">Subir</button>
</form>
<br>
<a class="btn btn-primary" href="{% url 'crear_pdf' %}">Atras</a>
</div>
Hope this helps.
I'm getting this error when submit:
CSRF verification failed. Request aborted.
I've got this far following the documentation, but I don't fully understand it and it's definitely wrong. I just want to take a query word from my search box(form) and pass it to a python script as an argument. I'm new to Django and getting stuck on the easiest things.
In models.py:
class QueryForm(forms.Form):
query = forms.CharField(label='query',max_length=100)
I added this line to my urls.py
url(r'^results/$', 'tweemo.views.results'),
On my homepage where my search box is I have this code for my form:
<form action="/home/results/" method="post">
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
In views.py I added these two functions:
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
return render(request, 'results.html', {'form': form})
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
MY results.html contains just this:
<form action="/home/results/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
You must just add the {% csrf_token %} tag inside EVERY <form></form> tag which has method to be post in your template.
So the below markup should be corrected:
<form action="/home/results/" method="post">
{% csrf_token %}
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
Well the problem is that you are not passing the csrf token to the form , you need to pass the csrf token to the render function in order for it to be applied in the form . To accomplish this you need to associate the csrf token to the request.
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('results.html', args)
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
I have a HTML form in Django and I'm not using Django form class.
Now I want to know how can I process this html form? (method is POST)
The form is genereted by xsl but the final generated form is like this:
<form method="POST" id="settingSubmit" action="/archive/agentUpdate/1">
<input value="1" name="AgentID" datatype="Int">
<input value=" agent 1" name="AgentName">
<input value=" agent 1 Description" name="AgentDescription">
<input value="submit" id="sendbutton" type="submit">
</form>
and the view:
def agentUpdate(request,id):
agentName = request.POST['AgentName']
return render_to_response('archive/base.html',{
'agentName':agentName
},
RequestContext(request, ))
urls.py:
urlpatterns = patterns('archive.views',
url(r'^agentUpdate/(?P<id>\w+)/$',
'agentUpdate',
name='agent_Update'),
)
Error:
MultiValueDictKeyError at /archive/agentUpdate/2/
"Key 'AgentName' not found in <QueryDict: {}>"
Fix your form's HTML by adding type="hidden" to your form fields, otherwise they will not be submitted as part of your request.
You should also add {% csrf_token %} which required for CSRF protection. This is enabled by default on all POST requests.
<form method="POST" id="settingSubmit" action="/archive/agentUpdate/1">
{% csrf_token %}
<input value="1" type="hidden" name="AgentID" datatype="Int">
<input value=" agent 1" type="hidden" name="AgentName">
<input value=" agent 1 Description" type="hidden" name="AgentDescription">
<input value="submit" id="sendbutton" type="submit">
</form>
Finally, in your view:
from django.shortcuts import render
def agentUpdate(request,id):
if request.method == 'POST':
agentName = request.POST.get('AgentName')
return render(request, 'archive/base.html', {'agentName':agentName})
Regarding MultiValueDictKeyError you should do
agentName = request.POST.get('AgentName')
Also will be better to check if this is a POST request
if request.POST:
agentName = request.POST.get('AgentName')
Then with this data you can do whatever you want - validate, save it to database, process in any other way.
Also instead of render_to_response you can use shortcut render
return render(request, 'archive/base.html', {'agentName': agentName})
Add csrf token to your form
<form method="POST" id="settingSubmit" action="/archive/agentUpdate/1">
{% csrf_token %}
<input value="1" type="hidden" name="AgentID" datatype="Int">
<input value=" agent 1" type="hidden" name="AgentName">
<input value=" agent 1 Description" type="hidden" name="AgentDescription">
<input value="submit" id="sendbutton" type="submit">
</form>
In views.py add
from django.shortcuts import render_to_response
def agentUpdate(request,id):
if request.method == 'POST':
agentName = request.POST.get('AgentName')
variables = RequestContext(request, {'agentName':agentName})
return render_to_response('archive/base.html', variables)
In urls.py
urlpatterns = patterns('archive.views',
(r'^agentUpdate/(\w*)\/?$','agentUpdate'),
)
I have a simple form I want users to be able to log into; here is the template code with the CSRF tag in it:
<html>
<head><title>My Site</title></head>
<body>
<form action="" method="post">{% csrf_token %}
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
</body>
</html>
Now here is my views.py page. The question is where do I put in the CSRF supporting part (right now I get a CFRS token error) in my view and how do i do it?
from django.contrib import auth
def login_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
# Correct password, and the user is marked "active"
auth.login(request, user)
# Redirect to a success page
return HttpResponseRedirect("/account/loggedin/")
else:
# Show an error page
return HttpResponseRedirect("account/invalid/")
def logout_view(request):
You have to add the RequestContext to the view that renders the page with the {% csrf_token %} line in it. Here is the example from the tutorial:
# The {% csrf_token %} tag requires information from the request object, which is
# not normally accessible from within the template context. To fix this,
# a small adjustment needs to be made to the detail view, so that it looks
# like the following:
#
from django.template import RequestContext
# ...
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p},
context_instance=RequestContext(request))
The context_instance=RequestContext(request) part is the important part. This makes the RequestContext available to the form template when it is rendered.