mcd
mcd

Reputation: 7156

Django model inserting foreign key from same model

I am building a simple comment app in Django. The app allows replies to comments and uses the same model to store comments and replies. My issues is when I try to insert a new reply, the parentpost(FK to parent comment) inserts as NULL. When I use the admin interface to insert a reply, it properly stores the parentpost ID for the parentpost I choose. So I know the issue is not within my model but within my view.

/MODEL/

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()

/VIEW/

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))

Upvotes: 2

Views: 3226

Answers (1)

dting
dting

Reputation: 39287

You are trying to set the parentpost ForeignKey by id.

You should either use:

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

or (see Django: Set foreign key using integer?):

newPost = UserPost(name = nameIn, post = postIn)
newPost.parentpost_id = pid

Upvotes: 1

Related Questions