我尝试创建表单以将博客添加到已登录用户的订阅列表中。 现在我只对form_valid的第一部分感兴趣直到'除了'
class AddBlogToSubList(CreateView):
model = SubscriptionList
form_class = SubsListForm
template_name = 'blog/add_blog_to_sub_list.html'
success_url = reverse_lazy('blog:blog-list')
def form_valid(self, form):
try:
# first I'm trying to find out if an instance of a
# SubscriptionList model is in the database
model_instance = self.request.user.subscription_list
# Then I create an instance of a form with kwarg 'instance'
# to work with the default model instance
f = SubsListForm(self.request.POST, instance=model_instance)
# As far as I understand here I get a instance of a model in
# the database with the ability to update it as I've mentioned
# earlier instance=model_instance
existing_instance = f.save(commit=False)
blog = Blog.objects.get(pk=self.kwargs['blog_pk'])
# update a subscription list of a current user with a new blog
existing_instance.blogs_in_subscription.add(blog)
# save an updated instance
existing_instance.save()
f.save_m2m()
return super(AddBlogToSubList, self).form_valid(form)
except SubscriptionList.DoesNotExist:
pass
我期望的是,如果我正在更新已经在数据库中的订阅列表的实例(露水到实例= model_instance,根据django文档)'用户'属性将已设置。但是我得到了这个错误:
File "D:\PyDocs\taskagain\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
328. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /blogs/3/add_to_subscription/
Exception Value: NOT NULL constraint failed: blog_subscriptionlist.user_id
表格
from django.forms import ModelForm
from blog.models import SubscriptionList
class SubsListForm(ModelForm):
class Meta:
model = SubscriptionList
fields = []
网址
urlpatterns = [
url(r'^$', BlogList.as_view(), name='blog-list'),
url(r'^(?P<blog_pk>\d+)/$', BlogDetail.as_view(), name='blog-detail'),
url(r'^(?P<blog_pk>\d+)/add_to_subscription/$', AddBlogToSubList.as_view(), name='add-to-subscription'),
url(r'^(?P<blog_pk>\d+)/subscriptions/$', SubscriptionListView.as_view(), name='subscription-list'),
url(r'^(?P<blog_pk>\d+)/create/$', PostCreate.as_view(), name='post-create'),
url(r'^(?P<blog_pk>\d+)/(?P<post_pk>\d+)/$', PostDetail.as_view(), name='post-detail'),
url(r'^(?P<blog_pk>\d+)/(?P<post_pk>\d+)/update/$', PostUpdate.as_view(), name='post-update'),
url(r'^(?P<blog_pk>\d+)/(?P<post_pk>\d+)/delete/$', PostDelete.as_view(), name='post-delete'),
模型
class SubscriptionList(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
related_name='subscription_list')
blogs_in_subscription = models.ManyToManyField(Blog, related_name='in_subscription_lists',
blank=True)
def __str__(self):
return "%s subscription list" % self.user.username
谢谢。