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?
Related
I have 2 two models with a one-to-one relation as follow.
class Kategori(models.Model):
urun = models.CharField(db_column='Urun', max_length=255, blank=True, null=True) # Field name made lowercase.
kategori = models.CharField(db_column='Kategori', max_length=255, blank=True, null=True) # Field name made lowercase.
ust_kategori = models.CharField(db_column='Ust_Kategori', max_length=255, blank=True, null=True) # Field name made lowercase.
urun_adi = models.CharField(db_column='URUN_ADI', max_length=255, blank=True, null=True) # Field name made lowercase.
ur_id = models.CharField(db_column='UR_ID', max_length=255, blank=True, null=True) # Field name made lowercase.
marka = models.CharField(db_column='MARKA', max_length=255, blank=True, null=True) # Field name made lowercase.
cesidi = models.CharField(db_column='CESIDI', max_length=255, blank=True, null=True) # Field name made lowercase.
miktar = models.FloatField(db_column='MIKTAR', blank=True, null=True) # Field name made lowercase.
birim = models.CharField(db_column='BIRIM', max_length=255, blank=True, null=True) # Field name made lowercase.
adet = models.FloatField(db_column='ADET', blank=True, null=True) # Field name made lowercase.
class categoryprob(models.Model):
urun = models.OneToOneField(Kategori,on_delete=models.CASCADE,related_name="prob")
kategori = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase.
ust_kategori = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase.
urun_adi = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase.
marka = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase.
cesidi = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase.
miktar = models.FloatField(blank=True, null=True) # Field name made lowercase.
birim = models.CharField(max_length=255, blank=True, null=True) # Field name made lowercase.
adet = models.FloatField(blank=True, null=True) # Field name made lowercase.
I am trying to update Kategori model objects depend on categoryprob inputs. I prepare a form to get Kategori objects depend on their probability at categoryprob as follows.
from django import forms
from mailservice.models import categoryprob,Kategori
PASS_PROB = 0.8
class predictionForm(forms.ModelForm):
class Meta:
model = Kategori
fields = ["urun","kategori","ust_kategori","urun_adi","marka","cesidi","miktar","birim","adet"]
widgets = {
'kategori': forms.Select(choices=set(Kategori.objects.all().values_list('kategori','kategori'))),
'ust_kategori': forms.Select(choices=set(Kategori.objects.all().values_list('ust_kategori','ust_kategori'))),
'marka': forms.Select(choices=set(Kategori.objects.all().values_list('marka','marka'))),
'cesidi': forms.Select(choices=set(Kategori.objects.all().values_list('cesidi','cesidi'))),
'miktar': forms.Select(choices=set(Kategori.objects.all().values_list('miktar','miktar'))),
'birim': forms.Select(choices=set(Kategori.objects.all().values_list('birim','birim'))),
'adet': forms.Select(choices=set(Kategori.objects.all().values_list('adet','adet'))),
}
labels ={
'urun':""
}
def __init__(self, *args, **kwargs):
super(predictionForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
prob = categoryprob.objects.get(urun=instance)
self.fields['urun'].widget.attrs['readonly'] = True
if float(prob.kategori) > PASS_PROB:
self.fields['kategori'].widget.attrs['disabled'] = True
self.fields['kategori'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['kategori'].widget.attrs['style'] = 'border-color:green'
if float(prob.ust_kategori) > PASS_PROB:
self.fields['ust_kategori'].widget.attrs['disabled'] = True
self.fields['ust_kategori'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['ust_kategori'].widget.attrs['style'] = 'border-color:green'
if float(prob.urun_adi) > PASS_PROB:
self.fields['urun_adi'].widget.attrs['disabled'] = True
self.fields['urun_adi'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['urun_adi'].widget.attrs['style'] = 'border-color:green'
if float(prob.marka) > PASS_PROB:
self.fields['marka'].widget.attrs['disabled'] = True
self.fields['marka'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['marka'].widget.attrs['style'] = 'border-color:green'
if float(prob.cesidi) > PASS_PROB:
self.fields['cesidi'].widget.attrs['disabled'] = True
self.fields['cesidi'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['cesidi'].widget.attrs['style'] = 'border-color:green'
if float(prob.miktar) > PASS_PROB:
self.fields['miktar'].widget.attrs['disabled'] = True
self.fields['miktar'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['miktar'].widget.attrs['style'] = 'border-color:green'
if float(prob.birim) > PASS_PROB:
self.fields['birim'].widget.attrs['disabled'] = True
self.fields['birim'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['birim'].widget.attrs['style'] = 'border-color:green'
if float(prob.adet) > PASS_PROB:
self.fields['adet'].widget.attrs['disabled'] = True
self.fields['adet'].widget.attrs['style'] = 'border-color:red'
else:
self.fields['adet'].widget.attrs['style'] = 'border-color:green'
I use modelformset_factory to render 3 of them together. Everything works fine when I am rending on the template as follows.
<form method="post" enctype="multipart/form-data">
<div class="form-row">
{{ p_form.management_form }}
{% csrf_token %}
{%for form in p_form%}
<div class="form-group col-md-12">
<div class="card">
<div class="card-header">
{{form.urun|as_crispy_field}}
</div>
<div class="card-body">
<div class="row">
<div class ="col-md-3 col ">
{{form.kategori|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.ust_kategori|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.urun_adi|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.marka|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.cesidi|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.miktar|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.birim|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.adet|as_crispy_field}}
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<button type="submit" class="btn btn-success">Kaydet</button>
</form>
When I submit with post method as follows:
def editCategories(request):
categories = Kategori.objects.all().order_by('?')[:3]
CategoryFormSet = modelformset_factory(Kategori, form = predictionForm,extra=0)
formset = CategoryFormSet(queryset = categories)
if request.method == "POST":
if formset.is_valid():
formset.save()
return redirect(request.META['HTTP_REFERER'])
content = {
"p_form":formset,
}
return render(request,'edit_categories.html',content)
formset.is_valid return false all the time.
I couldn't figure out how to validate all forms at once. Do you have any suggestion?
Picture of template output:
The output of the request.POST:
<QueryDict: {'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'csrfmiddlewaretoken': ['*****'], 'form-0-id': ['125'], 'form-0-urun': ['_MotorinEcoForce'], 'form-0-urun_adi': ['asdasd'], 'form-1-id': ['186'], 'form-1-urun': ['7 stick sakız karpuz aromalı 12 adet'], 'form-1-marka': ['7 days'], 'form-2-id': ['159'], 'form-2-urun': ['7 Days Kruvasan Kayısılı Tekli 72 g'], 'form-2-kategori': ['Sebze']}>
One can say there are two kinds of forms a bound form and an unbound form. What is the difference between these? Well a bound form is passed some data MyForm(request.POST, request.FILES) and an unbound form isn't passed any data MyForm(). By logic an unbound form can never be valid because, well it was never submitted and it is assumed to be created to simply display / render the form.
This logic similarly follows for formsets, and hence as you haven't passed any data to your formset it will never be valid. Another thing to be considered is that you haven't rendered the hidden fields for the formset. A formset makes certain hidden fields so that it can recognize which sub form is for which objects and some other things like deletion, etc. Without these hidden fields also your formset would be invalid.
Hence your view should be like:
def editCategories(request):
categories = Kategori.objects.all().order_by('?')[:3]
CategoryFormSet = modelformset_factory(Kategori, form = predictionForm,extra=0)
formset = CategoryFormSet(queryset = categories)
if request.method == "POST":
# Will get inefficient later on when you have many objects in the database, look for a different solution
formset = CategoryFormSet(request.POST, request.FILES) # Make a bound formset in case of a POST request
if formset.is_valid():
formset.save()
return redirect(request.META['HTTP_REFERER'])
content = {
"p_form":formset,
}
return render(request,'edit_categories.html',content)
Your template should be like:
<form method="post" enctype="multipart/form-data">
<div class="form-row">
{{ p_form.management_form }}
{% csrf_token %}
{%for form in p_form%}
{# Render hidden fields #}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
<div class="form-group col-md-12">
<div class="card">
<div class="card-header">
{{form.urun|as_crispy_field}}
</div>
<div class="card-body">
<div class="row">
<div class ="col-md-3 col ">
{{form.kategori|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.ust_kategori|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.urun_adi|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.marka|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.cesidi|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.miktar|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.birim|as_crispy_field}}
</div>
<div class ="col-md-3 col">
{{form.adet|as_crispy_field}}
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<button type="submit" class="btn btn-success">Kaydet</button>
</form>
Also you set fields to be disabled only by adding a disabled attribute to their widget, this means they are not posted with the form, but since the field itself is not disabled it looks for their data, doesn't find it and sets it to None, instead you want to disable the field itself:
class predictionForm(forms.ModelForm):
...
def __init__(self, *args, **kwargs):
...
# truncated for shortness
# similar needs to be done for other fields too
if float(prob.kategori) > PASS_PROB:
self.fields['kategori'].disabled = True
self.fields['kategori'].widget.attrs['style'] = 'border-color:red'
...
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 working on a project in Django where two custom build user model is used.
Industry
Employee
Here every Industry user will entry some of their Employee's data, and later on Employee will verify and finish to create his account.
my models.py:
class myCustomeUser(AbstractUser):
id = models.AutoField(primary_key=True)
username = models.CharField(max_length=20, unique="True", blank=False)
password = models.CharField(max_length=20, blank=False)
is_Employee = models.BooleanField(default=False)
is_Inspector = models.BooleanField(default=False)
is_Industry = models.BooleanField(default=False)
is_Admin = models.BooleanField(default=False)
class Industry(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user')
name = models.CharField(max_length=200, blank=True)
owner = models.CharField(max_length=200, blank=True)
license = models.IntegerField(null=True, unique=True)
industry_extrafield = models.TextField(blank=True)
class Employee(models.Model):
user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='employee_releted_user', blank=True)
#industry = models.OneToOneField(Industry, on_delete=models.CASCADE, related_name='employee_releted_industry')
industry = models.ForeignKey(Industry, on_delete=models.CASCADE)
i_id = models.IntegerField(null=True, blank=False, unique=True)
name = models.CharField(max_length=200, blank=False, null=True)
gmail = models.EmailField(null=True, blank=False, unique=True)
rank = models.CharField(max_length=20, blank=False, null=True)
employee_varified = models.BooleanField(default=False, blank=True)
Now I wrote the following code in views.py to create an Employee's entry by Industry user when the Industry user signed in from their account:
#method_decorator(industry_required, name='dispatch')
class industryDetails(DetailView):
model = Industry
template_name = 'app/industryDetails.html'
def get_queryset(self):
return Industry.objects.filter(user=self.request.user)
def get_object(self):
return get_object_or_404(Industry, user=self.request.user)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['inserted_text'] = "inserted text from EmployeeDetails of views.py"
return context
def employeeRegister_byIndustry(request):
employeeRegister_dict={
'insert_me' : "hello this is extra inserted"
}
if request.method == "POST":
this_i_id = request.POST['i_id']
this_name = request.POST['name']
this_rank = request.POST['rank']
this_gmail = request.POST['gmail']
this_industry = self.request.user.industry_releted_user
employee_obj = Employee.objects.create(industry=this_industry, i_id=this_i_id, name=this_name, rank=this_rank, gmail=this_gmail)
employee_obj.save()
if employee_obj.is_valid():
print('valid employee Object')
return redirect('app:employeeSignup')
return render(request, 'app/employeeSignup.html', employeeRegister_dict)
and my template (industryDetails.html):
<div class="container-fluid">
<div class="row m-0">
<div class="col-xl-10 mx-auto">
<p>inserted text: {{ inserted_text }}</p>
<hr>
<h3>Username: {{ industry.user }}</h3>
<p>name: {{ industry.name }}</p>
<p>owner: {{ industry.owner }}</p>
<p>license: {{ industry.license }}</p>
<p>id: {{ industry.user.id }}</p>
<p>username: {{ industry.user.username }}</p>
<p>password: {{ industry.user.password }}</p>
</div>
</div>
</div>
<div class="my-5"></div>
<hr>
<div class="my-5"></div>
<div class="container-fluid">
<div class="row m-0">
<div class="col-xl-8">
</div>
<div class="col-xl-3">
<h3>Add new Employee</h3>
<form class="" action="{% url 'app:employeeRegister_byIndustry' %}" method="post">
{% csrf_token %}
<div class="form-group">
<label>Enter industrial id</label>
<input type="text" class="form-control" name="i_id" placeholder="Industrial id">
</div>
<div class="form-group">
<label>Enter employee name</label>
<input type="text" class="form-control" name="name" placeholder="Employee name">
</div>
<div class="form-group">
<label>rank</label>
<input type="text" class="form-control" name="rank" placeholder="rank">
</div>
<div class="form-group">
<label>Enter employee's gmail</label>
<input type="email" class="form-control" name="gmail" placeholder="gmail">
</div>
<button type="submit" class="btn btn-primary" name="button">Submit</button>
</form>
</div>
</div>
</div>
But here the Foreign Key assignment does not working as I want. How can I fix it?
self.request.user is a user model object, so in thus case a myCustomUser object, not an Industry object. You can access the related Industry object with:
this_industry = request.user.industry_releted_user
This is thus the name of the relation from Industry to myCustomUser in reverse, the name of that relation is determined by the related_name=… parameter [Django-doc].
I would also advise to make use of ModelForm [Django-doc] to validate and clean user input. A POST request can lack certain data or can be forged, so request.POST will for example not per see contain a value for name. A form makes it convenient to validate that all required data is present, check if the email address is indeed a valid email address, and convert data from a string-like object to a python object that is more specific to the model field.
I am trying to upload pictures from an imageField, but it doesn't upload anything when I try.
models.py
def upload_location(instance, filename):
return "uploads/%s/img/%s/" % (instance.id, filename)
class CustomUser(AbstractBaseUser, PermissionsMixin):
...
width_field = models.IntegerField(default=0)
height_field = models.IntegerField(default=0)
photo = models.ImageField(
upload_to=upload_location,
null=True, blank=True,
width_field="width_field",
height_field="height_field"
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
objects = UserManager()
forms.py
class UserConfigurationForm(UserChangeForm):
class Meta:
model=CustomUser
fields = ('first_name', 'last_name', 'email', 'phone_number',
'direction', 'password', 'photo',)
views.py
def configuration(request):
categoria = Clasificacion.objects.filter(existencia=True)
templates = Templates.objects.get(isSelected=True)
if request.method == 'GET':
form = UserConfigurationForm(instance=request.user)
else:
form = UserConfigurationForm(request.POST or None, request.FILES or None, instance=request.user)
if form.is_valid():
form.save()
return redirect('myuser:myuser')
return render(request, 'myuser/configuration.html', {'form': form, 'categoria':categoria,'templates':templates})
template
<form method="post" action='' enctype="multipart/form-data">
{%csrf_token%}
<div class="col-sm-8 ">
<strong>{{form.photo}}</strong></div>
<!--FIRST NAME-->
<label for="first_name">Nombre</label>
<div class="form-group">
<input class= "form-control" type="text" name="first_name" maxlength="20" value="{{user.first_name}}" required>
</div>
<label for="last_name">Apellidos</label>
<div class="form-group">
<input class="form-control" type="text" name="last_name" value="{{user.last_name}}">
</div>
<!--Username and email is same in this case-->
<label for="last_name">Correo electrónico</label>
<div class="form-group">
<input class= "form-control" type="email" name="email" value="{{user.email}}" required>
</div>
<!--Phone number-->
<label for="phone_number">Teléfono</label>
<div class="form-group">
<input class= "form-control" type="tel" pattern="[0-9]{4}-[0-9]{3}-[0-9]{4}" name="phone_number" placeholder="Formato ejem: 0414-685-4716" value="{{user.phone_number}}"required>
</div>
<!--Direction-->
<label for="direction">Dirección</label>
<div class="form-group">
<textarea id="direction" class= "form-control" rows="6" name="direction"
value="{{user.direction}}" required>{{user.direction}}</textarea>
</div>
<!--SUBMIT-->
<div class="form-group">
<div class="col-xs-12">
<br>
<button type="submit" class="btn btn-lg btn-success">Guardar cambios</button>
</div>
</form>
I did it before but I don't know what is causing this. The other fields are working fine, I just have the problem with the photo. I put the enctype, and the request.FILES but it doesn't work.
Hope you can help me! Thank you!
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?