开发者

Django Forms, Foreign Key and Initial return all associated values

I a working with Django forms. The issue I have is that Foreign Key fields and those using initial take all associated entries (all records associated with that record other then the one entry i wanted e.g instead of getting a primary开发者_StackOverflow中文版 key, i get the primary key, post subject, post body and all other values attributed with that record). The form and the other associated queries still work well, but this behaviour is clogging my database. How do i get the specific field i want instead of all records. An example of my models is here:

A form field for childParentId returns postID, postSubject and postBody instead of postID alone.

Also form = ForumCommentForm(initial = {'postSubject':forum.objects.get(postID = postID), }) returns all records related to postID.

class forum(models.Model):
postID = models.AutoField(primary_key=True)
postSubject = models.CharField(max_length=25)
postBody = models.TextField()
postPoster = models.ForeignKey(UserProfile)
postDate =  models.DateTimeField(auto_now_add=True)
child = models.BooleanField()
childParentId = models.ForeignKey('self',blank=True, null=True)
deleted = models.BooleanField()

def __unicode__(self):
    return u'%s %s %s %s %s' % (self.postSubject, self.postBody, self.postPoster, self.postDate, self.postID


I sort of figured this out using the following.

in forms.py

class ForumCommentForm(forms.ModelForm):
    postBody = forms.CharField(widget=forms.Textarea(attrs={'cols':'70', 'rows':'5'}))
    childParentId = forms.CharField(widget=forms.TextInput)
    class Meta:
        model = forum

in views.py

@login_required def forum_view(request,postID):

post = list(forum.objects.filter(postID = postID)|forum.objects.filter(childParentId__in = postID))

if request.method == 'POST':

    form = ForumCommentForm(request.POST)
    if form.is_valid():
        form.save()
        #this reloads the query to include updated values
        post = list(forum.objects.filter(postID = postID)|forum.objects.filter(childParentId__in = postID))
        #this returns an empty form 
        form = ForumCommentForm()

else:
    parent = forum.objects.get( postID = postID)
    form = ForumCommentForm(initial = {'postSubject':parent.postSubject, 'child':'1', 'childParentId':parent.postID})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜