需要帮助在通用视图中获取form_valid的正确实例

时间:2015-12-01 22:19:42

标签: django django-models django-forms django-views django-generic-views

我无法弄清楚如何为我的通用视图的form_valid部分获取正确的实例。 我试图允许用户在他们的项目墙上发帖(有点像Facebook)。我需要将帖子与单个项目相关联(用户可以拥有多个项目)。实例应该是pk还是项目名称?任何示例代码或帮助将非常感谢!我很难理解当你创建一个新帖子时,它知道与哪个项目相关联。

视图

char buf[100];
scanf("%99[^\n]%*1[\n]", buf);

模型

class NewPost(CreateView):
    model = ProjectPost
    form_class = ProjectPostForm
    template_name = 'howdidu/new_post.html'

    def form_valid(self, form):
        newpost = form.save(commit=False)
        form.instance.user = self.request.user
        newpost.save()
        self.object = newpost
        return super(NewPost, self).form_valid(form)

    def get_success_url(self):
        project_username = self.request.user.username
        project_slug = self.object.slug
        return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})

形式

class UserProject(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    project_overview = models.CharField(max_length=1000)
    project_picture = models.ImageField(upload_to='project_images', blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    project_views = models.IntegerField(default=0)
    project_likes = models.IntegerField(default=0)
    project_followers = models.IntegerField(default=0)
    slug = models.SlugField(max_length=100, unique=True) #should this be unique or not?

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(UserProject, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.title

class ProjectPost(models.Model):
    project = models.ForeignKey(UserProject)
    title = models.CharField(max_length=100)
    post_overview = models.CharField(max_length=1000)
    date_created = models.DateTimeField(auto_now_add=True)
    post_views = models.IntegerField(default=0)
    post_likes = models.IntegerField(default=0)

1 个答案:

答案 0 :(得分:1)

好的,在这种情况下,我建议使用类似

的网址
url(r'^(?P<pk>\d+)/post/add/$', views.NewPostCreateView.as_view(), name='...'),

然后是像

这样的视图
class NewPost(CreateView):
   model = ProjectPost
   form_class = ProjectPostForm
   template_name = 'howdidu/new_post.html'

   def form_valid(self, form):
      self.object = form.save(commit=False)

      # Find project by using the 'pk' in the URL
      project = get_object_or_404(UserProject, pk=self.kwargs['pk'])

      # Then just set the project on the newPost and save()
      self.object.project = project
      self.object.save()

      return super(NewPost, self).form_valid(form)

   def get_success_url(self):
      # Unchanged ...

我在您的代码中看到您尝试与用户做某事但我不明白为什么您的帖子没有用户字段(您可能想要添加created_by)并且UserProject应该已经有用户设置。

我还假设用户首先进入他/她的项目,所以你知道他正在添加帖子的项目是他的。如果不是这样,那么只需更改逻辑以通过常规查询获取UserProject。例如如果每个用户有一个项目(再次,仅作为示例),可能使用`UserProject.objects.get(user = self.request.user)。

无论如何,我在这里做了一些假设,但希望主要的问题是如何在newPost上设置项目,这在我的例子中得到了解答。