2016-02-03 76 views
1

我一直在努力彻底的DjangoGirls教程,并试图改善的部分上添加注释的应用程序 - TutorialExtensions的Django:指定当前用户为外键意见模型

我已经添加了注释的简单照片博客应用程序,但我试图做的是取代author = models.CharField(max_length=200)替代方案,将存储当前/登录的用户谁是评论照片实例,然后让我显示在photo_detail模板。

我还以为是靠近使用author = models.ForeignKey(User, related_name='Commenter')但经过了一个错误:

NOT NULL constraint failed: timeline_comment.author_id

这里是我的models.py一个照片模式和评论模式consisiting:

class Photo(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) 
    title = models.CharField(max_length=120) 
    slug = models.SlugField(unique=True) 
    image = ProcessedImageField(upload_to=upload_location, 
     null=True, 
     blank=False, 
     processors=[Transpose(), ResizeToFit(1000, 1000, False)], 
     format='JPEG', 
     options={'quality': 50}, 
     width_field="width_field", 
     height_field="height_field") 
    height_field = models.IntegerField(default=0) 
    width_field = models.IntegerField(default=0) 
    description = models.TextField(max_length=1000) 
    updated = models.DateTimeField(auto_now=True, auto_now_add=False) 
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) 

class Comment(models.Model): 
    post = models.ForeignKey('timeline.Photo', related_name='comments') 
    author = models.CharField(max_length=200) 
    text = models.TextField(max_length=1000) 
    created_date = models.DateTimeField(default=timezone.now) 

的相关视图:

def photo_detail(request, slug=None): 
    if not request.user.is_authenticated(): 
     return HttpResponseRedirect("/accounts/login") 

    instance = get_object_or_404(Photo, slug=slug) 

    if request.method == "POST": 
     form = CommentForm(request.POST) 
     if form.is_valid(): 
      comment = form.save(commit=False) 
      comment.post = instance 
      comment.save() 
      return redirect('timeline:detail', slug=instance.slug) 
    else: 
     form = CommentForm() 

    share_string = quote_plus(instance.description) 

    context = { 
     "title": instance.title, 
     "instance": instance, 
     "share_string": share_string, 
     "form": form, 
    } 

    return render(request, "photo_detail.html", context) 

我的for ms.py:

class CommentForm(forms.ModelForm): 
    text = forms.CharField(widget=forms.Textarea, label='Leave a comment: ') 
    class Meta: 
     model = Comment 
     fields = [ 
      "text", 
     ] 

最后的photo_detail视图模板:

<div class="row"> 
    <div class="col-md-12" id="comments"> 
     <p> 
      {% if instance.comments.count == 0 %} 
      No Comments 
      {% elif instance.comments.count == 1 %} 
      {{ instance.comments.count }} Comment 
      {% else %} 
      {{ instance.comments.count }} Comments 
      {% endif %} 
     </p> 
     <hr style="margin-top: 10px;"> 
      {% for comment in instance.comments.all %} 
       <div class="comment"> 
        <div class="date pull-right">{{ comment.created_date | timesince }} Ago</div> 
        <strong>{{ comment.author }}</strong> 
        <p>{{ comment.text|linebreaks }}</p> 
       </div> 
       <hr> 
      {% empty %} 
       <p>No comments here yet :(</p> 
      {% endfor %} 
    </div> 
</div> 

{% if user.is_superuser or user.is_authenticated %} 
<div class="row"> 
    <div class="col-md-12"> 
     <form method="POST" class="comment-form" action=''> 
      {% csrf_token %} 
      {{ form | crispy }} 
      <button type="submit" class="comment-add btn btn-lg btn-purple">Add</button> 
     </form> 
    </div> 
</div> 
{% endif %} 

可能有人建议这样做的最好的方法?任何帮助将非常感谢!谢谢。

回答

3

使用ForeignKey是正确的[1] - 缺点是您需要在视图中指定。在comment = form.save(commit=False)后面加一行:

comment.author = request.user 

它会起作用。

[1]尽管您不希望related_name作为“评论者”(因为它指的是您访问来自用户的评论的方式:默认为comment_set,这更有意义)。

+0

完美的作品!谢谢! – David