我的第一个问题是一旦我保存了一个故事,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})