0

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

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

这是我的大明看起来像

模型.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)

视图.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})
4

1 回答 1

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

于 2017-11-08T12:29:15.550 回答