2016-02-03 49 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