我几乎是Django的新手。由于我现在想要开始游戏,我想深入研究 基于通用类的视图 。我已经想出了如何使用模板视图,但现在我想去创建视图。
我有这些表格:
class LearningObjectiveForm(ModelForm):
class Meta:
exclude = ['trainee']
这些模型:
class LearningObjective(models.Model):
trainee = models.ForeignKey(Trainee, blank = True)
learning_objective = models.TextField()
class Trainee(models.Model):
username = models.TextField()
...
class Topic(models.Model):
trainee = models.ForeignKey(Trainee, blank = True)
learning_objective = models.ManyToManyField(LearningObjective, blank = True, null = True)
topic = models.TextField()
这创建视图:
class CreateLearningObjective(CreateView):
model = LearningObjective
form = LearningObjectiveForm
def form_valid(self, form):
self.object = form.save(commit=False)
if self.request.user.is_authenticated():
self.object.trainee = self.request.user
self.object.save()
return super(CreateLearningObjective, self).form_valid(form)
我的网址:
from django.conf.urls import patterns, url
from programm import views
from .views import LearningObjectiveView, CreateLearningObjective
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^learning_objective/$', LearningObjectiveView.as_view(), name = 'learning_objective'),
url(r'^learning_objective_add/$', CreateLearningObjective.as_view(), name = 'learning_objective_add'),
)
模板:
<form action="{% url 'learning_objective_add' %}" method="post">
{% csrf_token %}
<textarea name="learning_objective" rows="4"></textarea>
<p><select name="topic" size="6" multiple>
{% for lO in learning_objectives %}
{% for t in lO.topic_set.all %}
<option>{{ t.topic }}</option>
{% endfor %}
{% endfor %}
</select></p>
<input type="submit" value="Absenden"/>
</form>
很遗憾,当我尝试提交帖子时,我只收到Cannot assign None: "LearningObjective.trainee" does not allow null values.
错误。有人可以帮帮我吗?我真的陷入困境,无法在这里做什么:/
答案 0 :(得分:2)
将您的urls.py更改为:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^learning_objective/$', LearningObjectiveView.as_view(), name = 'learning_objective'),
url(r'^learning_objective_add/$', CreateLearningObjective.as_view(), name = 'learning_objective_add'),
)
错误是您的第二个网址('^ learning_objective')拦截了对第三个网址的发布请求。这就是你应该在正则表达式末尾添加$
的原因。
由于/
设置,POST
次观看也需要APPEND_SLASH
斜杠。