我正在尝试将链接所携带的值传递给视图,以便视图返回所需的结果。详细地说,如下面的程序所示,我试图将home.html模板中模板变量“{{a}}”包含的值传递给views.py文件中的视图“tag_search”。另外,找到下面的urls.py.我使用了方法POST的表单,这样当单击链接时,变量'a'的值传递给我的'tag_search'视图。然而,当点击链接时,当前视图中的'tag_posted'变量具有值'None'。我没有得到如何将值传递给视图。请纠正我出错的地方。这种方法是好方法还是我们有不同的方法来做到这一点?
home.html下面
{% load staticfiles %}
{%load comments%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Sourav's blog</title>
<!-- Bootstrap Core CSS -->
{%block styling%}
<link href="{%static 'css/bootstrap.min.css'%}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{%static 'css/blog-post.css'%}" rel="stylesheet">
{%endblock styling%}
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Ideate</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="{%url 'blog_new_post'%}">New idea</a>
</li>
<!-- <li><a href="{%url 'blog_login'%}">Login</a></li> -->
{{user.is_authenticated}}
{% if user.is_authenticated %}
<li>
<a href="{%url 'blog_logout'%}">Logout</a>
</li>
{% else %}
<li>
<a href="{%url 'blog_login'%}">Login</a>
</li>
{% endif %}
<li>
<a href="#">Help</a>
</li>
{% if user.is_authenticated %}
<li>
<a href="#">Hi {{user.username}}</a>
</li>
{%else%}
{% endif %}
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Post Content Column -->
<div class="col-lg-8">
<!-- Blog Post -->
<!-- Title -->
<h1>Idea Blog</h1>
<!-- Author -->
<p class="lead">
by <a href="#">Sourav</a>
</p>
<hr>
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span>
Posted on
<!-- {%for i in blog_data%}
{{i.posted_on}}
{%endfor%}</p> -->
{{last_element.posted_on}}
<hr>
<!-- Preview Image -->
<img class="img-responsive" src="http://placehold.it/900x300" alt="">
<hr>
<!-- Post Content -->
<!-- <p>Below is the result</p> -->
<!-- <p>{{blog_data}}</p> -->
<p>
<!-- {%for i in blog_data%}
<h1>{{i.title}}</h1>
<p>{{i.description}}</p>
{%empty%}
<span>No data</span>
{%endfor%} -->
<!-- {{last_element}} -->
<h1>{{last_element.title}}</h1><span> posted by {{last_element.posted_by}}</span>
<p>Description : {{last_element.description}}</p>
{{last_element.image}}
<p>Tags : {{last_element.tags}}</p>
{% get_comment_count for blog.blogpost last_element.id as comment_count %}
<p>{{ comment_count }} comments have been posted.</p>
{% get_comment_list for blog.blogpost 1 as comment_list %}
{% for comment in comment_list %}
<p>Posted by: {{ comment.user_name }} on {{ comment.submit_date }}</p>
<p>Comment: {{ comment.comment }}</p>
{% endfor %}
{% get_comment_form for blog.blogpost last_element.id as form %}
<!-- A context variable called form is created with the necessary hidden
fields, timestamps and security hashes -->
<table>
<form action="{% comment_form_target %}" method="post">
{% csrf_token %}
{{ form }}
<tr>
<td colspan="1">
<input type="submit" name="submit" value="Post">
<input type="submit" name="preview" value="Preview">
<input type="hidden" name="next" value="{% url 'comment_posted' %}" />
</td>
</tr>
</form>
</table>
{% get_comment_list for blog.blogpost last_element.id as comment_list %}
{%for comment in comment_list%}
<li><b>{{comment.name}}</b> has posted comment on {{comment.submit_date}} </li>
<ul><li>{{comment.comment}}</li></ul>
<a name="c{{ comment.id }}"></a>
<a href="{% get_comment_permalink comment %}">
see comment details
</a>
{%endfor%}
</p>
</div>
<div class="col-md-4">
<!-- Blog Search Well -->
<form action = "{%url 'blog_search'%}" method = "POST">
<div class="well">
<h4>Blog Search</h4>
<div class="input-group">
{%csrf_token%}
<input type="text" class="form-control" name = "keyword", placeholder = "Enter search keyword">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
<!-- /.input-group -->
</div>
</form>
<!-- Blog Categories Well -->
<div class="well">
<h4>Tags</h4>
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled">
<!-- {%for a in tags_list%}
<a href="">{{a}}</a>
{%endfor%} -->
<!-- {%for a in tags_list%}
<a href="">{{a}}</a>
{%endfor%} -->
{%for a in tags_list%}
<form id = 'form1' action = "{%url 'tag_search'%}" method = "POST">
{%csrf_token%}
<!-- <a href = "" name = 'tag'>{{a}},</a> -->
<a href="javascript:;" onclick="document.getElementById('form1').submit();" name = 'tag'>{{a}},</a>
</form>
{%endfor%}
<!-- {%for a in tags_list%}
<a href="{%url 'tag_search'%}">{{a}}</a>
{%endfor%} -->
<!-- <li><a href="#">Category Name</a>
</li>
<li><a href="#">Category Name</a>
</li>
<li><a href="#">Category Name</a>
</li>
<li><a href="#">Category Name</a>
</li> -->
</ul>
</div>
<div class="col-lg-6">
<ul class="list-unstyled">
<li><a href="#">Category Name</a>
</li>
<li><a href="#">Category Name</a>
</li>
<li><a href="#">Category Name</a>
</li>
<li><a href="#">Category Name</a>
</li>
</ul>
</div>
</div>
<!-- /.row -->
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>Side Widget Well</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Sidebar Widgets Column -->
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
{%block javascript%}
<script src="{%static 'js/jquery.js'%}"></script>
<!-- Bootstrap Core JavaScript -->
<script src="{%static 'js/bootstrap.min.js'%}"></script>
{%endblock javascript%}
</body>
</html>
下面的views.py
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.db.models import Q
from .forms import *
# Create your views here.
def home(request):
print("I am home")
try:
blog_data = BlogPost.objects.all()
print("blog_data", blog_data)
except BlogPost.DoesNotExist:
blog_data = None
print("blog_data", blog_data)
try:
last_element = BlogPost.objects.filter(id = len(blog_data))[0]
print("last_element", last_element)
except BlogPost.DoesNotExist:
last_element = None
print("last_element", last_element)
tags_list = BlogPost.objects.values_list("tags", flat = True).distinct()
#tags_list = BlogPost.objects.all().distinct()
context = {'blog_data':blog_data, "last_element":last_element, "tags_list":tags_list}
#last_element = list(BlogPost.objects.all().reverse()[0])
print("last_element",last_element, "blog_data",blog_data,"context",context)
return render(request, 'blog/home.html', context)
# def home(request):
# blog_data = BlogPost.objects.all()
# context = {'blog_data':blog_data}
# print('context', context)
# last_element = BlogPost.objects.all().reverse()[0]
# #last_element = BlogPost.objects.all().reverse()[0]
# return render(request, 'blog/home.html', context)
def new_post(request):
if request.method == 'POST':
form = BlogForm(data = request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('home')
else:
form = BlogForm()
return render(request, 'blog/blogform.html', {'form':form })
def login_user(request):
username = password = ''
state = "Please log in"
if request.POST:
username = request.POST.get('Username')
password = request.POST.get('Password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
state = "You're successfully logged in!"
return HttpResponseRedirect('/blog/home')
else:
state = "Your account is not active, please contact the site admin."
else:
state = "Your username and/or password were incorrect."
#return render_to_response('main/login.html',{'state':state, 'username': username})
return render(request, "blog/login.html", {'state':state, 'username': username, 'next_page':"home.html"})
#return HttpResponseRedirect("home.html")
# def logout_user(request):
# logout(request)
# return(request, home)
# #return render(request,'blog/home.html')
def register_user(request):
username = password = password_again = email = ''
state = ''
if request.method == 'POST':
username = request.POST.get('Username')
password = request.POST.get('Password')
password_again = request.POST.get('Password_again')
email = request.POST.get('Email')
print('email', email)
if password == password_again:
password = make_password(password, salt = None, hasher = 'default')
else:
state = "Password and password re-entered do not match, please try again..."
return HttpResponseRedirect('login')
print("at 63")
try:
user = User.objects.get(username = username)
print('user at 67', user)
except Exception as e:
print("Error is :", e)
user = None
print("user", user)
try:
emailID = User.objects.get(email = email)
print("emailID", emailID)
except Exception as e:
print("Error is :", e)
emailID = None
print("emailID exception", emailID)
if user is not None:
state = 'Username already exists, please try another one...'
else:
if emailID is None:
new_user = User(username = username, password = password, email = email)
##Adding new logic for securityQAs vvv
#new_SQA = SecurityQA(user_email = email, security_question = security_question, security_answer = security_answer)
##Adding new logic for securityQAs ^^^
new_user.save()
#new_SQA.save()
state = 'You are successfully registered.. Thanks'
return HttpResponseRedirect('login')
else:
state = "Email ID already registered, try a new one.."
print('state at else', state)
#return HttpResponseRedirect('login')
return render(request, "blog/register.html", {'state':state, 'username':username, 'next_page':'home.html'})
def forgot_password(request):
pass
def comment_posted(request):
return render(request, "blog/comment_posted.html")
def blog_search(request):
qset = Q()
keyword = ''
keyword = request.POST.get('keyword')
print("keyword", keyword)
for word in keyword.split():
qset |= (Q(title__contains = word)|Q(description__contains = word))
print('qset', qset)
result = BlogPost.objects.filter(qset)
context = {'result':result}
return render(request, 'blog/blog_search.html', context)
def logout_user(request):
logout(request)
return reverse(redirect('home', request))
#return render(request, home)
def tag_search(request):
tag_posted = request.POST.get('tag')
print("tag_posted", tag_posted)
tagsearch_result = BlogPost.objects.filter(tags = tag_posted)
#tagsearch_result = BlogPost.objects.filter(tags = tag)
print("tagsearch_result", tagsearch_result)
context = {'tagsearch_result': tagsearch_result}
return render(request, 'blog/tag_search.html', context)
urls.py
from django.conf.urls import url, patterns
from django.contrib.auth.views import *
from . import views
from blog.templates.blog import *
urlpatterns = [
url(r'^home$', views.home, name = 'blog_home'),
url(r'^newpost$', views.new_post, name = 'blog_new_post'),
url(r'^login$', views.login_user, name = 'blog_login'),
url(r'^logout$', views.logout_user, name = 'blog_logout'),
url(r'^register$', views.register_user, name = 'blog_register'),
url(r'^resetpassword/passwordsent/$', password_reset_done, name = 'password_reset_done'),
url(r'^resetpassword/$', password_reset, name = 'password_reset'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm, name = 'password_reset_confirm'),
url(r'^reset/done/$', password_reset_complete, name = 'password_reset_complete'),
url(r'^comments/posted', views.comment_posted, name = 'comment_posted'),
url(r'^blogsearch/', views.blog_search, name = 'blog_search'),
#url(r'^tagsearch/(?P<a>)', views.tag_search, name = 'tag_search'),
url(r'^tagsearch/', views.tag_search, name = 'tag_search'),
]
答案 0 :(得分:1)
你永远不会放置&#34; a&#34;任何&lt;中的值输入&gt;你表单中的字段。 &LT; a&gt;标签不是表单元素。
答案 1 :(得分:0)
如果您希望变量成为POST数据的一部分,您需要将其设为隐藏输入的值,而不仅仅是锚标记的子项
<input type="hidden" name="whatever" value="{{a}}"/>