Tuesday, June 28, 2016

Re: django form data not saving to database

I removed 'default' attribute and replaced OneToOneField with ForeignKey of Post Model still it is not saving to database.
Do I need to override the save method as I did in Category Model.
If yes,then any solution??

On Tuesday, June 28, 2016 at 5:44:16 PM UTC+5:30, kaustubh tripathi wrote:
Hi everyone!

I am creating a simple webapp using django where a user can login, choose one of the given category and create a post under the chosen category.

I am having trouble in creating a post. When I create a  new post through django form the date isn't saved to database. I log in to the django-admin to check if the post is created but the 'post' table remains empty.
 
Here are the necessary code snippets:

"Category model"
class  Category(models.Model):
   
    name = models.CharField(max_length=128,unique=True)
    slug = models.SlugField()
    def save(self,*args,**kwargs):
        self.slug = slugify(self.name)
        super(Category,self).save(*args,**kwargs)

    def __unicode__(self):
        return self.name
   
"Post Model"
class Post(models.Model):
    category = models.OneToOneField(Category,default='category')
    title = models.CharField(max_length=128,null=True)
    content = models.TextField(blank=True,null=True)   
   
    def __unicode__(self):
        return self.title

"Postform/forms.py"

class PostForm(forms.ModelForm):
    title = forms.CharField(max_length=128)
    content = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Post
        fields = ('title','content')

"create_post function/views.py"

def create_post(request,category_name_slug):
   
    created = False
    instance = get_object_or_404(Category,slug=category_name_slug)
    if request.method == 'POST':
        form = PostForm(data=request.POST or None,instance=instance)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            created = True
        else:
            print form.errors
    else:
        form = PostForm()
    context={
        'form':form,
        'instance':instance,       
        'created':created
    }
    return render(request,"add_post.html",context)


Any solution??

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0cf89106-7a6e-45c3-96ce-790400d4d225%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment