Answer the question
In order to leave comments, you need to log in
Why is data not being written from a Django form to the database?
Does not want to write data from the form to the database. At the same time, the message comes that the post was added successfully. Here is my code:
models.py
class Post(models.Model):
STATUS_CHOICES = (
('unpublished', 'Unpublished'),
('published', 'Published'),
)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts_created', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
body = models.TextField(max_length=5000, null=False, blank=False)
image = models.ImageField(upload_to='images/%Y/%m/%d/')
created = models.DateField(auto_now_add=True, db_index=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=11, choices=STATUS_CHOICES, default='unpublished')
anonymity = models.SmallIntegerField()
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
class PostCreateForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'body', 'image','anonymity')
@login_required
def post_create(request):
if request.method == 'POST':
post_form = PostCreateForm(instance=request.user, data=request.POST, files=request.FILES)
if post_form.is_valid():
cd = post_form.cleaned_data
post_new = post_form.save(commit=False)
#post.user = Profile.objects.get(user=request.user.id)
post_new.user = request.user
post_new.save()
messages.success(request, 'Add post successfully')
else:
messages.error(request, 'Error add your post')
else:
post_form = PostCreateForm(instance=request.user)
return render(request,
'posts/post/create.html',
{'section': 'posts',
'post_form': post_form})
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question