我在Django中有一个非常简单的代码,而且每次都会出现这个错误。
表单的内容很好地保存在模型中,但是当我想使用反向时出现此错误:'unicode' object has no attribute 'get'
有我的代码:
views.py:
class PastaView(View):
template_name = 'pasta.html'
form_class = PastaForm
def get(self, request, *args, **kwargs):
item = get_object_or_404(Pasta, url=kwargs['hash'])
return render(request, self.template_name, {'pasta': item, 'form': self.form_class})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
item = get_object_or_404(Pasta, url=kwargs['hash'])
if form.is_valid():
item.text = form.cleaned_data['text']
item.save()
return reverse('detail_pasta', kwargs={'hash': item.url})
forms.py:
class PastaForm(Form):
text = forms.CharField(widget=forms.Textarea)
models.py:
class Pasta(models.Model):
text = models.TextField(verbose_name='Text', blank=False, null=False)
url = models.CharField(verbose_name='url', max_length=255, blank=False, null=False)
def __unicode__(self):
return u'%s' % self.text
def save(self):
super(Pasta, self).save()
if not self.url:
self.url = baseconvert(str(self).id, BASE10, BASE62)
self.save()
回溯
Environment:
Request Method: POST
Request URL: http://localhost:8000/pastabin/B/
Django Version: 1.8.2
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pastabin')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/snaaail/.virtualenvs/copy_pasta/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
223. response = middleware_method(request, response)
File "/home/snaaail/.virtualenvs/copy_pasta/local/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response
31. if response.get('X-Frame-Options', None) is not None:
Exception Type: AttributeError at /pastabin/B/
Exception Value: 'unicode' object has no attribute 'get'
感谢您的帮助。
答案 0 :(得分:3)
您的post
方法返回reverse
的结果,这是一个字符串,即URL。您实际上需要返回重定向响应。
redirect
快捷方式可以直接为您执行此操作:
from django.shortcuts import redirect
...
def post(self, request, *args, **kwargs):
...
return redirect('detail_pasta', hash=item.url)