When I send an image to the bank to save, it always returns this message "This field is required." but I fill the field with an image but it always returns this error.
Views
def criar (request):
form = forms_user()
if request.method == 'GET':
return render(request, 'create.html', {'form': form})
if request.method == 'POST':
form = forms_user(request.POST, request.FILES )
if form.is_valid():
form.save()
messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
form_clean = forms_user()
return render(request, 'create.html', {'form': form_clean})
else:
print(form.errors)
messages.add_message(request, constants.ERROR, f'{form.errors}')
return render(request, 'create.html', {'form': form})
Models
class items(models.Model):
titulo:models.CharField(max_length=30, blank=False)
descricao = models.TextField(max_length=50, blank=False)
usuario = models.CharField(max_length=20, blank=False)
Preco = models.BooleanField(blank=False)
royalties = models.PositiveIntegerField(blank=False)
image = models.ImageField(upload_to='image/', null=True, blank=True)
Forms
class forms_user (forms.ModelForm):
class Meta:
model = items
fields = '__all__'
HTML
<form id="contact" action="" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Seu arquivo</label>
{% render_field form.image type="file" id="file" name="myfiles[]" %}
</fieldset>
</form>
Here in the forms I just put the form and the IMG field so it doesn't get too big but the other fields I put everything right.
At first there's a typo in model field titulo it should be = not :.
Secondly, you should always return an HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general, so use following view:
def criar(request):
if request.method == 'GET':
return render(request, 'create.html', {'form': forms_user()})
else:
form = forms_user(request.POST, request.FILES )
if form.is_valid():
form.save()
messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
return redirect("success")
else:
print(form.errors)
messages.add_message(request, constants.ERROR, f'{form.errors}')
return render(request, 'create.html', {'form': forms_user()})
If you have created modelform then render image field as below, and you can also remove the action attribute as Django by default takes current page route.
Html:
<form id="contact" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="file">Seu arquivo</label>
{{form.image}}
</fieldset>
</form>
urls.py
urlpatterns=[
path("success/", views.success, name="success")
...
]
success.html:
<body>
<h1> The form has been successfully submitted </h1>
</body>
Related
Good day!
I'm trying to create a form with four fields, like in the screenshot. I'm not getting anywhere yet.
Now I use this form in template:
<form>
<form id="FirstForm" action="{% url one.views.FirstForm %}" method="POST">
{% csrf_token %}
{{ form1 }}
</form>
<form id="SecondForm" action="{% url one.views.SecondForm %}" method="POST">
{% csrf_token %}
{{ form2 }}
</form>
<div>
<input type="submit" name="subform1" value="Отправить" class="form_button">
</div>
</form>
And here is the code in views.py:
def FirstForm(request):
if request.method == 'GET':
form = FirstForm()
return render(request, 'home.html', {'form':form})
else:
form = FirstForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
try:
send_mail(name, email, settings.EMAIL_HOST_USER, ['daribian#list.ru'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'home.html', {'form': form})
def SecondForm(request):
if request.method == 'GET':
form = SecondForm()
else:
form = SecondForm(request.POST)
if form.is_valid():
date = form.cleaned_data['date']
number = form.cleaned_data['number']
try:
send_mail(date, number, settings.EMAIL_HOST_USER, ['daribian#list.ru'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'home.html', {'form': form})
def successView(request):
return HttpResponse('Success!')
As well as the forms themselves:
class FirstForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name_class'}), max_length=100, required=True)
email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email_class'}), required=True)
class SecondForm(forms.Form):
date = forms.CharField(widget=forms.TextInput(attrs={'class' : 'my_name_class'}), max_length=100, required=True)
number = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'my_email_class'}), required=True)
I keep getting various errors and I think I'm doing something wrong. Can someone tell me what my mistake is?
enter image description here
I am new to django, I created a form to save Data into my database but it not working corectly, I got no error but data is not sent in database. Thanks for helping!
views.py
#login_required()
def data(request):
if request.POST == "POST":
form = CreatePost(request.POST)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect(data)
else:
form = CreatePost()
context = {
"form": form
}
return render(request, "sms/data.html", context)
forms.py
class CreatePost(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content"]
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
data.html
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<pre></pre>
<button class="btn btn-outline-info" type="submit" value="Submit">Data</button>
</form>
try like this
#login_required()
def data(self, request):
if request.method == "POST": #this line
form = CreatePost(request.POST)
if form.is_valid():
post = form.save(commit=False) #new line
post.author = self.request.user #this line
post.save() #this line
return redirect(data)
else:
form = CreatePost()
context = {
"form": form
}
return render(request, "sms/data.html", context)
if request.POST == "POST":
Should instead be:
if request.method == 'POST':
I am creating a project using Python and Django in which I keeping track of all the products in my store, once I sell a particular product I need to update the number of units of that product remaining
Here is my Models.py file
from django.db import models
class Product(models.Model):
prod_name=models.CharField(max_length=100, blank=False)
company=models.CharField(max_length=100, blank=False)
quantity=models.IntegerField()
price=models.IntegerField()
prod_type=models.CharField(max_length=100)
units=models.IntegerField()
def __str__(self):
return('Name:{0} Company: {1} Qty:{2} Price: {3} Type:{4} Units: {5}'.format(self.prod_name, self.company,self.quantity, self.price, self.prod_type, self.units))
Here is my views.py file
from django.shortcuts import render, redirect, get_object_or_404
from .models import *
from .forms import *
def index(request):
return render(request, 'index.html')
def display_product(request):
items=Product.objects.all()
context={
'items':items
}
return render(request, 'index.html', context)
def add_product(request):
if request.method == "POST":
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form =ProductForm(request.POST)
return render(request, 'add_new.html', {'form':form})
def edit_product(request, pk):
item = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('index')
else:
form = ProductForm(instance=item)
return render(request, 'edit_product.html', {'form':form})
def sell_product(request, pk):
item = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('index')
else:
form = ProductForm(instance=item)
return render(request, 'sell_product.html', {'form':form})
Here is my sell_product.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
{% csrf_token %}
<div class ="form-form row">
<label for="UpdateSold">Units Sold</label>
<input type="Units Sold" class="form-control" id="UpdateSold" aria-describedby="emailHelp" placeholder="Units Sold">
</div>
</div>
<button type="submit" class="btn btn-primary" name="button">Update Product</button>
</form>
</div>
{% endblock %}
So here is a snippet of front end
I have 25 Oreo cookies I sell 3 of them and I enter 3 in Units Sold so I want the Units value of Oreo cookies to be updated to 22Snippet
I'm not able to display content of comment in Django template.
do i have to pass something to the view or do i just call the object simply the wrong way.
views.py
def comment_delete(request, pk):
comment = get_object_or_404(Comment, pk=pk)
try:
if request.method == 'POST':
comment.delete()
messages.success(request, 'You have successfully deleted the Comment')
return redirect('post_detail', pk=comment.post.pk)
else:
template = 'myproject/comment_delete.html'
form = CommentForm(instance=comment)
context = {
'form': form,
}
return render(request, template, context)
except Exception as e:
messages.warning(request, 'The comment could not be deleted. Error {}'.format(e))
models.py
class Comment(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
content = models.TextField()
published_date = models.DateField(auto_now_add=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.content
template.html
<div class="class-one-box">
<p>{{ comment.post.content }}</p>
<p>Are you sure that you want to delete this Comment? If so, please confirm.</p>
<form method="POST">
{% csrf_token %}
<button class="btn btn-danger" type="submit">Delete Comment</button>
</form>
</div>
Yes, you need to pass the comment object through context. So try like this:
if request.method == 'POST':
comment.delete()
messages.success(request, 'You have successfully deleted the Comment')
return redirect('post_detail', pk=comment.post.pk)
else:
template = 'myproject/comment_delete.html'
form = CommentForm(instance=comment)
context = {
'comment': comment, # <-- Here
'form': form,
}
return render(request, template, context)
In my project as soon as user signup it is redirected to update view where he has to fill this information.Since the user has also logged in automatically after signup I want that user field to be filled automatically and can't be edited.
models.py
class Userpro(models.Model):
user = models.OneToOneField(User)
dob = models.DateField(default=datetime.date.today)
country = models.CharField(max_length=50, default='')
qualification = models.CharField(max_length=10, choices=CHO,
default='No')
university = models.CharField(max_length=100, default='')
location = models.CharField(max_length=100, default='')
def __str__(self):
return str(self.user)
forms.py
class UserProForm(forms.ModelForm):
class Meta:
model = Userpro
fields = '__all__'
views.py
def update(request):
if request.method == 'POST':
form = UserProForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/')
else:
redirect('/')
else:
form = UserProForm()
return render(request, 'app/update.html', {'form': form})
All the required libraries are imported.
I was with the same problem. The solution I've found is very simple.
First remove the "user" field in your forms.py
them in views:
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
by making this the obj is a saved form (but not commited in database) and them you can manage it like puting the user as the request.user; them save.
notice that obj."the name you put in your models"
You can use widgets for your form. Something like this(code below is not tested).
from django.forms import TextInput
class UserProForm(forms.ModelForm):
class Meta:
model = Userpro
fields = '__all__'
widgets = {
'user': TextInput(attrs={'readonly': 'readonly'})
}
def update(request):
instance = Userpro.objects.filter(user=request.user).first()
if request.method == 'POST':
form = UserProForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/')
else:
return redirect('/')
else:
form = UserProForm(instance=instance)
return render(request, 'app/update.html', {'form': form})
Edited: we should pass user inside dict like this:
form = UserProForm({'user': request.user})
Edited 2: You should find profile object first and then pass it to the form
instance = Userpro.objects.filter(user=request.user).first()
form = UserProForm(request.POST, instance=instance)
I think it will be better if you will use ModelForm with fields that you want to modify and in template show object instance values like that.
from django.forms import TextInput
class UserProfileForm(forms.ModelForm):
class Meta:
model = Userprofile
fields = ('field1', 'field2')
def update(request):
if request.method == 'POST':
form = UserProfileForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/')
else:
redirect('/')
else:
form = UserProfileForm(user=request.user)
return render(request, 'app/update.html', {'form': form})
# template
<form method="post">
{% csrf_token %}
<div class="form-row">
{{ form.field1.errors }}
{{ form.field1.label_tag }} {{ form.field1 }}
</div>
<div class="form-row">
{{ form.field2.errors }}
{{ form.field2.label_tag }} {{ form.field2 }}
</div>
<div class="form-row">
{{ form.instance.field3.errors }}
{{ form.instance.field3.label_tag }} {{ form.instance.field3 }}
</div>
</form>