When i submit my form having image it is not saving in any folder and when i submit it from django admin panel it is saving
this is my models.py
class dish(models.Model):
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
dish_image = models.ImageField(upload_to="", default=None, blank=True, null=True)
dish_date = models.DateField()
def __str__(self):
return self.dish_name
this is my setting.py
STATIC_URL = 'static/'
MEDIA_URL = 'images/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_ROOT = os.path.join(BASE_DIR, 'card/static/images')
this is my view.py
def index(request):
if request.method == "POST":
dish_name = request.POST.get('dish_name')
dish_size = request.POST.get('dish_size')
dish_price = request.POST.get('dish_price')
dish_description = request.POST.get('dish_description')
dish_image = request.POST.get('dish_image')
dish_category = request.POST.get('dish_category')
item = dish(dish_name = dish_name, dish_size = dish_size, dish_price =dish_price, dish_description = dish_description,dish_category=dish_category, dish_image=dish_image, dish_date = datetime.today())
item.save()
dishs = dish.objects.all()
params = {'dish': dishs}
return render(request, "card/index.html", params)
this is my form
<form method="post" action="/index">
{% csrf_token %}
<div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div>
<div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div>
<div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div>
<div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div>
<div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div>
<div>Dish image: <input name="dish_image" type="file"></div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
I think you have to encode the data of the request this way.
<form enctype="multipart/form-data" method="POST" action="/index">
According to your model field dish_image, you have not set folder name to upload_to.
let's set it:
dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
And in settings.py file:
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
And in your main project urls:
Add below code in urlpatterns:
+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
EX:
urlpatterns = [
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) #added here
Note: You don't need to create media folder in your project root. It will create media folder along with images folder in your project root
Related
I wanted to save text and images in my database in django but when i used
enctype='multipart/form-data'
it is not storing the image.
When i do it without
enctype='multipart/form-data'
it is storing the name of image
this is my index.html
`
<form method="POST" action="/index" enctype='multipart/form-data'>
{% csrf_token %}
<div>Dish name: <input name="dish_name" type="text" placeholder="Dish name"></div>
<div>Dish category: <input name="dish_category" type="text" placeholder="Dish category"></div>
<div>Dish size: <input name="dish_size" type="text" placeholder="Dish size"></div>
<div>Dish price: <input name="dish_price" type="text" placeholder="Dish price"></div>
<div>Dish description: <input name="dish_description" type="text" placeholder="Dish description"></div>
<div>Dish image: <input name="dish_image" type="file"></div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
this is my views.py
def index(request):
if request.method == "POST":
dish_name = request.POST.get('dish_name')
dish_size = request.POST.get('dish_size')
dish_price = request.POST.get('dish_price')
dish_description = request.POST.get('dish_description')
dish_image = request.POST.get('dish_image')
dish_category = request.POST.get('dish_category')
item = dish(dish_name = dish_name, dish_size = dish_size, dish_price = dish_price, dish_description = dish_description,dish_category=dish_category, dish_image = dish_image, dish_date = datetime.today())
item.save()
dishs = dish.objects.all()
params = {'dish': dishs}
return render(request, "card/index.html", params)
this is my models.py
class dish(models.Model):
dish_id = models.AutoField
dish_name = models.CharField(max_length=255, blank=True, null=True)
dish_category = models.CharField(max_length=255, blank=True, null=True)
dish_size = models.CharField(max_length=7, blank=True, null=True)
dish_price = models.IntegerField(blank=True, null=True)
dish_description = models.CharField(max_length=255, blank=True, null=True)
# dish_image = models.ImageField(upload_to="images/", default=None, blank=True, null=True)
dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) #here added images as a foldername to upload to.
dish_date = models.DateField()
def __str__(self):
return self.dish_name
this is my urls.py
urlpatterns = [
path('/index', views.index),
path('', views.index),
path('/', views.index),
path('index/', views.index),
path('index', views.index),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
this is my settings.py
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
`
using this my text is saving but image is not saving
In your html file, use this: enctype='multipart/form-data'
In your post method, you should use:
dish_image = request.FILES.get('dish_image')
This will return a file, which you can then save it to the model.
USERS can Upvote or Downvote Posts/Projects posted by Other Users:
screenshot of 'jammed' active dropdown selection box
THIS CODE DIRECTLY BELOW is the models.py that contains the Project class (model) with the vote_total and vote_ratio fields.
It also contains the Review class (model) which is the basis for the ReviewForm in forms.py (code included later)
class Project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
featured_image = models.ImageField(null=True, blank=True, default="default.jpg")
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.title
class Meta:
# ordering = ['-created']
ordering = ['-vote_ratio', 'vote_total', 'title']
AND here is the Review class (model)
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class Meta:
unique_together = [['owner', 'project']]
def __str__(self):
return self.value
Here is the ReviewForm from the forms.py
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ['value', 'body']
labels = {
'value': 'Place your vote',
'body': 'Add a comment with your vote'
}
def __init__(self, *args, **kwargs):
super(ReviewForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Here is the html template where the form is located
<div class="comments">
<h3 class="singleProject__subtitle">Comments</h3>
<h5 class="project--rating">
{{project.vote_ratio}}% Postitive ({{project.vote_total}} Vote{{project.vote_total|pluralize:"s"}})
</h5>
{% if request.user.profile.id in project.reviewers %}
<p>You have already submitted a comment!</p>
{% elif request.user.profile == project.owner %}
<p>You can't comment your own work!</p>
{% elif request.user.is_authenticated %}
<form class="form" action="{% url 'project' project.id %}" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#textarea">{{field.label}} </label>
{{field}}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg" type="submit" value="Add Review" />
</form>
{% else %}
Please login to leave a comment
{% endif %}
It was working okay when first implemented and has somehow developed this issue
This is running in venv with Python 3.9.6
Thank you for considering this question !
ADDED - rendered html
rendered html
how to save data from html table in django without using form.py. I am currently creating table in html with add button and after adding all rows in table i want to save it but i am not using form.py only view.py,html,model.py
my view code is below
views.py
school_name = request.POST['school_name']
m_pass_out = request.POST['m_pass_out']
medicalschool = MedicalSchool(school_name=school_name, m_pass_out=m_pass_out)
medicalschool.save()
my model code is below
models.py
class DoctorProfile(models.Model):
user_guid = models.OneToOneField(
'EgdEradUsers', models.DO_NOTHING, db_column='user_guid', primary_key=True)
doctor_guid = models.UUIDField(unique=True)
featured_doctor_id = models.BooleanField()
primary_speciality = models.ForeignKey(DSpecialtyType, models.DO_NOTHING)
# This field type is a guess.
secondary_speciality = models.TextField(blank=True, null=True)
years_experience = models.IntegerField()
# This field type is a guess.
education = models.TextField(blank=True, null=True)
license_number = models.CharField(max_length=1000, blank=True, null=True)
npi_number = models.CharField(max_length=1000, blank=True, null=True)
revalidation_cme = models.IntegerField(blank=True, null=True)
# This field type is a guess.
states_to_practice = models.TextField(blank=True, null=True)
# This field type is a guess.
board_certification = models.TextField(blank=True, null=True)
# This field type is a guess.
honors_awards_recognition = models.TextField(blank=True, null=True)
# This field type is a guess.
publications = models.TextField(blank=True, null=True)
description = models.CharField(max_length=1000, blank=True, null=True)
# This field type is a guess.
hospital_privileges = models.TextField(blank=True, null=True)
phone_code = models.IntegerField(blank=True, null=True)
primary_contact_number = models.CharField(max_length=45)
phone_code2 = models.IntegerField(blank=True, null=True)
secondary_contact_number = models.CharField(
max_length=45, blank=True, null=True)
resume_url = models.CharField(max_length=1000, blank=True, null=True)
avatar_url = models.CharField(max_length=1000, blank=True, null=True)
additional_comments = models.CharField(
max_length=1000, blank=True, null=True)
class Meta:
managed = True
db_table = 'doctor_profile'
class MedicalSchool(models.Model):
school_name = models.CharField(max_length=100)
m_pass_out = models.DateField(max_length=100)
doctor_profile = models.ForeignKey(DoctorProfile, on_delete=models.CASCADE)
created_at = models.DateTimeField()
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'medical_school'
my html code is below
html
<div class="container-lg">
<div class="table-responsive">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-8">
<h2>Medical School</h2>
</div>
<div class="col-sm-4">
<button type="button" id="medical" class="btn btn-info add-
new"><i class="fa fa-plus"></i> Add New</button>
</div>
</div>
</div>
<table id="medicaltable" class="table table-bordered">
<thead>
<tr>
<th>Name of School</th>
<th>Year of Graduation</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td id="medicaltext" name="school_name"></td>
<td id="medicaldate" name="m_pass_out"></td>
<td>
<a id="medicaladd" class="add" title="Add" data-
toggle="tooltip"><i class="material-icons"></i></a>
<a id="medicaledit" class="edit" title="Edit" data-
toggle="tooltip"><i class="material-icons"></i></a>
<a id="medicaldelete" class="delete" title="Delete" data-
toggle="tooltip"><i class="material-icons"></i></a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
you can access to your each html form inputs by their name in view. see below code:
models
from django.db import models
from django import forms
class MedicalSchool(models.Model):
school_name = models.CharField(max_length=100)
m_pass_out = models.DateField(max_length=100)
doctor_profile = models.ForeignKey(DoctorProfile, on_delete=models.CASCADE)
created_at = models.DateTimeField()
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'medical_school'
class MedicalSchoolForm(forms.ModelForm):
class Meta:
model = MedicalSchool
fields = ['school_name', 'm_pass_out', 'doctor_profile']
views
from django.contrib import messages
from django.shortcuts import redirect, render
from . import models
def MedicalSchool(request):
url = request.META.get('HTTP_REFERER') # get last url
if request.method == 'POST':
form = models.MedicalSchoolForm(request.POST) # access to ModelForm
if form.is_valid():
data = models.MedicalSchool() # create a instance of your Model
data.school_name = form.cleaned_data['school_name'] # 'school_name' is the name that we specified in html form input
data.m_pass_out = form.cleaned_data['m_pass_out'] # 'm_pass_out' is the name that we specified in html form input
data.doctor_profile_id = form.cleaned_data['doctor_profile'] # 'doctor_profile' is the name that we specified in html form input
data.save()
return redirect(url)
else:
messages.warning(request, form.errors)
return redirect(url)
context = {'DoctorProfile': models.DoctorProfile.objects.all()}
return render(request, 'MedicalSchool.html', context)
urls
from django.urls import path
from . import views
app_name = 'School'
urlpatterns = [
path('', views.MedicalSchool, name='MedicalSchool'),
...
]
MedicalSchool.html
<form action="{% url 'School:MedicalSchool' %}" method="POST">
{% csrf_token %}
<input type="text" name="school_name" placeholder="school name" required>
<input type="text" name="m_pass_out" placeholder="m pass out" required>
<select name='doctor_profile'>
{% for dr in DoctorProfile %}
<option name="doctor_profile" value="{{ dr.id }}">{{ dr.title}}</option> <!-- Match your code with {{ dr.title}} -->
{% endfor %}
</select>
<button type="submit"> Submit </button>
</form>
let me know if there was a problem
models.py
from django.db import models
class Ads(models.Model):
business_id = models.CharField(max_length=20, blank=True, null=True)
description = models.CharField(max_length=100, blank=True, null=True)
image = models.ImageField(upload_to='images', blank=True, null=True)
forms.py
from django import forms
from .models import Ads
class AdsForm(forms.Form):
class Meta:
model = Ads
fields = '__all__'
view.py
from .models import Ads
from .forms import AdsForm
from django.core.files.storage import FileSystemStorage
def ads_view(request):
if request.method == 'POST':
form = AdsForm(request.POST, request.FILES)
if form.is_valid():
business_id = request.POST.get('business_id')
description = request.POST.get('description')
image = request.FILES['image']
print(business_id)
print(description)
print(image)
file_storage = FileSystemStorage()
ads_obj = Ads(business_id=business_id, description=description, image=file_storage.save(image.name, image))
ads_obj.save()
return redirect('/ads/')
else:
form = AdsForm()
return render(request, 'ads/myads.html', {'form': form})
myads.html
<form action="#" method="post" enctype="multipart/form-data">
<input type="text" name="business_id" class="form-control form-control" id="colFormLabelSm" placeholder="">
<textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
<input type="file" name="image" class="form-control" id="exampleFormControlInput1" multiple>
<button type="submit" class="btn btn-primary mt-5">Submit</button>
</form>
Here I'm trying to upload multiple images but in view i'm getting lastly selected one image only. How to get all images and save all images. Help me in this problem.
You can create a separate image class with foreign key as Ads as below and call the images in your templates as object.image_set.all(), so that you can add any amount of images which inherit from your Ads model
class Ads(models.Model):
business_id = models.CharField(max_length=20, blank=True, null=True)
description = models.CharField(max_length=100, blank=True, null=True)
class Image(models.Model):
ads = models.ForeignKey(Ads, ....)
image = models.ImageField(upload_to='images', blank=True, null=True)
I want to send my data through post request. I used postgres database.
I also tried for makemigrations and migrate this model, it also shows the error message.
When i tried to submit my form, it shows following error.
IntegrityError at /formSubmit
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (Own, Khar, 3, 23, 2323, 23233, 324, null).
Request Method: POST
Request URL: http://127.0.0.1:8000/formSubmit
Django Version: 2.1.7
Exception Type: IntegrityError
Exception Value:
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (Own, Khar, 3, 23, 2323, 23233, 324, null).
Exception Location: D:\coding time\Django+ GeoDjango\Django
Enviroment\venv\lib\site-packages\django\db\backends\utils.py in _execute,
line 85
Python Executable: D:\coding time\Django+ GeoDjango\Django
Enviroment\venv\Scripts\python.exe
Python Version: 3.7.2
my models.py file is comes form python manage.py inspectdb command. I managed the database in postgres. models.py file is here:
class Form(models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
email = models.CharField(max_length=29, blank=True, null=True)
password = models.CharField(max_length=30, blank=True, null=True)
class Meta:
db_table = 'form'
class Ownership(models.Model):
house_no = models.IntegerField(blank=True, null=True)
ward_no = models.IntegerField(blank=True, null=True)
tole = models.CharField(max_length=100, blank=True, null=True)
house_owner = models.CharField(max_length=100, blank=True, null=True)
gender = models.CharField(max_length=100, blank=True, null=True)
religion = models.CharField(max_length=100, blank=True, null=True)
language = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'ownership'
class Residence(models.Model):
ownership_type = models.CharField(max_length=100, primary_key=True)
house_type = models.CharField(max_length=100, blank=True, null=True)
land_type = models.CharField(max_length=100, blank=True, null=True)
total_room = models.CharField(max_length=101, blank=True, null=True)
house_use = models.CharField(max_length=101, blank=True, null=True)
house_area = models.CharField(max_length=101, blank=True, null=True)
earthquake_resistance = models.CharField(max_length=101, blank=True, null=True)
id = models.ForeignKey(Ownership, models.DO_NOTHING, db_column='id')
class Meta:
db_table = 'residence'
class ServiceDetail(models.Model):
radio = models.BooleanField(primary_key=True)
television = models.BooleanField(blank=True, null=True)
telephone = models.BooleanField(blank=True, null=True)
computer = models.BooleanField(blank=True, null=True)
internet = models.BooleanField(blank=True, null=True)
motorcycle = models.BooleanField(blank=True, null=True)
car = models.BooleanField(blank=True, null=True)
refrigerator = models.BooleanField(blank=True, null=True)
washing_machine = models.BooleanField(blank=True, null=True)
heater = models.BooleanField(blank=True, null=True)
id = models.ForeignKey(Ownership, models.DO_NOTHING, db_column='id')
class Meta:
db_table = 'service_detail'
my form.html file is here:
<html>
<head>
<title>form</title>
<style type="text/css">
table {
width:100%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
text-align: left;
}
table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color: #fff;
}
table#t01 th {
background-color: black;
color: white;
}
</style>
</head>
<body>
<form method="POST" action='/formSubmit'>
{% csrf_token %}
<h3>Ownership Detail</h3>
Name: <input type="text" name="name"><br><br>
Ward: <input type="text" name="ward"><br><br>
tole name: <input type="text" name="tname"><br><br>
House number: <input type="text" name="hnumber"><br><br>
Gender: <input type="radio" name="gender" value="male">Male <input type="radio" name="gender" value="male">Female<br><br>
Religeous: <select name="religeous">
<option>Select</option>
<option>Hindu</option>
<option>Buddhist</option>
<option>Islam</option>
<option>Isai</option>
</select>
<br><br>
language: <input type="text" name="language"> <br><br>
<h3>Residence Detail</h3>
Owner type: <select name="ownertype"><option>select</option><option>Own</option><option>Lease</option><option>Corporation</option></select><br><br>
House type: <select name="housetype">
<option>select</option>
<option>Khar</option>
<option>Tin</option>
<option>Cement</option>
<option>Stone</option>
</select><br><br>
Land type: <input type="text" name="landtype"><br><br>
Total room: <input type="text" name="totalroom"><br><br>
House used: <input type="text" name="houseused"><br><br>
House area: <input type="text" name="housearea"><br><br>
Earthquake resistance: <input type="text" name="earthquake"><br><br>
<h3>Service Detail</h3>
<table>
<tr>
<th>Facilities</th>
<th>Yes/no</th>
</tr>
<tr>
<td>Radio</td>
<td><select name="radio"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>TV</td>
<td><select name="tv"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>Mobile</td>
<td><select name="mobile"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>computer</td>
<td><select name="computer"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>Internet</td>
<td><select name="internet"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>MoterCycle</td>
<td><select name="motercycle"><option>Yes</option><option>No</option></select></td>
</tr>
<tr>
<td>Car</td>
<td><select name="car"><option>Yes</option><option>No</option></select></td>
</tr><tr>
<td>Hitar</td>
<td><select name="hitar"><option>Yes</option><option>No</option></select></td>
</tr>
</table>
<br><br>
<p align="center"><button type="submit" name="submit">Submit Data</button></p>
</form>
</body>
</html>
my views.py file is here:
from .models import Form, Residence, Ownership, ServiceDetail
# Create your views here.
def index(request):
form = Form.objects.all()
context = {
'form': form
}
return render(request, 'index.html', context)
def form(request):
return render(request, 'form.html')
def submit(request):
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
info = Form(name=name, email=email, password=password)
info.save()
return render(request, 'submit.html')
def formSubmit(request):
name = request.POST['name']
ward = request.POST['ward']
tname = request.POST['tname']
hnumber = request.POST['hnumber']
gender = request.POST['gender']
religeous = request.POST['religeous']
language = request.POST['language']
ownertype = request.POST['ownertype']
housetype = request.POST['housetype']
landtype = request.POST['landtype']
totalroom = request.POST['totalroom']
houseused = request.POST['houseused']
housearea = request.POST['housearea']
earthquake = request.POST['earthquake']
radio = request.POST['radio']
tv = request.POST['tv']
computer = request.POST['computer']
mobile = request.POST['mobile']
internet = request.POST['internet']
motercycle = request.POST['motercycle']
car = request.POST['car']
hitar = request.POST['hitar']
def count(n):
for i in range(n):
return i
if i == n:
return n+1
ownership = Ownership(house_no=hnumber, ward_no=ward, tole=tname, house_owner=name, gender=gender, religion=religeous, language=language)
ownership.save()
residence = Residence(ownership_type=ownertype, house_type=housetype, land_type=landtype, total_room=totalroom, house_use=houseused, house_area=housearea, earthquake_resistance=earthquake)
residence.save()
serviceDetail = ServiceDetail(radio=radio, television=tv, computer=computer, internet= internet, motorcycle=motercycle, car=car, heater=hitar)
serviceDetail.save()
return render(request, 'submit.html')
my urls.py file is here:
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('form', views.form, name = 'form'),
path('submit', views.submit, name = 'submit'),
path('formSubmit', views.formSubmit, name= 'formSubmit')
]