I've been working on an application I originally started in Django 1.7, then ported it over to 1.10, where it stopped working. It will work if I select a District to search by, but only by the District. What I'm hoping is that if all the search terms are left blank, it will return all objects in that pool. It would be great if anyone had some ideas on where this is going wrong, as it doesn't give me errors, just tells me there are no results.
Model:
class PlantingSite(models.Model):
id_planting_site = models.IntegerField(null=True, blank=True)
empty = models.BooleanField(default=False)
address = models.CharField(max_length=256, null=True, blank=True)
street = models.CharField(max_length=256, null=True, blank=True)
coord_lat = models.CharField(max_length=256, null=True, blank=True)
coord_long = models.CharField(max_length=256, null=True, blank=True)
zipcode = models.CharField(max_length=256, null=True, blank=True)
neighborhood = models.ForeignKey(Neighborhood, null=True)
district = models.ForeignKey(District, null=True)
property_address = models.CharField(max_length=256, null=True, blank=True)
property_street = models.CharField(max_length=256, null=True, blank=True)
property_zipcode = models.CharField(max_length=256, null=True, blank=True)
property_owner = models.ForeignKey(Contact, related_name='planting_sites_owned_by_contact', null=True)
contact = models.ForeignKey(Contact, related_name='planting_sites_cared_for_by_contact', null=True)
notes = models.TextField(null=True, blank=True)
basin_type = models.ForeignKey(BasinType, related_name='planting_sites_with_basin_type', null=True)
overhead_utility = models.ManyToManyField(OverheadUtility, related_name='planting_sites_with_overhead_utility', blank=True)
hardscape_damage = models.ManyToManyField(HardscapeDamage, related_name='planting_sites_with_hardscape_damage', blank=True)
aspect = models.ForeignKey(Aspect, null=True)
sequence = models.IntegerField(null=True, blank=True)
side = models.CharField(max_length=256, null=True, blank=True)
size = models.CharField(max_length=256, null=True, blank=True)
created_by = models.ForeignKey(User, related_name='planting_sites_created', null=True)
created_at = models.DateTimeField(default=timezone.now)
last_edited = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return unicode(self.id_planting_site)
class Meta:
ordering = ['-created_at']
My View:
def uf_search(request):
if request.POST:
search_sent = True
# SEARCH PLANTING SITES
if request.POST.get('search_type_id') == "1":
planting_site_search = True
if request.POST.get('address_range'):
if request.POST.get('address_start') and request.POST.get('address_end'):
address_start = request.POST.get('address_start')
address_end = request.POST.get('address_end')
r_address = Q(address__range=[address_start, address_end])
else:
r_address = Q(address__isnull=False) | Q(address__isnull=True)
elif request.POST.get('address_exact'):
if request.POST.get('address'):
address = request.POST.get('address')
r_address = Q(address__icontains=address)
else:
r_address = Q(address__isnull=False) | Q(address__isnull=True)
planting_site_fields = {
'street': request.POST.get('street'),
'zipcode': request.POST.get('zipcode'),
}
r_objects = Q()
if request.POST.get('neighborhood_id'):
r_neighborhood = Q(neighborhood__id_neighborhood=request.POST.get('neighborhood_id'))
else:
r_neighborhood = Q(neighborhood__id_neighborhood__isnull=False) | Q(neighborhood__id_neighborhood__isnull=True)
if request.POST.get('district_id'):
r_district = Q(district__id_district=request.POST.get('district_id'))
else:
r_district = Q(district__id_district=False) | Q(district__id_district=True)
for field, value in planting_site_fields.iteritems():
if value:
r_objects = Q(**{field+'__icontains': value})
if request.POST.get('empty_planting_sites'):
search_results = PlantingSite.objects.values('id', 'id_planting_site', 'address', 'street', 'zipcode', 'neighborhood__name', 'district__name', 'empty').filter(r_address, r_objects, r_neighborhood, r_district, empty=True)
else:
search_results = PlantingSite.objects.values('id', 'id_planting_site', 'address', 'street', 'zipcode', 'neighborhood__name', 'district__name', 'empty').filter(r_address, r_objects, r_neighborhood, r_district)
request.session['search_results'] = list(search_results)
neighborhood_list = Neighborhood.objects.all()
district_list = District.objects.all()
species_list = Species.objects.all()
condition_list = TreeCondition.objects.all()
args = {'search_sent': search_sent, 'planting_site_search': planting_site_search, 'search_results': search_results, 'neighborhood_list': neighborhood_list,
'district_list': district_list, 'species_list': species_list, 'condition_list': condition_list}
args.update(csrf(request))
return render(request, 'uf_search.html', args)
Template:
<form action="/forest/search/" method="post">
{% csrf_token %}
<input type="hidden" name="search_type_id" id="search_type_id" value="1">
<p>
<div class="row">
<div class="col-sm-4">
Address:
</div>
<div class="col-sm-4">
Exact: <input type="checkbox" name="address_exact" id="address_exact" />
</div>
<div class="col-sm-4">
Range: <input type="checkbox" name="address_range" id="address_range" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Range:
</div>
<div class="col-sm-8">
<input type="text" id="address_start" name="address_start" /> to <input type="text" id="address_end" name="address_end" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Exact:
</div>
<div class="col-sm-8">
<input type="text" id="address" name="address" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Street:
</div>
<div class="col-sm-8">
<input type="text" id="street" name="street" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Zipcode:
</div>
<div class="col-sm-8">
<input type="text" id="zipcode" name="zipcode" />
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
Neighborhood:
</div>
<div class="col-sm-8">
<select name="neighborhood_id" id="neighborhood_id">
<option value="">Select:</option>
{% for neighborhood in neighborhood_list %}
<option value="{{neighborhood.id_neighborhood}}">{{neighborhood.name}}</option>
{% endfor %}
</select>
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
District:
</div>
<div class="col-sm-8">
<select name="district_id" id="district_id">
<option value="">Select:</option>
{% for district in district_list %}
<option value="{{district.id_district}}">{{district.name}}</option>
{% endfor %}
</select>
</div>
</div>
</p>
<p>
<div class="row">
<div class="col-sm-4">
</div>
<div class="col-sm-8">
<input type="checkbox" name="empty_planting_sites" id="empty_planting_sites">
Show Empty Planting Sites Only
</div>
</div>
</p>
<input type="submit" name="submit" id="submit" value="Search" />
</form>
Any ideas? Is it something that was dropped in the newest version?
Related
I’m trying to edit a user’s profile in django but when editing the banner image and the profile pictura overlap. I mean, I put a different image on each one, but when I save the form, I get the same image.
When a profile is created both are set by default as it comes in models.py.
views.py
#login_required
def EditProfile(request):
user = request.user.id
profile = Profile.objects.get(user__id=user)
user_basic_info = User.objects.get(id=user)
if request.method == 'POST':
form = EditProfileForm(request.POST, request.FILES, instance=profile)
if form.is_valid():
user_basic_info.first_name = form.cleaned_data.get('first_name')
user_basic_info.last_name = form.cleaned_data.get('last_name')
profile.picture = form.cleaned_data.get('picture')
profile.banner = form.cleaned_data.get('banner')
profile.location = form.cleaned_data.get('location')
profile.url = form.cleaned_data.get('url')
profile.birthday = form.cleaned_data.get('birthday')
profile.bio = form.cleaned_data.get('bio')
profile.save()
user_basic_info.save()
return redirect('users:profile', username=request.user.username)
else:
form = EditProfileForm(instance=profile)
context = {
'form':form,
}
return render(request, 'users/edit.html', context)
forms.py
class EditProfileForm(forms.ModelForm):
first_name=forms.CharField(
widget=forms.TextInput(attrs={
'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md',
})
)
last_name=forms.CharField(
widget=forms.TextInput(attrs={
'class': 'shadow-sm focus:ring-indigo-500 dark:bg-dark-third dark:text-dark-txt focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md',
})
)
picture = forms.ImageField(label='Profile Picture', required=False, widget=forms.FileInput)
banner = forms.ImageField(label='Banner Picture', required=False, widget=forms.FileInput)
location = forms.CharField(widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=25, required=False)
url = forms.URLField(label='Website URL', widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=60, required=False)
bio = forms.CharField(widget=forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), max_length=260, required=False)
birthday = forms.DateField(widget= forms.TextInput(attrs={'class': 'max-w-lg block w-full shadow-sm dark:bg-dark-third dark:text-dark-txt dark:border-dark-third focus:ring-indigo-500 focus:border-indigo-500 sm:max-w-xs sm:text-sm border-gray-300 rounded-md'}), required=False)
class Meta:
model = Profile
fields = ('first_name','last_name','picture','banner','location','url','bio','birthday')
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
picture = models.ImageField(default='users/user_default_profile.png', upload_to=user_directory_path_profile)
banner = models.ImageField(default='users/user_default_bg.jpg', upload_to=user_directory_path_banner)
verified = models.CharField(max_length=10, choices=VERIFICATION_OPTIONS, default='unverified')
followers=models.ManyToManyField(User, blank=True, related_name="followers")
date_created = models.DateField(auto_now_add=True)
location=models.CharField(max_length=50, null=True, blank=True)
url=models.CharField(max_length=80, null=True, blank=True)
birthday=models.DateField(null=True, blank=True)
bio = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.user.username
edit.html
<form class="form-horizontal dark:text-dark-txt" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="mt-1 sm:mt-0 sm:col-span-2">
<img class="h-28 w-full bg-cover" src="{{user.profile.banner.url}}" alt="{{profile.user.username}} Banner Picture">
<div class="max-w-lg flex justify-center px-6 pt-5 pb-6 border-2 dark:border-dark-third border-gray-300 border-dashed rounded-md">
{{form.banner}}
<div class="space-y-1 text-center">
<div class="flex text-sm text-gray-600">
</div>
</div>
</div>
<!--Profile Picture-->
<div class="mt-4 sm:grid sm:grid-cols-3 sm:gap-4 sm:items-center sm:border-t dark:border-dark-third border-gray-200 sm:pt-5">
<label for="photo" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Photo
</label>
<div class="mt-1 sm:mt-0 sm:col-span-2">
<div class="flex items-center">
<span class="mr-4 h-18 w-18 rounded-full overflow-hidden dark:bg-dark-third bg-gray-100">
<img src="{{user.profile.picture.url}}" alt="">
</span>
{{form.picture}}
</div>
</div>
</div>
<div class="mt-4">
<label for="first name" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
First Name
</label>
{{form.first_name}}
</div>
<label for="last name" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Last Name
</label>
{{form.last_name}}
<label for="bio" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Bio
</label>
{{form.bio}}
<label for="city" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Location: City, Country
</label>
{{form.location}}
<label for="birthday" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Date of Birth: yyyy-mm-dd
</label>
{{form.birthday}}
<label for="url" class="block text-sm font-medium dark:text-dark-txt text-gray-700">
Website URL
</label>
{{form.url}}
</div>
<div class="control-group">
<div class="controls">
<a href="{% url 'users:profile' username=user.username %}" class="mt-4 inline-flex items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded dark:text-dark-txt text-indigo-700 dark:bg-dark-second bg-indigo-100 dark:hover:bg-dark-third hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-dark-third focus:ring-indigo-500">
Return to Profile </a>
<button type="submit" class="mt-4 inline-flex float-right items-center px-2.5 py-1.5 border border-transparent text-xs font-medium rounded dark:text-dark-txt text-indigo-700 dark:bg-dark-third bg-indigo-100 dark:hover:bg-dark-third hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:focus:ring-dark-third focus:ring-indigo-500">
Update</button>
</div>
</div>
</div>
</form>
I have two models: PersonelModel and ArizaModel. Both in one html form.
Personel data was previously saved in the PersonelModel table. When the fetch data button is pressed, the data is fetched by querying according to the p_sicil field. It is displayed in the p_isim and p_bilgisayar_adi fields. I created the required relationship between PersonelModel and ArizaModel.
I want to save the data I entered in the a_aciklama field into the database according to the relationship between PersonelModel and ArizaModel.
Screenshot of html form
How can i do that?
models.py:
class PersonelModel(models.Model):
p_sicil = models.CharField(max_length=8, verbose_name='Personel Sicili')
p_isim = models.CharField(max_length=50, verbose_name='Personel Adı')
p_bilgisayar_adi = models.CharField(max_length=4, verbose_name='Bilgisayar Adı')
p_durum = models.BooleanField(default=True, verbose_name='Personel Durumu')
birim = models.ForeignKey(BirimModel, verbose_name=("BİRİM"), on_delete=models.DO_NOTHING, null=True)
grup = models.ForeignKey(GrupModel, verbose_name=("GRUP"), on_delete=models.DO_NOTHING, null=True)
unvan = models.ForeignKey(UnvanModel, verbose_name=("ÜNVAN"), on_delete=models.DO_NOTHING, null=True)
class Meta:
db_table = 'PersonelTablosu'
verbose_name = "PERSONEL"
verbose_name_plural = "PERSONELLER"
def __str__(self):
return self.p_sicil
class ArizaModel(models.Model):
a_aciklama = models.CharField(max_length=100, verbose_name='Arıza Açıklama')
a_acilma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Açılma Tarihi')
a_durum = models.BooleanField(default=True, verbose_name='Arıza Durumu')
a_kapanma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Kapanma Tarihi')
birim = models.ForeignKey(BirimModel, verbose_name=("BİRİM"), on_delete=models.DO_NOTHING, null=True)
teknik_personel = models.ForeignKey(TeknikPersonelModel, verbose_name=("TEKNİK PERSONEL"), on_delete=models.DO_NOTHING, null=True)
personel_ariza_acan = models.ForeignKey(PersonelModel, verbose_name=("AÇAN PERSONEL"), on_delete=models.DO_NOTHING, null=True)
class Meta:
db_table = 'ArizaTablosu'
verbose_name = "ARIZA"
verbose_name_plural = "ARIZALAR"
def __str__(self):
return self.a_aciklama
forms.py:
class PersonelBilgileriForm(forms.ModelForm):
p_sicil = forms.CharField(widget=forms.TextInput(attrs={
'class' : 'form-control',
'placeholder' : 'ab sicil',
'maxlength' : '8'
}))
p_isim = forms.CharField(widget=forms.TextInput(attrs={
'class' : 'form-control',
'placeholder' : 'Adınız Soyadınız',
'maxlength' : '50'
}))
p_bilgisayar_adi = forms.CharField(widget=forms.TextInput(attrs={
'class' : 'form-control',
'placeholder' : 'Bilgisayar adınızın son 4 hanesi',
'maxlength' : '4'
}))
class Meta:
model = PersonelModel
fields = ['p_sicil','p_isim','p_bilgisayar_adi']
class ArizaBilgileriForm(forms.ModelForm):
a_aciklama = forms.CharField(widget=forms.Textarea(attrs={
'class' : 'form-control',
'placeholder' : 'Arızayı yazınız'
}))
class Meta:
model = ArizaModel
fields = ['a_aciklama']
views.py:
def kullaniciArizaKaydetView(request):
if request.method == 'POST':
form2 = ArizaBilgileriForm(request.POST, prefix='ariza_bilgileri')
kullaniciningirdigisicil = request.POST['sicildenpersonelbulinput']
try:
personelbilgileri = PersonelModel.objects.get(p_sicil=kullaniciningirdigisicil)
icerik = {'bulunanbilgi':kullaniciningirdigisicil, 'personelbilgileri':personelbilgileri, 'ArizaBilgileriForm': form2}
return render(request, 'kullanici.html', icerik)
except:
return render(request, 'kullanici.html', {"hata":"kullanıcı tanımlı değil"})
else:
return render(request, 'kullanici.html')
kullanici.html: form area
<form action="{% url 'kullaniciGetirURL' %}" method="POST" id="form-box" class="p-2">
{% csrf_token %}
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<input type="search" class="form-control" value="{{personelbilgileri.p_sicil}}" name="sicildenpersonelbulinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit">Kişisel Bilgileri Getir</button>
</div>
</div>
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user"></i></span>
</div>
<input type="text" class="form-control" placeholder="{{personelbilgileri.p_isim}}" name="" readonly>
</div>
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-desktop"></i></span>
</div>
<input type="text" class="form-control" placeholder="{{personelbilgileri.p_bilgisayar_adi}}" name="" readonly>
</div>
{% if personelbilgileri %}
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-comment-alt"></i></span>
</div>
{{ArizaBilgileriForm.a_aciklama}}
</div>
<div class="form-group">
<input type="submit" name="submit" id="submit" class="btn btn-primary btn-block" value="ARIZA BİLDİR">
</div>
{% endif %}
</form>
How can I save it to the database after the information is entered in the form?
I am working on a project which is online printing ordering service.
Here on the order page I am getting different attributes of product in radio button list in the form, and all the attributes I want to store in a single json in database.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
# this is the order table , there is a "attribute_field" I wantto store the attributes in this field
# as JSON.
class Order(models.Model):
order_id = models.AutoField("Order ID", primary_key=True)
user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID")
prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID")
quantity = models.ImageField('Product Quantity', max_length=10, default=500)
attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False)
order_date = models.DateField("Order Date", auto_now_add=True, null=False)
order_job_title = models.CharField("Name of Company/Business", max_length=100, null=False)
order_desc = models.CharField("Details for Product", max_length=1000, null=False)
product_img = models.ImageField("Template Image", null=False)
address = models.CharField("Customer Address ", max_length=100, null=False)
state = models.CharField("Customer State", max_length=30, null=False)
city = models.CharField("Customer City", max_length=30, null=False)
postal_code = models.IntegerField("Area Pin Code", null=False)
order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
class ColorProductMapping(models.Model):
color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
class PaperChoiceProductMapping(models.Model):
paper_p_map_id = models.AutoField("Paper Choices & Product Map ID", primary_key=True, auto_created=True)
paper_id = models.ForeignKey(PaperChoice, null=False, on_delete=models.CASCADE, verbose_name="Paper ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
this is my views.py and it is incomplete , I want to store the forms data in the model using this
view.
views.py
#here in thi view method I am only getting data from models but not getting template data to store in the the model,
# I know I haven't taken inputs from the form here
# I haven't done because I don't know what logic I should use here.
def order(request, id):
products = Product.objects.all()
sizesList = []
ColorsList = []
PaperChoiceProductsList = []
try:
sizesMap = SizeProductMapping.objects.filter(prod_id=id)
sizesList = [data.size_id.prod_size for data in sizesMap]
except AttributeError:
pass
try:
colorMap = ColorProductMapping.objects.filter(prod_id=id)
ColorsList = [data.color_id.prod_color for data in colorMap]
except AttributeError:
pass
try:
PaperChoiceProductMap = PaperChoiceProductMapping.objects.filter(prod_id=id)
PaperChoiceProductsList = [data.paper_id.paper_choices_name for data in PaperChoiceProductMap]
except AttributeError:
pass
context = {'products': products,
'sizesList': sizesList,
"ColorsList": ColorsList,
"PaperChoiceProductsList": PaperChoiceProductsList,
}
return render(request, 'user/order.html', context)
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
form
{
position:relative;
}
.tasksInput
{
margin-right:150px;
}
label
{
vertical-align: top;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form>
<div class="card mx-2 my-2 border border-secondary">
<div class="my-2">
<!-- The data I want to store in JSON starts from here -->
{% if sizesList %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="sizeList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Sizes : </h5></label>
<div id="sizeList">
{% for s in sizesList %}
<input id="{{s}}" class="mx-2 my-auto" type="radio" name="size">
<label for="{{s}}">{{s}}</label><br>
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% if ColorsList %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ColorsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Colors : </h5></label>
<div id="ColorsList">
{% for c in ColorsList %}
<input id="{{c}}" class="mx-2 my-auto" type="radio" name="Color">
<label for="{{c}}">{{c}}</label><br>
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% if PaperChoiceProductsList %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ColorsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Paper Choice : </h5></label>
<div id="PaperChoiceProductsList">
{% for pc in PaperChoiceProductsList %}
<input id="{{pc}}" class="mx-2 my-auto" type="radio" name="PaperChoice">
<label for="{{pc}}">{{pc}}</label><br>
{% endfor %}
</div>
</div>
</div>
{% endif %}
<!-- The Data I want to store in the JSON ends here -->
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-success my-2">Place Order</button>
</div>
</div>
</div>
{% endblock %}
As mentioned in above template comment I want to store that data in single JSON.
Can you please help me to create a view for it.
urls.py
path('order/<int:id>', views.order, name="user-order"),
I used jason dump method to store value in single json object and then passed it to the field and it is working for me.
views.py
import json
def order(request, id):
products = Product.objects.all()
sizesList = []
ColorsList = []
PaperChoiceProductsList = []
value = {}
try:
sizesMap = SizeProductMapping.objects.filter(prod_id=id)
sizesList = [data.size_id.prod_size for data in sizesMap]
except AttributeError:
pass
try:
colorMap = ColorProductMapping.objects.filter(prod_id=id)
ColorsList = [data.color_id.prod_color for data in colorMap]
except AttributeError:
pass
try:
PaperChoiceProductMap = PaperChoiceProductMapping.objects.filter(prod_id=id)
PaperChoiceProductsList = [data.paper_id.paper_choices_name for data in PaperChoiceProductMap]
except AttributeError:
pass
if request.method == 'POST':
if request.method == 'POST':
customer_id = request.user
product = Product.objects.get(prod_ID=id)
product_id = product
try:
quantity = request.POST['quantity']
print(quantity)
except MultiValueDictKeyError:
pass
try:
size = request.POST['size']
value.update(size=size)
except MultiValueDictKeyError:
pass
try:
Colour = request.POST['Color']
value.update(Colour=Colour)
except MultiValueDictKeyError:
pass
try:
Paper_Choice = request.POST['PaperChoice']
value.update(Paper_Choice=Paper_Choice)
except MultiValueDictKeyError:
pass
attribute_value = json.dumps(value)
order_store = Order(user_id=customer_id, prod_id=product_id, quantity=quantity, attribute_value=attribute_value,
order_job_title=Job_title, order_desc=Order_Detail, address=User_Address, state=State,
city=City, postal_code=Postal_Code, product_img=TemplateValue)
order_store.save()
context = {'products': products,
'sizesList': sizesList,
"AqutousCoatingProductList": AqutousCoatingProductList,
"ColorsList": ColorsList,
"PaperChoiceProductsList": PaperChoiceProductsList,
}
return render(request, 'user/order.html', context)
I am implementing search by two fields in form in Django.
I want to keep input data after search.
For example I input "C++" and chose "IT"
then I received Default values
I tried to parse request variable --- e.g. data = request.POST.copy()
but did not achieved result. What is the reason of this problem?
How can I solve this problem?
This is my code:
models.py
class Company(models.Model):
name = models.CharField(max_length=200)
about = models.TextField()
def __str__(self):
return self.name
class Vacancy(models.Model):
company_key = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
salary = models.CharField(max_length=200, default='40.000')
text = models.TextField(default="The text about vacancy")
city = models.CharField(max_length=200, default='Москва')
date_str = models.CharField(max_length=50, default='12 сентября')
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
CHOICES = [
('ALL', 'ALL'),
('IT', 'IT'),
('FINANCE', 'FINANCE'),
('OTHER', 'OTHER'),
]
department = models.CharField(
max_length=20,
choices=CHOICES,
default='ALL',
)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
urls.py
urlpatterns = [
path('', HomePageView.as_view(), name='vacancy_list'),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('vacancy/<int:pk>/', views.vacancy_detail, name='vacancy_detail'),
path('accounts/login/', BBLoginView.as_view(), name='login'),
path('accounts/profile/', profile, name='profile'),
path('accounts/logout/', BBLogoutView.as_view(), name='logout'),
views.py
class HomePageView(ListView):
model = Vacancy
template_name = 'vacancy_list/vacancy_list.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def vacancy_detail(request, pk):
vacancy = get_object_or_404(Vacancy, pk=pk)
return render(request, 'vacancy_list/vacancy_detail.html', {'vacancy': vacancy})
class SearchResultsView(ListView):
model = Vacancy
template_name = 'vacancy_list/search_results.html'
paginate_by = 2
page_kwarg = 'vacancy'
context_object_name = 'vacancies'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
object_list = Vacancy.objects.filter(
Q(title__icontains=query) and Q(department__icontains=query2)
)
return object_list
vacancy_list.html
{% block content %}
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-md-8">
<h1>{{vacancy.title}}</h1>
</div>
<div class="col-md-4 text-right">
<p> {{ vacancy.salary}} </p>
</div>
</div>
</div>
....
{% endfor %}
search_result.html
{% extends 'vacancy_list/base.html' %}
{% block content %}
<h1> {{request}}</h1>
<div class="container col-md-8" style="margin:20px;">
<div class="container" style="margin-top: 40px; font-size: 2rem; padding-left: 0px;">
<form action="{% url 'search_results' %}" method="get">
<div class="row">
<div class="col-lg-8 col-md-6 col-xs-12">
<input name="q" type="text" placeholder="Search..." class="form-control">
</div>
<div class="col-lg-3 col-md-4 col-xs-12">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>ALL</option>
<option>IT</option>
<option>Finance</option>
<option>Other</option>
</select>
</div>
<div class="col-lg-1 col-md-2 col-xs-12" style="padding-left: 0px;">
<button class="btn btn-primary">Primary</button>
</div>
</div>
</form>
</div>
{% for vacancy in vacancies %}
...
{% endfor %}
{% endblock %}
In your search results template, you should use {{ query }} and {{ query2 }} and a little bit of logic to populate the text and drop-down boxes.
I would like to render a Django form in the following manner...
Form UI
In particular, how would I go about populating and rendering the three drop-down lists based on the model provided.
The model
class Positions(models.Model):
position_code = models.CharField(primary_key=True, max_length=8)
name = models.CharField(max_length=64, blank=True, null=True)
description = models.CharField(max_length=4000, blank=True, null=True)
position_type = models.CharField(max_length=8, blank=True, null=True)
class Meta:
managed = False
db_table = 'positions'
class Clubs(models.Model):
club_id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=4, blank=True, null=True)
club_name = models.CharField(max_length=4000, blank=True, null=True)
nickname = models.CharField(max_length=4000, blank=True, null=True)
class Meta:
managed = False
db_table = 'clubs'
class Players(models.Model):
player_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=512, blank=True, null=True)
last_name = models.CharField(max_length=512, blank=True, null=True)
dob = models.CharField(max_length=512, blank=True, null=True)
display_name = models.CharField(max_length=512, blank=True, null=True)
active = models.BooleanField(default=True)
class Meta:
managed = False
db_table = 'players'
class DefaultSquads(models.Model):
default_squad_id = models.AutoField(primary_key=True)
club = models.ForeignKey(Clubs, models.DO_NOTHING)
player = models.ForeignKey('Players', models.DO_NOTHING)
position_code = models.ForeignKey('Positions', models.DO_NOTHING, db_column='position_code', blank=True, null=True)
playing_status_code = models.CharField(max_length=16, blank=True, null=True)
class Meta:
managed = False
db_table = 'default_squads'
The view
class DefaultSquadsViewCreate(CreateView):
template_name = 'fafl/defaultSquad_form.html'
model = DefaultSquads
fields = ['player', 'position_code', 'playing_status_code']
success_url = reverse_lazy('fafl:defaultSquads-list')
def get_context_data(self, **kwargs):
context = super(DefaultSquadsView, self).get_context_data(**kwargs)
context['clubs'] = Clubs.objects.all().order_by('club_id')
context['players'] = Players.objects.all().order_by('player_id')
return context
The template
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="box-body">
<div class="form-group">
<label for="{{ form.club.club_id.id_for_label }}" class="col-sm-2 control-lable">Club</label>
<div class="col-sm-10">
<!-- Not sure how ? -->
<select id="{{ form.club.club_id.id_for_label }}" name="club" class="form-control">
<option value="None"></option>
{% for club in clubs %}
<option value="{{ club.club_id }}" selected="selected">{{ club.nickname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.club_name.id_for_label }}" class="col-sm-2 control-lable">Player</label>
<div class="col-sm-10">
<input id="{{ form.short_name.id_for_label }}" type="text" name="short_name" maxlength="100" class="form-control" required />
</div>
</div>
<div class="form-group">
<label for="{{ form.club_name.id_for_label }}" class="col-sm-2 control-lable">Position</label>
<div class="col-sm-10">
<input id="{{ form.nickname.id_for_label }}" type="text" name="nickname" maxlength="6" class="form-control" required />
</div>
</div>
</div>
<div class="box-footer">
<div class="margin">
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" data-target="#myModal"><i class="fa fa-trash" role="button"></i> Delete</button>
Cancel
<button type="submit" class="btn btn-success"><i class="fa fa-check" role="button"></i> Save</button>
</div>
</div>
</form>
Since your question was only directed to form rendering . . .
In the view:
class DefaultSquadsViewCreate(CreateView):
template_name = 'fafl/defaultSquad_form.html'
model = DefaultSquads
fields = ['player', 'position_code', 'playing_status_code']
success_url = reverse_lazy('fafl:defaultSquads-list')
def get_context_data(self, **kwargs):
context = super(DefaultSquadsView, self).get_context_data(**kwargs)
context['clubs'] = Clubs.objects.all().order_by('club_id')
context['players'] = Players.objects.all().order_by('player_id')
context['positions'] = Positions.objects.all()
return context
In the template:
<div class="form-group">
<label for="{{ form.club.id_for_label }}" class="col-sm-2 control-label">Club</label>
<div class="col-sm-10">
<select id="{{ form.club.id_for_label }}" name="{{ form.club.html_name }}" class="form-control">
<option value="" selected>None</option>
{% for club in clubs %}
<option value="{{ club.club_id }}">{{ club.nickname }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.player.id_for_label }}" class="col-sm-2 control-label">Player</label>
<div class="col-sm-10">
<select id="{{ form.player.id_for_label }}" name="{{ form.player.html_name }}" class="form-control">
<option value="" selected>Please select a player</option>
{% for player in players %}
<option value="{{ player.player_id }}">{{ player.display_name }}</option>
{% endfor %}
</select>
</div>
</div>
<div class="form-group">
<label for="{{ form.postion_code.id_for_label }}" class="col-sm-2 control-label">Position Code</label>
<div class="col-sm-10">
<select id="{{ form.position_code.id_for_label }}" name="{{ form.position_code.html_name }}" class="form-control">
<option value="" selected>Please select a Position</option>
{% for position in positions %}
<option value="{{ position.position_code }}">{{ position.name }}</option>
{% endfor %}
</select>
</div>
</div>