Image is not coming up properly - python

I'm working on a little e-commerce site. when I post a product from my site, the image(picture) doesn't show but when I post from the admin panel, the image shows so I don't why. I need help on this please. This is the code.
The code below is from the model.py
class OrderedItem(models.Model):
name = models.CharField(max_length=50)
price = models.FloatField()
image = models.ImageField(upload_to='pics')
def __str__(self):
return self.name
The code below is from the views.py
def additem(request):
if request.method == 'POST':
stock_name = request.POST['stock_name']
stock_price = request.POST['stock_price']
stock_image = request.POST['stock_image']
new_item = Stock(stock_name=stock_name, stock_price=stock_price, stock_image=stock_image)
new_item.save()
return redirect('/')
else:
return render(request, 'post.html')
the code below is from the html page
<form action="{% url 'additem' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" name="stock_name" id="" placeholder="stock_name">
</div>
<div class="form-group">
<input type="text" name="stock_price" id="" placeholder="stock_price">
</div>
<div class="form-group">
<input type="file" name="stock_image">
</div>
<div class="form-group">
<input type="submit" value="Additem" class="btn btn-primary btn-lg">
</div>
</form>

You need to add enctype='multipart/form-data' in the form otherwise no file will be accepted.
<form method="POST" action="" enctype='multipart/form-data'>
To get the images inputted in your html file
stock_image = request.FILES['stock_image']

Related

Why aren't changes saved when editing a Django product?

Created a website with products. I need to make a window for editing them on the site in order to change the manufacturer and other characteristics. This must be done in a pop-up window. I have data displayed, I change it, but nothing changes when I save it. How can this problem be solved.
My vievs:
def parts(request):
added = ''
error = ''
PartAllView = Part.objects.order_by('-id')
if request.method == 'POST' and 'parts_add' in request.POST:
form = PartForm(request.POST, request.FILES)
if form.is_valid():
form.save()
added = 'Добавлено'
else:
error = 'Данная запчасть уже добавлена'
if request.method == 'POST' and 'parts_edit' in request.POST:
PartPost = int(request.POST['parts_edit'])
PartID = Part.objects.get(id=PartPost)
if PartID:
PartID.save()
added = 'Запчасть успешно отредактирована'
else:
error = 'Ошибка редактирования'
form = PartForm()
data = {
'added': added,
'error': error,
'form': form,
'PartAllView': PartAllView,
}
return render(request, 'kross/parts.html', data)
My HTML:
{% if PartAllView %}
{% for el in PartAllView %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="modal fade" id="partEdit{{ el.id }}">
<div class="modal-dialog modal-dialog-centered text-center" role="document">
<div class="modal-content modal-content-demo">
<div class="modal-header">
<h6 class="modal-title">Добавление запчасти</h6><button aria-label="Close" class="btn-close"
data-bs-dismiss="modal"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="row row-sm">
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" name="brand" value="{{ el.brand }}">
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.number }}">
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<input type="text" class="form-control" value="{{ el.name }}"><br>
<input type="textarea" class="form-control" rows="2" value="{{ el.description }}">
</div>
</div>
</div>
{{ el.analog }}
...
You can use updateView to edit an existing data in your website by simply:
from django.views.generic.edit import UpdateView
From MyApp models import #Model
class editview(UpdateView):
model = #Your Model You want to edit
fields = [#Add the fields you want to edit]
template_name = 'edit.html'
success_url = ('Home')
In your edit Template add:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
I hope it help.

URL is adding automatically - Django

I have got a problem while redirecting to the edit form.
SO what I am doing is that whenever user clicks on edit button it redirects to "editadmin/{{admin.id}}" using form action = "editadmin/{{admin.id}}" in HTML.
URL path is
path("editadmin/<int:id>", views.editadmin, name="editadmin")
path("update/<int:id>", views.updateadmin, name="updateadmin")
Views.py
#csrf_exempt
def editadmin(request, id):
admin = Admin.objects.get(id=id)
return render(request, "editadmin.html", {"admin": admin})
#csrf_exempt
def updateadmin(request, id):
if request.method == "POST":
admin_id = request.POST["admin_id"]
admin_id = str(admin_id).strip().upper()
name = request.POST["name"]
name = str(name).strip()
if db_name equals to name:
messages.error(request, "Admin name already exists")
return redirect("editadmin/" + str(id))
editadmin.html
<form method="post" class="post-form" action="/update/{{admin.id}}">
<input type="hidden" name="id" id="id" required maxlength="20" value="{{ admin.id }}"/>
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Admin ID : </h4></label>
<div class="col-sm-4">
<input type="text" name="admin_id" required style="margin-left:20px; height:38px; width:300px;
border-radius: 5px" id="admin_id" value="{{ admin.admin_id }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Name : </h4></label>
<div class="col-sm-4">
<input type="text" name="name" style="margin-left:20px; height:38px;
border-radius: 5px; width:300px" required id="name" value="{{ admin.name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success" style="margin-left:210px">Submit</button>
</div>
</div>
So what I want is that Whenever user submits invalid name in editadmin.html (URL - editadmin/1 ), it should redirect to the same URL editadmin/1 but what it does is it appends update/ which redirects to update/editadmin/1
How to fix this? I dont want update/ to get appended after redirecting to same form.
update/ is appending because you mentioned your form action to this URL. So instead of mentioning action in your form, you can do something like this.
#csrf_exempt
def updateadmin(request, id):
if request.method == "POST":
admin_id = request.POST["admin_id"]
admin_id = str(admin_id).strip().upper()
name = request.POST["name"]
name = str(name).strip()
# asuming you are checking if admin with this name already exists in database
if db_name equals to name:
messages.error(request, "Admin name already exists")
return redirect("editadmin/" + str(id))
# It mean user enter a unique name
else:
# your logic to save the incoming user here.
message.success(request, "Your success message")
return redirect(f'/update/{admin_id}')
and make sure to update your form from this:
<form method="post" class="post-form" action="/update/{{admin.id}}">
to this:
<form method="post" class="post-form" action="">

Django doesn't read form

I have form:
<form id="contact-form" class="contact__form" method="POST" action="{% url 'backcall' %}">
{% csrf_token %}
<span class="text-color">Send letter</span>
<div class="form-group">
<input name="name" type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" placeholder="Phone (+380)" pattern="[\+][3][8][0]\d{9}" minlength="13" maxlength="13" />
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" placeholder="Email">
</div>
<div class="form-group-2 mb-4">
<textarea name="message" class="form-control" rows="4" placeholder="Your letter"></textarea>
</div>
<button class="btn btn-main" name="submit" type="submit">Send</button>
</form>
views.py:
def backcall(request):
backcall = BackCall(name = request.POST['name'], phone = request.POST['phone'], email=request.POST['email'] , message = request.POST['message'])
backcall.save()
return redirect('thanks')
models.py
class BackCall(models.Model):
name = models.CharField(max_length=50)
phone = models.CharField(max_length=13)
email = models.EmailField()
message = models.TextField(default=None)
datetime = models.DateTimeField(auto_now_add=True)
When I fill out the form and submit nothing happens. When I follow the link 'backcall/' I get an error.
What the problem can be connected with and how to fix it?
Please, search more, exist the solution
Use the MultiValueDict's get method. This is also present on
standard dicts and is a way to fetch a value while providing a default
if it does not exist.
def backcall(request):
backcall = BackCall(name = request.POST.get('name'), phone = request.POST.get('phone'), email=request.POST.get('email') , message = request.POST.get('message'))
backcall.save()
return redirect('thanks')
You should check whether or not the record exists in your database, I think, a quick example would be:
def backcall(request):
obj, created = BackCall.objects.get_or_create(email=request.POST.get('email'),
defaults={'phone': request.POST.get('phone'),
'name': request.POST.get('name'),
'message': request.POST.get('message')}
if created:
return redirect('thanks')
return ...

django ModelForms and normal form in POST request

Hi i just have a small doubt can we create a HTML template which will have the Django form and normal HTML form together.
I created a HTML template which has both normal HTML input tag and Django forms.
I am getting the following error when i do a form.save(commit=False)
could not be created because the data didn't validate.
My view.py
if request.method == 'POST':
form_value = request.POST.copy()
print form_value
form = InfoForm(data=request.POST)
post_val = form.save(commit=False)
my HTML
<div class="form-row">
<div class="form-group col-md-4">
{{form.name}}
</div>
<div class="form-group col-md-4">
{{form.number}}
</div>
<div class="form-group col-md-4">
{{form.location}}
</div>
</div>
<div class="form-group">
<label for="Feedback">Feedback</label>
<div id="Feedback" class="optionBox1">
<div class="input-group my-add-div">
<input type="text" class="form-control" name="feedback" required>
<input type="text" class="form-control" name="feedback" required>
<input type="text" class="form-control" name="feedback" required>
</div>
</div>
</div>
my form.py
class InfoForm(forms.ModelForm):
name = forms.CharField(label='Project Name',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Click to enter text',}))
number = forms.DecimalField(label='Project #',widget=forms.NumberInput(attrs={'class':'form-control','placeholder':'Enter the ID',}))
location = forms.CharField(label='Location',max_length=100,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter the Location',}))
class Meta:
model = Info
field = ('name','number','location',)
My Model.py
name = models.CharField(max_length=200,blank=True , null=True)
number = models.IntegerField(blank=True , null=True)
location = models.CharField(max_length=200,blank=True , null=True)
feedback = ArrayField(ArrayField(models.CharField(max_length=200,blank=True,null=True)))
Thanks in advance
You need to first call form.is_valid() to use save method on the form.
All what you need to create any form in template you want, example:
``
<form action="." method="post">
{% csrf_token %}
<input type="text" name="first_name">
<p><input type='submit' value="Change"></p>
</form> ``
then, in your view call
first_name = request.POST['first_name']
and it will be works fine.

How to pass context from view to action in html file in django?

I am passing context from view.py file
def change_password(request,pk=None):
user = MyUser.objects.get(pk=pk)
if request.method == "POST":
form = PasswordChangeForm(user=user, data=request.POST)
if form.is_valid():
form.save()
update_session_auth_hash(request, form.user)
return render(request, "nurse/change_password.html", {"user_id":user.id}) // passing user_id as context
I can see this value in my html file
<div class="form-group">
<label class="control-label allign col-sm-3" > {{user_id}} Old Password </label> // user_id is giving the right value
</div>
But when i try to fetch the same in action than it is not working:
<form class="form-horizontal login-box2" action="{% url 'booking:change_password' user_id %}" role="form" method="post"> // not getting user_id here
<div class="form-group">
<label class="control-label allign col-sm-3" > {{user_id}} Old Password </label> // getting user_id here
</div>
<div class="form-group">
<li> <button type="submit" class="btn btn-primary f-w-b f-s-18">Change</button> </li>
</div>
</form>
Can anyone tell me what i am doing wrong?
Thanks
EDITED
adding urls.py code:
url(r'^change_password/(?P<pk>[0-9]+)/$',views.change_password,name='change_password'),

Categories

Resources