这是追溯:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/myapp/addinterest/
Django Version: 1.8.2
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
132. `response = wrapped_callback(request, *callback_args, **callback_kwargs)`
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. `return view_func(request, *args, **kwargs)`
File "/~/myapp/views.py" in add_interest
155. `return render_to_response('add_interests.html', context, {'form': form})`
File "/Library/Python/2.7/site-packages/django/shortcuts.py" in render_to_response
45. `using=using)`
File "/Library/Python/2.7/site-packages/django/template/loader.py" in render_to_string
116. `template_name, context, context_instance, dirs, dictionary)`
File "/Library/Python/2.7/site-packages/django/template/engine.py" in render_to_string
220. `with context_instance.push(context):`
Exception Type: AttributeError at /myapp/addinterest/
Exception Value: 'dict' object has no attribute 'push'
这是我的代码:
网址:url(r'^addinterest/$', views.add_interest, name='add_interest'),
查看:
@login_required
def add_interest(request):
context = RequestContext(request)
if request.method == 'POST':
#create a form instance and populate it with data from the request
form = InterestForm(request.POST)
if form.is_valid():
#process data in form.clean_data
interest = form.cleaned_data['interest']
user.add_interest(interest)
return HttpResponseRedirect('add_interests.html', context)
else:
form=InterestForm()
return render_to_response('add_interests.html', context, {'form': form})
形式:
class InterestForm(forms.Form):
interest = forms.CharField(label="Enter a new Interest:", max_length=100)`
模板:
<div class="container">
<h1>Add Interests</h1>
</div> <!-- /container -->
<div class="container">
This is your list:
<ul>{% for i in user.profile.interests %}
<li>{{i}} <button type="button">Remove Interest</button>
{% endfor %}</ul>
</div> <!-- /container -->
<div class ="container">
<form action="{% url add_interest %}" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="Add Interest" />
</form>
</div>
我是Django的新手,所以我假设这是一个非常简单的修复,但我无法找到任何其他问题。对象没有属性&#39; push&#39;。
我的兴趣字段是用户个人资料模型的一部分。兴趣领域是一个ListView,我在这里已经看过很多次了。
class ListField(models.TextField):
__metaclass__ = models.SubfieldBase
description = "Stores a python list"
def __init__(self, *args, **kwargs):
super(ListField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value:
value = []
if isinstance(value, list):
return value
return ast.literal_eval(value)
def get_prep_value(self, value):
if value is None:
return value
return unicode(value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
在我的UserProfile模型中,这里是添加和删除兴趣。我怀疑这是问题的原因,但以下是这些功能。
class UserProfile(models.Model):
interests = ListField(blank=True)
def add_interest(self, value):
self.interests.insert(len(self.interests)+1, value)
#self.save()
def remove_interest(self, value):
self.interests.remove(value)
#self.save()
答案 0 :(得分:7)
你的render_to_response()
论点混淆了:
return render_to_response('add_interests.html', context, {'form': form})
documentation告诉你第二个参数是一个字典,第三个参数是上下文实例,但你交换了它们。
最好使用context_instance
参数作为关键字参数:
return render_to_response('add_interests.html', {'form': form}, context_instance=context)
答案 1 :(得分:0)
这里还有一个案例。即使论证是正确的,但你仍然得到错误,以下内容对我有用。
render_to_response
更改为渲染..../something.html
和context_dict
括在大括号内。 前:
context_dict = {}
context_dict.update(csrf(request))
return render(request,("xxxx/Test.html", context_dict), {})