Form validation failed in django - python

I have a simple form
forms.py
class CraveDataForm(forms.ModelForm):
class Meta:
model = crave_data
exclude=['date']
class CraveReplyForm(forms.ModelForm):
class Meta:
model = comments
exclude=['date', 'crave']
model.py
class crave_data(models.Model):
#person = models.ForeignKey(User)
post=models.TextField(blank = True,null = True)
date= models.DateTimeField()
def __unicode__(self):
return self.post
class comments(models.Model):
crave=models.OneToOneField(crave_data)
reply=models.CharField(max_length=1000, blank = True,null = True)
date= models.DateTimeField()
def __unicode__(self):
return self.reply
and views.py
def crave_view(request):
if (request.method=="POST"):
form1=CraveDataForm(request.POST, request.FILES)
if form1.is_valid():
crave_made = form1.save(commit=False)
crave_made.person = request.user
crave_made.save()
messages.success(request, 'You Registered Successfully')
else:
messages.error(request, 'Please enter all required fields')
else:
form1=CraveDataForm()
return render(request, "crave/crave.html", { 'form1' : form1 })
def comment_view(request):
if (request.method=="POST"):
form2 = CraveReplyForm(request.POST, request.FILES)
if form2.is_valid():
reply = form2.save(commit=False)
reply.person=request.user
#reply.crave = request.user
reply.save()
else:
messages.error(request, 'Please enter all required fields')
else:
form2 = CraveReplyForm()
return render(request, "crave/comment.html", { 'form2' : form2 })
my template fie crave.html
<form class="horizontal-form" role="form" action="/crave/" method="post" style="padding: 10px;">
{% csrf_token %}
<div class="form-group" >
<div class="col-sm-10">
{{ form1.post.label_tag }}{{ form1.post }} <br /><br>
</div>
</div>
<input type="submit" class="btn btn-success" value="crave" />
</form>
<form action="/crave/reply_get/">
<input type="submit">
</form>
my comment.html
<form class="horizontal-form" role="form" action="/crave/reply_get/" method="post" style="padding: 10px;">
{% csrf_token %}
<div class="form-group" >
<div class="col-sm-10">
{{ form2.reply.label_tag }} {{ form2.reply }} </br> </br>
</div>
</div>
<input type="submit" class="btn btn-success" value="reply" />
</form>
when i click on crave button i want to save data for form one only without saving data for second form. So comments will be for related posts only. Using foreign key. But i am getting the error here in "reply.crave = crave_made" i want to access the crave made from create_view view.
Help me.

Your forms are derived from UserCreationForm so fields of that form should also be present to make it valid.
But I think you want to inherit from ModelForm and not UserCreationForm.
So change your code as
class CraveDataForm(forms.ModelForm):
class Meta:
model = crave_data
exclude=['date']
class CraveReplyForm(forms.ModelForm):
class Meta:
model = comments
exclude=['date', 'crave']

Related

Unable to add comments to a post using a ModelForm in Django

views.py
def postdetail(request,pk): # Single Post view.
post = Post.objects.get(id=pk)
comment = post.comments.all()
comment_count = comment.count()
if request.user.is_authenticated:
if request.method == 'POST':
form = CommentForm(data=request.POST)
content = request.POST['cMessage']
if form.is_valid():
print("Yes valid")
form.instance.body = content
new_comment = form.save(commit=False)
print(new_comment)
new_comment.post = post
new_comment.user = request.user
new_comment.save()
return redirect('blog-home')
else:
form = CommentForm()
context = {
'comment_form': CommentForm,
'post' : post,
'comments': comment,
'count': comment_count,
}
return render(request,'post/postdetail.html', context=context)
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='comments')
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
# active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return f'Comment by {self.user} on {self.post}'
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
template
{% if request.user.is_authenticated %}
<!-- respond -->
<div class="respond">
<h3>Leave a Comment</h3>
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="">
{% csrf_token %}
<fieldset>
<div class="message group">
<label for="cMessage">Message <span class="required">*</span></label>
<textarea name="cMessage" id="cMessage" rows="10" cols="50" ></textarea>
</div>
<button type="submit" class="submit">Submit</button>
</fieldset>
</form> <!-- Form End -->
</div>
{% endif %}
There is no error being displayed neither If I am adding a comment using the shell/through admin panel but if I am trying to add the comment dynamically through the form then the comment is not getting saved.
I have added only the form in the template.
You have defined field body in your CommentForm. It's required in your form, because you didn't include blank=True argument in your model for this field. This means that when you POST request and check if form is valid with form.is_valid(), the form expects an element with a name body in the request. If it's not there, it will not validate and content won't be saved.
Make the following changes:
Change your view to
...
if request.method == 'POST':
form = CommentForm(data=request.POST)
if form.is_valid():
new_comment = form.save(commit=False)
new_comment.post = post
new_comment.user = request.user
new_comment.save()
return redirect('blog-home')
else:
print(form.errors) # or log it to a file, if you have logging set up
form = CommentForm()
...
Change your HTML to this:
...
<form name="contactForm" id="contactForm" method="post" action="">
{% csrf_token %}
<fieldset>
<div class="message group">
<label for="body">Message <span class="required">*</span></label>
<textarea name="body" id="cMessage" rows="10" cols="50" ></textarea>
{{ comment_form.body.errors }}
</div>
<button type="submit" class="submit">Submit</button>
</fieldset>
</form>
...
In views.py
def postdetail(request):
print(Comment.objects.all())
if request.method == 'POST':
form = CommentForm(data=request.POST)
content = request.POST['body']
if form.is_valid():
print("Yes valid")
new_comment = form.save(commit=False)
print(new_comment)
new_comment.post = post
new_comment.user = request.user
new_comment.save()
return redirect('blog-home')
else:
form = CommentForm()
return render(request,'temp/postdetail.html', context=context)
In html file
{% if request.user.is_authenticated %}
<div class="respond">
<h3>Leave a Comment</h3>
<form name="contactForm" id="contactForm" method="post" action="">
{% csrf_token %}
<textarea name="body"cols="30" rows="10"></textarea>
<button type="submit" class="submit">Submit</button>
</form>
</div>
{% endif %}
This worked for me.

Django file upload returns None

I'm trying to upload the image file using Django. I'm able to get the other form data but not the image file. request.FILES is blank. Below is my code.
models.py
class Module(models.Model):
title = models.CharField(max_length = 50)
slug = models.CharField(max_length = 50)
description = models.TextField(max_length = 500)
Forms.py
class ModuleAddForm(forms.ModelForm):
title = forms.CharField(max_length = 50, widget = forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Title'} ))
description = forms.CharField(max_length = 50, widget = forms.Textarea(attrs = {'class': 'form-control', 'placeholder': 'Description'} ))
image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)
class Meta:
model = Module
fields = ['title', 'description', 'image']
Views.py
form = ModuleAddForm(request.POST, request.FILES or None)
if form.is_valid():
title = form.cleaned_data['title']
description = form.cleaned_data['description']
image = request.FILES['image]
Html
<form class="kt-form" method = "POST" id="kt_form userform" enctype=”multipart/form-data” >{% csrf_token %}
<div class="form-group row">
<label class="col-3 col-form-label">Title</label>
<div class="col-9">
{{ form.title }}
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label">Description</label>
<div class="col-9">
{{ form.description }}
</div>
</div>
<div class="form-group row">
<label class="col-3 col-form-label">Image</label>
<div class="col-9">
{{ form.image }}
</div>
</div>
<button type="submit" class="btn btn-brand">Save</button>
</form>
When I print request.FILES it returned blank and also when I tried to get it using Key it returned MultiValueDict error. But when I print request.POST, image was there. But it was of no use because an image wasn't uploaded.
I'm using another model to store the image files of this model (Module) because it can contain multiple images. I've implemented the same logic in my other model and function. It's working there properly but not working here.
I'm using Django 2.2.
Like Arjun said, you have no image field in your model. You can create another ModelForm for your model with the image, and display that in addition to your other form on your webpage.
Take this as an example. A user form and a profile form where the profile has the image.
Forms.py
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = get_user_model()
fields = ['email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ['image']
views.py
if request.method == 'POST':
user_form = UserUpdateForm(request.POST, instance=request.user)
profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user)
if user_form.is_valid() and profile_form.is_valid():
user_form.save()
profile_form.save()
messages.success(request, f"Your account has been updated")
return redirect('profile')
jinja
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Profile Info</legend>
{{ user_form | crispy }}
{{ profile_form | crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>

Does not display data after filling in the template

I make comments on the site and cannot understand why, after the user has filled out comment forms, they are not displayed, I try to display them through a template
P.S
I need to display the text and the nickname that the user would enter
views.py
def CommentGet(request):
if request.method == 'POST':
comment = Comments(request.POST)
name = request.POST['name']
text = request.POST['text']
if comment.is_valid():
comment.save()
return HttpResponseRedirect(request.path_info)
comments = CommentModel.objects.all()
else:
comment = Comments(request.POST)
comments = CommentModel.objects.all()
return render(request, 'news/post.html', {'comment': comment,'comments':comments})
post.html
<form method="post" action="{% url 'comment' %}">
{% csrf_token %}
<input type="text" name="name" value="{{ name }}">
<input type="text" name="text" value="{{ text }}">
<input type="submit">
</form>
{% for comm in comments %}
<h1> {{ comm.name }} </h1>
<h1> {{ comm.text }} </h1>
{% endfor %}
models.py
class CommentModel(models.Model):
name = models.CharField(max_length=100)
text = models.TextField(default='')
dates = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-dates']
def __str__(self):
return self.name
I'd suggest using a ModelForm to make things simpler, Try something like this:
# views.py
def CommentGet(request):
if request.method == 'POST':
comment_form = CommentForm(request.POST)
comment_form.save()
else:
comment_form = CommentForm()
comments = CommentModel.objects.all()
return render(request, 'news/post.html', {'comment_form': comment_form,'comments':comments, })
# forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = CommentModel
fields = ['name', 'text']
Then, in your template, replace the two text fields with {{ comment_form }}

Django: Form is not valid

I am currently struggling to get my form to work properly. I created the form manually (template.html) and I can see all the data when I call it with print(request.POST) (in views.py - checkout) however form.is_valid(): (in views.py - checkout) doesn't work. Means my form is not valid.
I think the issue is, that I created the form manually and combined it with a model form where I want after validating my data with form.valid() save it in. Can anyone of you guys help me with my problem, why it's not valid?
template.html
<form action="{% url 'checkout:reserve_ticket' %}" method="post">
{% csrf_token %}
{% for ticket in event.tickets.all %}
<p>
{{ ticket.name }} for {{ ticket.price_gross }} with quantity:
<input type="hidden" name="order_reference" value="123456af">
<input type="hidden" name="ticket" value="{{ ticket.id }}">
<input type="hidden" name="ticket_name" value="{{ ticket.name }}">
<input type="number" name="quantity" max="{{ ticket.event.organiser.max_quantity_per_ticket }}" placeholder="0">
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Continue</button>
</form>
models.py
class ReservedItem(models.Model):
order_reference = models.CharField(
max_length=10,
unique=True
)
ticket = models.ForeignKey(
Ticket,
on_delete=models.PROTECT,
related_name='reserved_tickets'
)
ticket_name = models.CharField(max_length=100)
quantity = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
forms.py
class ReserveForm(forms.ModelForm):
class Meta:
model = ReservedItem
fields = ['order_reference', 'ticket', 'ticket_name', 'quantity']
views.py - events
# Create your views here.
class EventDetailView(DetailView):
context_object_name = 'event'
def get_object(self):
organiser = self.kwargs.get('organiser')
event = self.kwargs.get('event')
queryset = Event.objects.filter(organiser__slug=organiser)
return get_object_or_404(queryset, slug=event)
views.py - checkout
def reserve_ticket(request):
if request.method == 'POST':
form = ReserveForm(request.POST)
if form.is_valid():
print("Hello World")
return redirect("https://test.com")
else:
print("back to homepage")

update / edit function in django one-to-one models

i've made an edit form in django, and i have trouble in my update function. There is a relational models that using one-to-one relationship. When i run this function, data in User models stored properly, but not in the UserProfile models.
This is my urls.py
url(r'^update_user/(?P<pk>\d+)$', views.update_user, name='update_user'),
This is my models:
class UserProfile(models.Model):
user = models.OneToOneField(User)
CATEGORY_CHOICES = (
('admin','Admin'),
('user','User'),
)
hak_akses = models.CharField(max_length=100, choices = CATEGORY_CHOICES)
def __unicode__(self):
return self.user.username
This is my views.py
def update_user(request, pk, template_name='form_user.html'):
related = User.objects.select_related().all()
user = get_object_or_404(related, pk=pk)
# profile = get_object_or_404(UserProfile, pk=pk)
if request.POST:
user_form = UserForm(data=request.POST, instance=user)
profile_form = UserProfileForm(data=request.POST, instance=user)
if user_form.is_valid() and profile_form.is_valid():
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
return redirect('manajemen_user')
else:
user_form = UserForm(instance=user)
profile_form = UserProfileForm(instance=user)
return render_to_response(template_name, {
'user_form': user_form, 'profile_form': profile_form,
}, context_instance=RequestContext(request))
This is my forms:
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'password')
class UserProfileForm(forms.ModelForm):
CATEGORY_CHOICES = (
('admin','Admin'),
('user','User'),
)
hak_akses = forms.ChoiceField(choices = CATEGORY_CHOICES)
class Meta:
model = UserProfile
fields = ('hak_akses',)
And this is my form templates html:
<form name="tambah_user" class="form-horizontal style-form" method="POST">{% csrf_token %}
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Nama User</label>
<div class="col-sm-10">
<!-- <input type="text" class='form-control'> -->
{{ user_form.username }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Password</label>
<div class="col-sm-10">
{{ user_form.password }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-sm-2 control-label">Hak Akses</label>
<div class="col-sm-10">
{{ profile_form.hak_akses }}
<br><br><br>
<button type="submit" class="btn btn-theme">Submit</button>
</div>
</div>
</form>
why data in User Models updated properly but not in UserProfile models ?
what's the solution?
thank you very much
You should construct UserProfileForm form with the UserProfile instance instead of User:
profile = UserProfile.objects.filter(user=user).first()
...
profile_form = UserProfileForm(data=request.POST, instance=profile)
...
profile_form = UserProfileForm(instance=profile)
If you are sure that profile is already exist then you can write:
profile = user.userprofile
instead of the filter().first() call.

Categories

Resources