Django RadioSelect Widget as Bootstrap Buttons? - python

I have a Django reviewing and photo sharing application.
When a user submits a new Review instance, they can indicate the 'Method of Consumption' using Select widget, which by default will show choices as a dropdown. This is a very bland look.
I want to use a custom Widget which will render the choices as buttons--not radio buttons, but bootstrap buttons Bootstrap5 Radio Toggle Buttons. This is far more visually appealing.
How do I render the widget such that for each choice, there is a button with value equal to the choice (Flower, Extract, Edible) as shown in the screenshot?
models.py
class Review(models.Model):
title = models.CharField(max_length=35)
content = models.TextField(max_length=500)
strain = models.ForeignKey(
Strain,
on_delete=models.CASCADE,
related_name="user_review"
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name="user_reviews",
default=1
)
photo = models.ImageField(
upload_to=upload_location,
blank=True,
null=True,
height_field="height_field",
width_field="width_field",
)
height_field = models.IntegerField(default=0, null=True)
width_field = models.IntegerField(default=0, null=True)
FLOWER = 'Flower'
EXTRACT = 'Extract'
EDIBLE = 'Edible'
METHOD_CHOICES = (
(FLOWER, 'Flower'),
(EXTRACT, 'Extract'),
(EDIBLE, 'Edible'),
)
method = models.CharField(
max_length=20,
choices=METHOD_CHOICES,
default='Flower',
blank=False
)
RATING_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
)
rating = models.IntegerField(choices=RATING_CHOICES, default=5)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
users_like = models.ManyToManyField(
settings.AUTH_USER_MODEL,
related_name="reviews_liked",
blank=True
)
class Meta:
ordering = ["-timestamp", "-updated"]
def get_absolute_url(self):
return reverse("reviews:review_detail", kwargs={"id": self.id})
def __str__(self):
return self.title
forms.py
class ReviewForm(forms.ModelForm):
photo = forms.ImageField(
required=True,
)
FLOWER = 'Flower'
EXTRACT = 'Extract'
EDIBLE = 'Edible'
METHOD_CHOICES = (
(FLOWER, 'Flower'),
(EXTRACT, 'Extract'),
(EDIBLE, 'Edible'),
)
rating = forms.IntegerField(widget=Stars)
method = forms.ChoiceField(choices=METHOD_CHOICES, widget=MethodSelectWidget)
class Meta:
model = Review
fields = [
"rating",
"title",
"method",
"content",
"photo",
]
labels = {
'title': '',
'content': '',
'method': '',
}
help_texts = {
'method': 'Choose method of consumption'
}
widgets = {
'title': forms.TextInput(attrs={'placeholder': 'Title'}),
'content': forms.Textarea(attrs={'placeholder': 'Description'}),
}
def save(self):
instance = super(ReviewForm, self).save(commit=False)
instance.slug = slugify(instance.title)
instance.save()
return instance
widgets.py
class MethodSelectWidget(forms.Widget):
template_name = 'partials/reviews/widgets/method_select_widget.html'
def get_context(self, name, value, attrs=None):
return {'widget': {
'name': name,
'value': value,
}}
def render(self, name, value, attrs=None, renderer=None):
context = self.get_context(name, value, attrs)
template = loader.get_template(self.template_name).render(context)
return mark_safe(template)
method_select_widget.html
<h2>Form</h2>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-success active">
<input type="radio" name="options" id="option1" autocomplete="off" checked>{{ widget.value }}
</label>
</div>
review_form.html
{% extends "base.html" %}
{% block head_title %}{{ strain.name }} Review | {{ block.super }}{% endblock head_title %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-5">
<div class="h-100 row justify-content-center align-items-center">
<div class="col-sm-6">
<h2 style="font-weight: 600;">Review {{ strain }}</h2>
<hr/>
<form method="POST" action="" enctype="multipart/form-data" class="form">
{% csrf_token %}
{{ form|crispy }}
<button type=submit style="background-color:#6eb257; color: white; font-weight: 600; font-size: 1.2rem; letter-spacing: 1px;"
class="mx-auto mt-3 mb-3 btn btn-block shadow">
Submit
</button>
</form>
</div>
</div>
</div>
{% endblock %}

Related

django clean method is not being called when validating form

I tried the simplest way of form validation I could find using the clean method (I need to validate multiple fields). However, it is not working and it is not throwing any errors.
forms.py
class DOEForm1(ModelForm):
class Meta:
model = Doe
labels = {
'column_parameter': ('Parameter to vary'),
'column_min': ('Minimum value'),
'column_max': ('Maximum value'),
'column_step': ('Step value'),
}
exclude = ('substrate','row_parameter','row_min','row_max','row_step',)
def clean(self):
cleaned_data = super().clean()
print('test')
min = cleaned_data.get('column_min')
max = cleaned_data.get('column_max')
step = cleaned_data.get('column_step')
if min and max and step:
if not (int(step) > 10):
raise ValidationError(
'(!) the parameters you inputted dont go well with the substrate size'
)
return cleaned_data
template
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<br>
<div class="row" style = "padding-left: 15px; width: 500px; margin: auto;">
<div class="col" style = "margin: auto; ">
<div class="card card-body">
<form style = "margin: auto; width: 400px; padding: 20px; border: 1px solid #270644;" action="" method="POST">
{% csrf_token %}
<table>
{{ St_form.as_table }}
{{ DOE_form.as_table }}
</table>
{% for error in form.non_field_errors %}
<p class = "help is-danger">{{ error }}</p>
{% endfor %}
<input type="submit" name="Submit" >
</form>
</div>
</div>
</div>
{% endblock %}
views.py
def ST_parameters(request):
st_form = STForm()
doe_form = DOEForm1()
if request.method == 'POST':
#print('Printing POST: ', request.POST)
st_form = STForm(request.POST)
doe_form = DOEForm1(request.POST)
if st_form.is_valid() and doe_form.is_valid():
st = st_form.save()
doe = doe_form.save(False)
doe.st=st
doe.save()
return redirect('user-page')
context ={'St_form':st_form,'DOE_form':doe_form}
return render(request, 'accounts/ST_form.html',context)
models.py
class Doe(models.Model):
LASER_POWER = "Laser Power"
LASER_SPEED = "Laser speed"
POWDER_FEED="Powder feed rate"
CARRIER_GAS = "Carrier gas"
SHIELD_GAS = "Shield gas"
SPOT_DIAMETER = "Spot Diameter"
NOZZLE_STANDOFF = "Nozzle standoff"
PARAMETER_CHOICES = [
(LASER_POWER, "Laser Power"),
(LASER_SPEED, "Laser Speed"),
(POWDER_FEED, "Powder feed rate"),
(CARRIER_GAS, "Carrier Gas"),
(SHIELD_GAS,"Shield Gas"),
(SPOT_DIAMETER,"Spot Diameter"),
(NOZZLE_STANDOFF, "Nozzle Standoff")
]
doe_id = models.AutoField(db_column='DoE_ID', primary_key=True)
substrate = models.ForeignKey('Substrate', models.SET_NULL, db_column='Substrate_ID', blank=True, null=True) # Field name made lowercase.
row_parameter = models.CharField(max_length=45, choices = PARAMETER_CHOICES,default = LASER_POWER, blank=True, null=True)
row_min = models.CharField(max_length=45, blank=True, null=True)
row_max = models.CharField(max_length=45, blank=True, null=True)
row_step = models.CharField(max_length=45, blank=True, null=True)
column_parameter = models.CharField(max_length=45,choices = PARAMETER_CHOICES,default = LASER_POWER, blank=True, null=True)
column_min = models.CharField(max_length=45, blank=True, null=True)
column_max = models.CharField(max_length=45, blank=True, null=True)
column_step = models.CharField(max_length=45, blank=True, null=True)
class Meta:
db_table = 'doe'
What am I doing wrong here?
When you work with Django Forms, keep in mind this (simplified) validation flow:
form.is_valid() check if not form.errors
form.errors call form.full_clean()
form.full_clean() clean each single field and after will call form.clean()
So if you want to understand what is happening, debug the value of form.is_valid() and form.errors.

Django - what is wrong with my If statement?

I inserted an if statement in my template - I only want the form to appear if the product category is "Champagne".
For some reason, the product does not appear for champagne products.
Here is the code
Models.py
CATEGORY=(
(1,'Rum'),
(2,'Gin'),
(3,'Whisky'),
(4,'Champagne'),
(5,'Others'),
)
class Product(models.Model):
name = models.CharField('Product Name', max_length=120, null=True)
category = models.IntegerField(choices=CATEGORY, default=0)
description = models.TextField(blank=True, null=True)
price = models.DecimalField(null=True, max_digits=6, decimal_places=3)
image_url= models.URLField('Image Web Address', blank=True)
product_url = models.URLField('Product Web Address', blank=True)
class Meta:
db_table='Product'
def __str__(self):
return str(self.name)
HTML
{% if product.category == 'Champagne' %}
<div class="d-flex flex-column mt-4">
<a class="btn btn-outline-secondary btn-sm" href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a>
</div>
{% endif %}
Forms.py
class DrinkForm(ModelForm):
class Meta:
model = Product
fields = ('name','category', 'description')
labels ={
'name': '',
'category': '',
'description': '',
}
widgets = {
'name': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter name'}),
'category': forms.Select(attrs={'class':'form-control', 'placeholder':'Enter category'}),
'description':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter description'}),
}
You have to use 4 insted of "Champagne"
4 is value and "Champagne" is label
HTML
{% if product.category == 4 %}
<div class="d-flex flex-column mt-4">
<a class="btn btn-outline-secondary btn-sm" href="{% url 'ElderFlowerReview' product.id %}">Tasting Notes</a>
</div>
{% endif %}

Store multiple inputs values of form in single json to store in model field. - Django

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)

How to add the option that checks if checkbox is checked and deletes checked objects in Django

Hello I'm a new comer to Django. I'm confused now having the thought of how django admin panel deleting option works and how to use that option in my site.The purpose is to use all CRUD options in one template not just with url like deleting one by one.
I have a models.py:
GRADES = (
('1', '1',), ('2', '2',),
('3', '3',), ('4', '4',),
('5', '5',), ('6', '6',),
('7', '7',), ('8', '8',),
('9', '9',), ('10', '10',),
('11', '11',),
)
class Grade(models.Model):
grade = models.CharField(null=True, max_length=200,
choices=GRADES, unique=True)
def __str__(self):
return self.grade
class Unique_grade(models.Model):
grades = models.ForeignKey(
Grade,
null=True, on_delete=models.SET_NULL,
verbose_name="Sinf raqamini kiriting",
)
A_B_C = models.CharField(max_length=1, null=True,)
motto = models.TextField(max_length=200, null=True,
verbose_name='Shior', blank=True,
unique=True, default=None)
class Meta:
unique_together = ['grades', 'A_B_C']
def clean_motto(self):
if self.cleaned_data['motto'] == "":
return None
else:
return self.cleaned_data['motto']
def __str__(self):
return f"{self.grades}-{self.A_B_C}"
class Pupil(models.Model):
first_name = models.CharField(max_length=200, null=True)
surname = models.CharField(max_length=200, null=True)
date_of_birth = models.DateField(
null=True)
nation = models.CharField(
max_length=100, null=True, verbose_name="Nation")
grade = models.ForeignKey(Unique_grade, null=True,
on_delete=models.SET_NULL)
m_full_name = models.CharField(
max_length=200, null=True, verbose_name="Mother's full name")
f_full_name = models.CharField(
max_length=200, null=True, verbose_name="Father's full name")
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = [
['first_name', 'date_of_birth',
'surname', 'nation',
'grade', 'm_full_name',
'f_full_name'],
]
def __str__(self):
return f"{self.first_name} {self.surname}."
my forms.py:
class CreateUniqueGrade(ModelForm):
class Meta:
model = Unique_grade
fields = "__all__"
error_messages = {
NON_FIELD_ERRORS: {
'unique_together': "Bunday sinf mavjud!",
},
}
def clean_motto(self):
if self.cleaned_data['motto'] == "":
return None
else:
return self.cleaned_data['motto']
my views.py:
from .models import *
from .forms import CreateUniqueGrade
from datetime import date
current_year = date.today().year
grade_nums = Grade.objects.all()
unique_grades = Unique_grade.objects.all()
def home(request):
content = {'grades': grade_nums, 'unique_grades': unique_grades,
'current_year': current_year}
return render(request, 'accounts/dashboard.html/', content)
def grades(request, g):
# grades = Grade.objects.all()
cform = CreateUniqueGrade()
if request.method == "POST":
cform = CreateUniqueGrade(request.POST)
if cform.is_valid():
cform.save()
return redirect(f'/grades/{g}')
uni = Unique_grade.objects.all().get(id=g)
unique_grade = Unique_grade.objects.all()
content = {
'grade': unique_grade.filter(grades=g),
'grades': grade_nums,
'unique_grades': unique_grades,
'current_year': current_year,
'g': g,
'Unique': cform,
}
return render(request, 'accounts/grades.html/', content)
def pupils(request, g, p):
pupil = Pupil.objects.all()
content = {
'pupil': pupil.filter(grade_id=p),
'grades': grade_nums,
'unique_grades': unique_grades,
'current_year': current_year
}
return render(request, 'accounts/pupils.html/', content)
def about(request):
return render(request, 'accounts/about.html/', {'grades': grade_nums, 'unique_grades': unique_grades, 'current_year': current_year})
def for_each_pupil(request, g, p, for_each):
pupil = Pupil.objects.all()
content = {'pupil': pupil.get(id=for_each), 'grades': grade_nums,
'unique_grades': unique_grades, 'current_year': current_year}
return render(request, 'accounts/for_each_pupil.html/', content)
finally my template:
{% extends 'accounts/maktab.html' %} {% load static %} {% block content %}
<!-- css > sinflar.css -->
<h3 id="to_top"></h3>
{% include "accounts/special_icons/plus-minus.html" %}
<div class="row">
{% for i in grade %}
<div class="pupil">
<div class="first fir">
<form action="" method="POST">
<input type="checkbox" name="todelete" value="{{ i.id }}">
</form>
<img src="#" alt="#" />
</div>
<div class="second sec">
<div>
<a
href="{% url 'pupils' i.grades i.id %}"
style="text-decoration: none; color: aliceblue;"
>
<h3 class="is_m">{{i}} sinfi</h3>
{% if i.motto %}
<h3>Shior: {{i.motto}}</h3>
{% endif %}
</a>
</div>
<button class="shr" onclick="forShrink()">shrink</button>
</div>
</div>
{% empty %}
<h2>
Apologies...<br />
But you have no unique grades yet.
</h2>
{% endfor %}
<div class="pupil pup remove" >
<div class="first fir">
<img src="#" alt="#" id="for_ease"/>
</div>
<div class="second">
<form action="" method="POST">
{% csrf_token %} {% if Unique.non_field_errors %}
<style>
.remove {
opacity: 1;
height: 600px;
position: relative;
pointer-events: all;
}
</style>
{{ Unique.non_field_errors }} {% endif %}
<div class="field nums def">
{{ Unique.grades.errors }}
<label for="{{ Unique.grades.id_for_label }}"
>Sinf raqami</label
>
{{ Unique.grades }}
</div>
<div class="field letters def">
<h3>Sinf raqami: {{ g }}</h3>
<label for="{{ Unique.A_B_C.id_for_label }}"
>Sinf Belgisi</label
>
{{ Unique.A_B_C }}
</div>
<div class="field motto">
{% if Unique.motto.errors %}
<style>
.remove {
opacity: 1;
height: 600px;
position: relative;
pointer-events: all;
}
</style>
{{ Unique.motto.errors }} {% endif %}
<label for="{{ Unique.motto.id_for_label }}"
>motto</label
>
{{ Unique.motto }}
</div>
<button type="submit" name="submit" id="subm">
Add
</button>
<br />
<button id="subm">
<a
href="#to_top"
style="text-decoration: none; color: aliceblue;"
onclick="remove()"
>Cancel</a
>
</button>
</form>
</div>
</div>
</div>
<script>
selectElement("id_grades", "{{ g }}");
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
</script>
{% endblock %}
And again main purpose is to have all CRUD in one template without url routing for each object.
Second is to have 'delete by check' option.
Please if you know the answer don't keep silence. Would be very glad! Thanks!

Django form field is displaying uuid of the record

I am using django 2.2 and python 3.6.
I have a django modelform. I am using crispy forms to display the form in template.
The form is not displaying the value of the records. It is displaying the uuid values of the records. I need to display the record name value instead of uuid value.
models.py :
#reversion.register()
class Staff(BaseModel):
user = models.OneToOneField(
User, on_delete=models.PROTECT, db_index=True, verbose_name=_("Kullanıcı"))
photo = models.ImageField(
upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf"))
staff_type = models.ManyToManyField(
StaffType, verbose_name=_("Personel Tipi"))
name = models.CharField(
max_length=100, db_index=True, verbose_name=_("İsim"))
surname = models.CharField(
max_length=100, db_index=True, verbose_name=_("Soyad"))
phone = models.CharField(max_length=100, verbose_name=_("Telefon Numarası"))
email = models.EmailField(verbose_name=_("Email"), db_index=True)
address = models.TextField(verbose_name=_("Adres"))
subject = models.ForeignKey(Subject, on_delete=models.SET(
get_unknown_subject), verbose_name=_("Branş"))
gender = models.IntegerField(
choices=GENDERS, default=None, verbose_name=_("Cinsiyet"))
nationality = models.CharField(
choices=NATIONALITIES, max_length=100, verbose_name=_("Uyruk"))
blood_type = models.CharField(
choices=BLOOD_TYPES, max_length=20, verbose_name=_("Kan Grubu"))
id_no = models.CharField(max_length=100, unique=True,
verbose_name=_("Kimlik No"))
birthdate = models.DateField(verbose_name=_("Doğum Günü"))
birthplace = models.CharField(max_length=200, verbose_name=_("Doğum Yeri"))
education = models.IntegerField(
choices=EDUCATION, default=None, verbose_name=_("Eğitim"))
marital_status = models.BooleanField(
default=True, verbose_name=_("Evlilik Durumu"))
number_of_children = models.IntegerField(
verbose_name=_("Çocuk Sayısı"))
special_notes = models.TextField(
null=True, blank=True, verbose_name=_("Özel Notlar"))
registration_date = models.DateField(verbose_name=_("Kayıt Tarihi"))
foreign_language = models.ForeignKey(Language, on_delete=models.SET(
get_default_language), null=True, blank=True, verbose_name=_("Yabancı Dil"))
class Meta:
permissions = (
("list_staff", _("List Staff")),
)
ordering = ['name', 'surname']
def __unicode__(self):
return "%s %s" % (self.name, self.surname)
def save(self, *args, **kwargs):
self.name = self.name.title()
self.surname = self.surname.upper()
groups = []
for staff_type_object in self.staff_type.all():
group = Group.objects.get_or_create(name=staff_type_object.name)[0]
groups.append(group)
self.user.groups = groups
self.user.save()
super(Staff, self).save(*args, **kwargs)
views.py:
#login_required(login_url='/accounts/login/')
def personelkayit(request):
staffs = Staff.objects.values("user__username", "name", "surname", "uuid")
if request.method == 'GET':
staff_uuid = request.GET.get("staff_uuid")
if staff_uuid:
instance = get_object_or_404(Staff, uuid=staff_uuid)
form = StaffForm(instance=instance)
form.fields['username'].initial = instance.user.username
form.fields['username'].widget.attrs['readonly'] = True
else:
form = StaffForm()
return render(request, 'personelkayit.html', {'form': form, 'staffs':
staffs, 'staff_uuid': staff_uuid})
elif request.method == 'POST':
staff_uuid = request.GET.get("staff_uuid")
if staff_uuid:
instance = get_object_or_404(Staff, uuid=staff_uuid)
form = StaffForm(request.POST or None,
request.FILES or None, instance=instance)
else:
form = StaffForm(request.POST, request.FILES or None)
if form.is_valid():
password = form.cleaned_data.get("password")
re_password = form.cleaned_data.get("re_password")
staff = form.save(commit=False)
staff.user = user
staff.save()
form.save_m2m()
staff.save()
return redirect('/')
else:
return render(request, "personelkayit.html", {'form': form, 'staffs': staffs})
personelkayit.html:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load i18n %}
{% load staticfiles %}
{% block content %}
<br>
<table style="width: 100%">
<tr>
<td style="width: 4%"></td>
<td style="width: 92%">
<div class="block-area" id="basic">
<form role="form" method="get">
<select class="form-control input-sm m-b-10" name="staff_uuid">
<option value="" {% if not staff_uuid %} selected="selected" {% endif %} disabled="disabled">{% trans "Personel" %}</option>
{% for staff in staffs %}
<option {% if staff_uuid and staff.uuid|lower == staff_uuid|lower %}selected="selected"{% endif %} value="{{ staff.uuid }}">{{ staff.user__username }} - {{ staff.name }} {{ staff.surname }}</option>
{% endfor %}
</select>
<br />
<button type="submit" class="btn btn-sm btn-alt">{% trans "Personel Düzenle" %}</button>
<a class="btn btn-sm btn-alt" href="{% url 'personelkayit' %}">{% trans "Personel Ekle" %}</a>
<div class="modal-footer"></div>
</form>
</div>
<div class="block-area" id="basic">
<form role="form" enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ form|crispy }}
<div >
<br>
<button style="background-color: #002266 !important; color: white !important" type="submit" class="btn btn-lg btn-alt"><span class="glyphicon glyphicon-floppy-disk
pull-left"></span>{% trans "Kaydet" %}</button>
</div>
</form>
<br>
</div>
</td>
<td style="width: 4%"></td>
</tr>
</table>
<script>
$( document ).ready(function() {
$( "select[name$='staff_uuid']" ).select2({
theme: "bootstrap"
});
$( "select[name$='subject']" ).select2({
theme: "bootstrap"
});
$( "select[name$='staff_type']" ).select2({
theme: "bootstrap"
});
});
</script>
{% endblock content %}
The reason this happens is because Django will render the string-representation of model objects in the form. A model is, by default rendered by the name of the type of the object, and the primary key. So a string like Subject object (...) is normal.
You can simply implement a __str__ (and for python-2.x a __unicode__) for the Subject model, to render it the way you specify:
class Subject(models.Model):
# …
def __str__(self):
return …

Categories

Resources