我有一个基于类的视图,它显示一个页面并处理POST请求,如下所示:
class citywall (View):
def get(self, request, *args, **kwargs):
template_name = 'citywall.html'
city_slug = kwargs['city_slug']
context = self.get_context_data(city_slug)
return render_to_response(template_name, context, RequestContext(request))
def post(self, request, *args, **kwargs):
if request.is_ajax:
if request.POST.has_key('comment'):
#process comment
...
if request.POST.has_key('vote'):
#process vote
...
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试使用AJAX POST表单时,正在发送两个请求.Ajax请求然后是常规的POST请求.
这是我在html中的评论表:
<form class="comment_form" data-id="{{post.id}}" method="POST" >{% csrf_token %}
<textarea rows = "1" name="comment" class="form-control" placeholder="Write a comment..." ></textarea>
<button type="submit" class="btn btn-info">Go!</button>
</form>
Run Code Online (Sandbox Code Playgroud)
这是jQuery代码:
var comment_form = $('.comment_form')
comment_form.submit(function(){
var post_id = $(this).data('id');
var comment = $(this).find('textarea[name="comment"]').val();
$.ajax({
url: …Run Code Online (Sandbox Code Playgroud) 这是错误:
MultiValueDictKeyError at /add_city/
"Key 'city_image' not found in <MultiValueDict: {}>"
Run Code Online (Sandbox Code Playgroud)
这是POST信息:
Variable Value
country u'Bahrain'
csrfmiddlewaretoken u'NyuznsyqteRfmgkUC9W0TpZeuuU99WMZ'
name u'vv'
city_image u'Tuna_8.jpg'
Run Code Online (Sandbox Code Playgroud)
这是观点:
class addCity(View):
def get(self, request, *args, **kwargs):
countries = Country.objects.all()
return render_to_response('addCity.html', {'countries':countries}, RequestContext(request))
def post(self, request, *args, **kwargs):
name = request.POST['name']
country = Country.objects.get(name=request.POST['country'])
image = request.FILES['city_image']
city = City.objects.create(name=name, country=country, image= image)
return HttpResponse("success")
Run Code Online (Sandbox Code Playgroud)
这是QueryDict我的时间print request.POST:
<QueryDict: {u'country': [u'Bahrain'], u'csrfmiddlewaretoken': [u'NyuznsyqteRfmgkUC9W0TpZeuuU99WMZ'], u'name': [u'bb'], u'city_image': [u'user.png']}>
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,关键的'city_image'显然存在于QueryDict中,那么为什么我会收到一个错误,说key'city_image'找不到?
这是我的html文件.
<form method="POST" …Run Code Online (Sandbox Code Playgroud) 当用户收到从django发送的电子邮件时,我希望显示名称而不是电子邮件地址send_mail().
例如:
当使用以下代码发送电子邮件时,收到该电子邮件的人会to@ex.com在其收件箱中看到.我希望显示一个名字.
send_mail('subject', 'content', from@ex.com, ['to@ex.com'], fail_silently=False)
Run Code Online (Sandbox Code Playgroud)
就像公司向用户发送电子邮件一样,我们看不到电子邮件地址,而是看到公司名称.