如何将story_author名称与request.user相关联?

时间:2017-11-08 12:23:05

标签: python django forms associated-object

我的第一个问题是,一旦我保存故事,故事。作者将不会与request.user关联。

因此它带来了另一个问题,我必须从用户列表中添加story_author,然后手动选择故事的作者。

Here is my damin looks like

models.py

class StoryAuthor(models.Model):
"""
Model representing a author.
"""
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

def get_absolute_url(self):
    """
    Returns the url to access a particular story_author instance.
    """

    return reverse('stories_by_author', args=[str(self.id)])

def __str__(self):
    """
    String for representing the Model object.
    """
    return self.user.username

class Story(models.Model):
    author = models.ForeignKey(StoryAuthor,related_name='stories',null=True)

    sb_thing = models.CharField(max_length=30,null=True)
    sb_story = models.CharField(max_length=30,null=True)
    sb_name = models.CharField(max_length=30,null=True)

views.py

def story_new(request):
    if request.method == "POST":
       form = StoryForm(request.POST)
       #form.StoryAuthor = request.user
       if form.is_valid():
           story = form.save(commit=False)
           StoryAuthor = request.user
           story.published_date = timezone.now()
           story.save()
           return redirect('story_detail', pk=story.pk)
       else:
           form = StoryForm()
           return render(request, 'story/story_create.html', {'form': form})

1 个答案:

答案 0 :(得分:2)

您的StoryAuthor模型强制您根据需要创建相应的实例,如下所示:

if form.is_valid():
    story = form.save(commit=False)
    story.author, _ = StoryAuthor.objects.get_or_create(user=request.user)
    # ...
    story.save()

请参阅get_or_create上的文档。