how to upload multiple images in django - django

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)

Related

Djago time widget not showing up

All I want to do is add time widget to my form so I can easily pick the time. Everything is very simple, the page is loading but the widgets don't show up. No error nothing. I am thinking maybe I didn't set up the form widgets correctly but not sure what I did wrong. Here is my Forms.py-
from django.contrib.admin import widgets
from django.contrib.admin.widgets import AdminDateWidget, AdminTimeWidget, AdminSplitDateTime
class WorkOutForm(ModelForm):
class Meta:
model = WorkOut
fields = '__all__'
widgets={
'start':AdminTimeWidget(),
'end':AdminTimeWidget(),
}
Here is the Models.py. You will notice "start" and "end" fields are timefield-
class WorkOut(models.Model):
date=models.DateField(auto_now_add=True, auto_now=False, blank=True)
day=models.DateField(auto_now_add=True, auto_now=False, blank=True)
start=models.TimeField(null=True)
name=models.CharField(max_length=100, choices=move)
weight=models.CharField(max_length=100, blank=True)
rep=models.CharField(max_length=100, blank=True)
pedal= models.CharField(max_length=100, blank=True)
stretchtype =models.CharField(max_length=100, blank=True)
end=models.TimeField(null=True)
note=models.TextField(max_length=300, blank=True)
def __str__(self):
return self.name
And here are the views linked to it even though I don't think it has much relevance-
def workout(request):
form=WorkOutForm()
if request.method=="POST":
form=WorkOutForm(request.POST)
if form.is_valid():
form.save()
context={'form':form}
return render(request, 'myapp/enter_workout.html', context)
def update_workout(request, pk):
order=WorkOut.objects.get(id=pk)
form=WorkOutForm(instance=order)
if request.method=='POST':
form=WorkOutForm(request.POST, instance=order)
if form.is_valid():
form.save()
context={'form':form}
return render(request, 'myapp/enter_workout.html', context)
And the form on HTML page is also very basic,so don't think there is any issue there either-
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit">
</form>
What have I done wrong here? How can I make those widgets to show up?
You can try to fill the default values with the current time.
from datetime import datetime
class WorkOut(models.Model):
move = (("1", "Tom"), ("2", "Sara"), ("3", "Emilia"),)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
day = models.DateField(auto_now_add=True, auto_now=False, blank=True)
start = models.TimeField(default=datetime.now, null=True)
name = models.CharField(max_length=100, choices=move)
weight = models.CharField(max_length=100, blank=True)
rep = models.CharField(max_length=100, blank=True)
pedal = models.CharField(max_length=100, blank=True)
stretchtype = models.CharField(max_length=100, blank=True)
end = models.TimeField(default=datetime.now,null=True)
note = models.TextField(max_length=300, blank=True)
def __str__(self):
return self.name
Update 22.10.2022
Made fields with time selection on bootstrap.
For this you need to install:
pip install django-bootstrap4
pip install django-bootstrap-datepicker-plus
In the WorkOutForm class in init set the styles for all fields.
forms.py
from bootstrap_datepicker_plus.widgets import TimePickerInput
class WorkOutForm(ModelForm):
class Meta:
model = WorkOut
fields = "__all__"
widgets = {
"start": TimePickerInput(),
"end": TimePickerInput(),
}
def __init__(self, *args, **kwargs):
super(WorkOutForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
"class": "form-control"
})
templates
{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{{ form.media }}
<form action="" method="POST" style="width: 20%">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit">
</form>

in django how to add data from html table without using form.py

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

How to post one html form data into two models in django?

I having a html form consisting of some fields with details and I want to post some details of the form to one model and some details to another model how this can be done?
my models.py
class room(models.Model):
id = models.IntegerField(primary_key=True)
image = models.ImageField(upload_to='images')
content = models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.content
# This is the model for goals
class goal(models.Model):
id=models.IntegerField(primary_key=True)
goal = models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.goal
# This is the model for designs
class design(models.Model):
id=models.IntegerField(primary_key=True)
image = models.ImageField(upload_to='images')
content = models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.content
# This is the model for furniture
class furniture(models.Model):
id=models.IntegerField(primary_key=True)
phrase=models.CharField(max_length=60,default='111111')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.phrase
# This is the users model
class user(models.Model):
username=models.CharField(max_length=20)
email=models.CharField(max_length=50,unique=True)
password=models.CharField(max_length=50,default='0000000')
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __str__(self):
return self.username
class UserRequirement(models.Model):
id=models.IntegerField(primary_key=True)
user=models.ForeignKey(user,on_delete=models.CASCADE)
rooms = models.ForeignKey(room,on_delete=models.CASCADE)
goals = models.ManyToManyField(goal)
styles = models.ManyToManyField(design)
furn = models.ForeignKey(furniture,on_delete=models.CASCADE)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
My views.py for posting:
def user_register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
if user_form.is_valid():
username=request.POST["username"]
email = request.POST['email']
password = request.POST['password']
rooms = request.POST['room']
g=goals=request.POST['goal']
g = g.split(',')
s=styles=request.POST['style']
s=s.split(',')
furn=request.POST['furn']
u = user(username=username,password=password,email=email)
u.rooms=room.objects.get(pk=rooms)
goals = goal.objects.filter(pk__in=g)
styles = design.objects.filter(pk__in=s)
u.furn = furniture.objects.get(pk=furn)
u.save()
u.goals.add(*goals)
u.styles.add(*styles)
messages.success(request,'Your project design has been registered')
return render(request,'register.html')
else:
messages.warning(request,'Cant be registered this email already exists')
return render(request,'register.html')
My form.html is
<form action="{% url 'modsy:user_register' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" required>
<div id="uname_error"></div>
</div>
<div class="form-group">
<input type="hidden" name="room" id="name" value="">
</div>
<div class="form-group" >
<input type="hidden" name="goal" id="goal" value="">
</div>
<div class="form-group">
<input type="hidden" name="style" id="style" value=" ">
</div>
<div class="form-group" >
<input type="hidden" name="furn" id="furn" value="">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control" required><br>
<div id="name_error" style="color:red;"></div></div>
<div class="form-group">
<label for="password2">Password</label>
<input type="password" name="password" class="form-control" required>
<div id="pwd_error" style="color:red;"></div>
</div>
<div class="button"><input type="submit" value="Save the Project" style="background-color:#000080;" class="btn btn-secondary btn-block" onclick="return validation(form)">
</form>
Now here I want to post the username email and password to the user model and the user room goal furniture style should be stored in the user_requirement model how it can be done?
My forms.py
from django import forms
from . models import user
from django.contrib.auth.models import User
from . models import UserRequirement
from . models import room
from . models import goal
from . models import design
from . models import furniture
class UserForm(forms.ModelForm):
class Meta:
model = user
fields = ('email',)
def clean_email(self):
# Get the email
email = self.cleaned_data.get('email')
# Check to see if any users already exist with this email as a username.
try:
match = User.objects.get(email=email)
except User.DoesNotExist:
# Unable to find a user, this is fine
return email
raise forms.ValidationError('This email address is already in use.')
class UserRequirementForm(forms.ModelForm):
class Meta:
model = UserRequirement
fields=(user,rooms,goals,styles,furn)
Option 1: Create a form with all the fields you need and override the save method to store the data where you need them. You can use your User model as the base model and add any extra fields you need for other models.
Option 2: Use two different forms and process them separately.
if request.method == 'POST':
user_form = UserForm(data=request.POST)
user_requirement_form = UserRequirementForm(data=request.POST)
if user_form.is_valid() and user_requirement_form.is_valid():
user = user_form.save()
user_requirement = user_requirement_form.save(commit=False)
# Set user
user_requirement.user = user
user_requirement.save()
user_requirement_form.save_m2m()
redirect(...)
else:
# Handle errors
messages.warning(request, 'Please correct the errors below')
else:
# GET
user_form = UserForm()
user_requirement_form = UserRequirementForm()
return render(request,'register.html', {'user_form': user_form, 'requirements_form': user_requirement_form})
Then make sure you actually show the errors in your template, using {{ user_form.errors }} or {{ user_form.email.errors }} depending whether you show all the errors at once or per field.
I think the following approach would help.
Forms.py
class UserForm(forms.ModelForm):
class Meta:
model = user
fields = ['email',]
class UserRequirementForm(forms.ModelForm):
class Meta:
model = UserRequirement
fields=['rooms','goals','styles','furn']
Then 2. Views.py
from .forms import UserForm, UserRequirementForm
from django.shortcuts import redirect, render
def register_user(request):
if request.method == 'POST':
user_form = UserForm(request.POST)
user_requirement_form = UserRequirementForm(request.POST)
if user_form.is_valid() and user_requirement_form.is_valid():
user = user_form.save()
user_requirement = user_requirement_form.save(commit=False)
user_requirement.user = request.user # <- Setting the user to currently logged in user
user_requirement.save()
redirect('name_of_url_to_redirect_to')
else:
user_form = UserForm()
user_requirement_form = UserRequirementForm()
context = {
'user_form': user_form,
'user_requirement_form' : user_requirement_form,
}
return render(request, 'path_to_template.html', context)
Then finally in the template (.html file):
<form method="POST">
{{user_form.as_p}}
{{user_requirement_form.as_p}}
<button type="submit"> Submit</button>
</form>
That should render your form and save data correctly on submit
PS: Avoid adding id field on your models as Django already gives you an id field by default.

How to set image field as optional?

How to set image field as optional? I am trying to set image field as optional(None or selected). Image field is None its throwing "MultiValueDictKeyError" when submit the form. I want to make this image field as None.
models.py
class Profile(models.Model):
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
image = models.ImageField(upload_to='images', blank=True, null=True)
forms.py
class Meta:
model = Profile
fields = '__all__'
views.py
def profile(request):
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid:
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
image = request.FILES['images']
file_storage = FileSystemStorage()
obj = Profile(first_name=first_name, last_name=last_name, image=file_storage.save(image.name, image))
return render(request, 'index.html',{})
return render(request, 'index.html',{})
return render(request, 'index.html',{})
index.html
<form action="#" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="first_name" class="form-control form-control" id="fname">
<input type="text" name="last_name" class="form-control form-control" id="lname">
<input type="file" name="images" class="form-control" id="image">
<button type="submit" class="btn btn-primary mt-5 mb-5">Save</button>
</form>
use the same method you're using in the other fields:
image = request.FILES.get('images')
this will make image = None if it doesn't exist in the request. then:
image_saved = None
if image is not None:
image_saved = FileSystemStorage().save(image.name, image)
obj = Profile(first_name=first_name, last_name=last_name, image=image_saved)

django form how to render the fields

I'm trying to render a form but the fields are not displayed in the HTML.
views.py
#url(r'^boxes/(?P<pk>[0-9A-Za-z-]+)/$', views.show_form, name='box'),
def show_form(request, pk):
box = Box.objects.get(pk=pk)
form = SuggestionForm()
context = {
'box':box,
'form':form
}
return render(request, 'boxes/detail.html', context)
forms.py
class SuggestionForm(ModelForm):
class Meta:
model = Suggestion
fields = ['comment']
detail.html
<h3>{{box.title}}</h3>
<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" class="btn btn-info" value="Add suggies" />
</form>
My models.py
#python_2_unicode_compatible
class Suggestion(models.Model):
"""
For adding comments (or suggestions)
"""
def __str__(self):
return self.comment[0:10]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
comment = models.CharField("",max_length=250, blank=True, null=True)
box = models.ForeignKey(Participant, on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
The result HTML.. There is no fields in this form. I want to use a function based view.