2

我正在 Django 中构建一个简单的评论应用程序。该应用程序允许回复评论并使用相同的模型来存储评论和回复。我的问题是当我尝试插入新回复时,父帖子(FK 到父评论)插入为 NULL。当我使用管理界面插入回复时,它会正确存储我选择的父帖子的父帖子 ID。所以我知道问题不在我的模型中,而是在我的观点中。

/型号/

class UserPost(models.Model):

name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True,
                        help_text='Unique value for product page URL, created from name.', editable = False)


post = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords", max_length=255, blank = True, null = True,
                                 help_text='Content for description meta tag')
meta_description = models.CharField(max_length = 255, blank = True, null = True,
                                    help_text = 'Content for description meta tag')
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
parentpost = models.ForeignKey('self', blank = True, null = True)

class Meta:
    #app_label = ''

    db_table = 'userposts'
    ordering = ['created_at']
    verbose_name_plural = 'UserPosts'

def __unicode__(self):
    return self.name

@models.permalink   
def get_absolute_url(self):
    return ('lync_posts', (), {'posts_slug': self.slug})

def save(self):
    if not self.id:
        d = datetime.datetime.now()
        s = d.strftime('%Y-%M-%d-%H-%M-%S-%f')

        slugfield = str(self.name + s)
        self.slug = slugfield

        super(UserPost, self).save()

/查看/

def reply(request, slugIn):

parentpostIn = UserPost.objects.get(slug = slugIn)

pid = parentpostIn.id
template_name = 'reply.html'

if request.method == 'POST':
    form = forms.ReplyPostForm(data = request.POST)
    # create a new item

    if form.is_valid(): # All validation rules pass
        # Process the data in form.cleaned_data
        # ...
        if form.is_valid():
            nameIn = form.cleaned_data['name']
            postIn = form.cleaned_data['post']

            newPost = UserPost(name = nameIn, post = postIn, parentpost = pid)
            newPost.save()
    return render_to_response(template_name, locals(), context_instance = RequestContext(request))

else:
    # This the the first page load, display a blank form
    form = forms.NewPostForm()

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

return render_to_response(template_name, locals(), context_instance=RequestContext(request))
4

1 回答 1

1

您正在尝试通过 id 设置 parentpost ForeignKey。

您应该使用:

newPost = UserPost(name = nameIn, post = postIn, parentpost = parentpostIn)

或(参见Django:使用整数设置外键?):

newPost = UserPost(name = nameIn, post = postIn)
newPost.parentpost_id = pid
于 2013-02-03T06:11:33.387 回答