I want to save a model (Villa) in django with this form everغthing is ok but i don't know how to upload images with that when the villa is saved, it gets all its information, but saves the photos in a fake path that doesn't exist is there anyway to upload the image دn this method?
This is the code:
HTML
{% extends 'base.html' %}
{% load static %}
{% block title %}Save Villa{% endblock title %}
{% block content %}
<script src="{% static 'assets/villa_save_form_check.js' %}"></script>
<script src="{% static 'assets/villa_save_handle.js' %}"></script>
<div class="container my-5 rounded-3 w-100 h-100 justify-content-center d-flex">
<div class="row">
<div class="col-12">
<form method="POST" class="form-control">
<h1 class="form-label">Villa</h1>
<hr>
<input type="hidden" name="username" id="username" class="form-control" value="{{user.username}}">
<label class="form-label mt-1">Full Name</label>
<input type="text" name="owner_id" id="owner_id" placeholder="Owner Name" class="form-control mb-2" required>
<label class="form-label mt-1">Phone Number</label>
<input type="number" oninput="phoneCheck()" name="phone_id" id="phone_id" placeholder="Owner Phone Number" class="form-control mb-2" required>
<label class="form-label mt-1">Price</label>
<input type="number" name="price_id" id="price_id" oninput="priceCheck()" placeholder="Villa Price" class="form-control mb-2" required>
<label class="form-label mt-1">Address</label>
<input type="url" name="address_id" id="address_id" placeholder="Villa Address" class="form-control mb-2" required>
<label class="form-label mt-1">About</label>
<textarea name="description_id" id="description_id" oninput="descriptionCheck()" class="form-control mb-2" cols="100" rows="5" placeholder="Description" required></textarea>
<label class="form-label mt-1">Title Image</label>
<input type="file" name="title_id" id="title_id" placeholder="Villa Address" class="form-control mb-2" required>
<label class="form-label mt-1">Image 1</label>
<input type="file" name="img1_id" id="img1_id" placeholder="Villa Address" class="form-control mb-2" required>
<label class="form-label mt-1">Image 2</label>
<input type="file" name="img2_id" id="img2_id" placeholder="Villa Address" class="form-control mb-2" required>
<label class="form-label mt-1">Image 3</label>
<input type="file" name="img3_id" id="img3_id" placeholder="Villa Address" class="form-control mb-2" required>
<label class="form-label mt-3">Save</label>
<input type="submit" onmouseover="finalCheck()" name="btn_save_id" id="btn_save_id" data-csrftoken="{{csrf_token}}" placeholder="Villa Address" class="btn btn-outline-success form-control mb-2" required>
</form>
</div>
</div>
</div>
{% endblock content %}
jQuery file:
$(document).ready(function ()
{
$('#btn_save_id').click(function (e)
{
e.preventDefault();
var csrf_token = $(this).data('csrftoken');
var username = $('#username').val();
var owner = $('#owner_id').val();
var phone = $('#phone_id').val();
var price = $('#price_id').val();
var address = $('#address_id').val();
var description = $('#description_id').val();
var title_IMG = $('#title_id').val();
var img1 = $('#img1_id').val();
var img2 = $('#img2_id').val();
var img3 = $('#img3_id').val();
$.ajax({
url: '/owner/panel/create_villa/',
type: 'POST',
headers: {
'X-CSRFToken': csrf_token
},
data: {
'username': username,
'owner': owner,
'phone': phone,
'price': price,
'address': address,
'description': description,
'title_IMG': title_IMG,
'img1': img1,
'img2': img2,
'img3': img3,
},
success: function (response)
{
alert('Villa saved successfully\nYour villa will be visible as soon as it is verified by admin');
$('#username').val('');
$('#owner_id').val('');
$('#phone_id').val('');
$('#price_id').val('');
$('#address_id').val('');
$('#description_id').val('');
$('#title_id').val('');
$('#img1_id').val('');
$('#img2_id').val('');
$('#img3_id').val('');
},
error: function (xhr)
{
console.log('Error:', xhr.responseText);
}
});
});
});
View:
class OwnerVillaCreatePanel(CreateView):
model = Villa
template_name = 'owner_villa_creation.html'
fields = "__all__"
def post(self, request, *args, **kwargs):
print('\n\n\n-----------------------------------\n\n\n')
print('OwnerVillaCreatePanel View POST method called')
print('\n\n\n-----------------------------------\n\n\n')
rq_username = request.POST["username"]
owner = request.POST["owner"]
phone = request.POST["phone"]
price = request.POST["price"]
address = request.POST["address"]
description = request.POST["description"]
title_IMG = request.POST["title_IMG"]
img1 = request.POST["img1"]
img2 = request.POST["img2"]
img3 = request.POST["img3"]
newVilla = Villa(
username = User.objects.get(username=rq_username),
villa_owner = owner,
villa_contact = phone,
villa_price = price,
villa_id = "000000",
villa_rate = "1",
villa_address = address,
villa_description = description,
description_img1 = title_IMG,
description_img2 = img1,
description_img3 = img2,
description_img4 = img3,
likes = 0,
verified = False,
)
newVilla.save()
return super().post(request, *args, **kwargs)
Model:
class Villa(models.Model):
username = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=False, null=True, verbose_name="Username")
villa_owner = models.CharField("Owner", null=False, blank=False, default="ADD OWNER PLEASE", max_length=75, unique=False, help_text="Owner name")
villa_contact = models.CharField("Phone Number", null=False, blank=False, max_length=11, default="09991112233", help_text="Visitors will call this number")
villa_price = models.IntegerField(verbose_name="Price", blank=False, null=False, default=0, help_text="ریال")
villa_id = models.CharField("ID", max_length=6, blank=False, null=False, help_text="Villa ID")
villa_rate = models.CharField("Rate", max_length=1, blank=False, null=False, help_text="1-5", default=1)
villa_address = models.URLField("Address", blank=False, null=False, help_text="Villa Address", max_length=254, unique=True)
villa_description = models.TextField("About", max_length=800, null=True, blank=True, help_text="About the villa")
description_img1 = models.ImageField("Image-1", upload_to="images/", blank=True, null=True, default="images/default_img.jpg")
description_img2 = models.ImageField("Image-2", upload_to="images/", blank=True, null=True, default="images/default_img.jpg")
description_img3 = models.ImageField("Image-3", upload_to="images/", blank=True, null=True, default="images/default_img.jpg")
description_img4 = models.ImageField("Image-4", upload_to="images/", blank=True, null=True, default="images/default_img.jpg")
slug = models.SlugField("Slug", editable=False, max_length=180, unique=True)
likes = models.IntegerField("Liked", default=0)
verified = models.BooleanField("Visible", default=False, blank=False, null=False, help_text="shown in main page if true")
user_likes: list = []
def __str__(self) -> str:
return "Villa-{} | Owner: {}".format(self.villa_id, self.villa_owner)
def save(self, *args, **kwargs):
self.slug = "villa_{}".format(self.villa_id)
if int(self.villa_rate) > 5 or int(self.villa_rate) < 1:
self.villa_rate = str(1)
super().save(*args, **kwargs)
def like_villa(self, username: any):
if username not in self.user_likes:
self.likes += 1
self.user_likes.append(username)
self.save()
else:
self.likes -= 1
self.user_likes.remove(username)
self.save()
def is_verifid(self) -> bool:
if self.verified:
return True
return False
URL path:
path('owner/panel/create_villa/', login_required(OwnerVillaCreatePanel.as_view(), login_url="login"), name="owner_create_villa_panel"),