我的第一个问题是,一旦我保存故事,故事。作者将不会与request.user关联。
因此它带来了另一个问题,我必须从用户列表中添加story_author,然后手动选择故事的作者。
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)
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})
答案 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
上的文档。