I wanna display the text value of a foreign key on the templante, in a way that the user cannot change it.
Template:
{% for form in formset %}
<div class="">
{% for field in form %}
{{ field }}
{% endfor %}
</div>
{% endfor %}
HTML render:
<select name="form-0-semestre_solicitacao" id="id_form-0-semestre_solicitacao">
<option value="">---------</option>
<option value="5">2020/1</option>
<option value="4">2019/2</option>
<option value="3" selected="">2019/1</option>
<option value="2">2018/2</option
<option value="1">2018/1</option>
</select>
I tried {{ field.initial }} and {{ field.value }} but it displays 3 and i would like it to display the text: 2019/1
Update:
The field in display refers to the Foreign Key in semestre_solicitacao
models.py
class Solicitacao(models.Model):
"""Solicitações, depende de User e curso"""
#TODO trocar homologada de boolean para choice homologada e não homologada, e ajustar forms
solicitante = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
disciplina = models.ForeignKey(Disciplina, on_delete=models.CASCADE)
justificativa = models.TextField(("Justificativa para o pedido"),
help_text="O candidato pode explicar os motivos para solicitar a prova, por exemplo: experiência profissional, cursos não regulares, aproveitamentos indeferidos, entre outros.", blank=True, null=True)
documentos = models.FileField(("Documentos comprobatorios de conhecimentos"),
upload_to=None, max_length=100, blank=True, null=True,
validators=[FileExtensionValidator(['.pdf'])])
data_solicitacao = models.DateTimeField(
("Data da solicitação"), auto_now_add=True)
cursou_anteriormente = models.BooleanField(
("Cursou anteriormente a disciplina solicitada"), blank=True, null=True)
homologada = models.BooleanField(blank=True, null=True)
semestre_solicitacao = models.ForeignKey(Calendario, on_delete=models.CASCADE, null=True)
Views.py
from extra_views import ModelFormSetView
class ItemFormSetView(ModelFormSetView):
model = Solicitacao
fields = ['semestre_solicitacao', 'solicitante', 'disciplina', 'cursou_anteriormente']
template_name = 'manage_solicitacoes.html'
success_url = reverse_lazy('cc:solicitacoes')
factory_kwargs = {'extra': 0}
def get_queryset(self):
slug = self.kwargs['slug']
return super(ItemFormSetView, self).get_queryset().filter(semestre_solicitacao__slug=slug)
I'm using django-extra-views.
Update 2:
I'm getting the top part of the image, and i would like something similar to the one in the bottom
Others Models:
class Calendario(models.Model):
"""Calendario referente as datas do semestre"""
ano = models.CharField(
("Ano"), max_length=4,
help_text='Ano dos pedidos, ex: 2020')
semestre = models.CharField(
("Semestre"), max_length=1,
help_text='Semestre dos pedidos')
is_active = models.BooleanField('Calendário em vigor', default=True)
inicio_solicitacoes = models.DateField(
"Inicío das Solicitações", auto_now=False, auto_now_add=False)
fim_solicitacoes = models.DateField(
"Fim das Solicitações", auto_now=False, auto_now_add=False)
inicio_recursos = models.DateField(
"Inicío dos Recursos", auto_now=False, auto_now_add=False)
fim_recursos = models.DateField(
"Fim dos Recursos", auto_now=False, auto_now_add=False)
slug = models.SlugField(unique=True)
class Meta():
ordering = ['-ano', '-semestre']
constraints = [
models.UniqueConstraint(
fields=['ano', 'semestre'], name='unique_ano_semestre')
]
def __str__(self):
return f'{self.ano}/{self.semestre}'
def get_absolute_url(self):
return reverse("calendario:calendario-detail", kwargs={"slug": self.slug})
def get_delete_url(self):
return reverse("calendario:calendario-delete", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
"""Garante que exista apenas um is_active=True e define a slug"""
slug_str = f'{self.ano}-{self.semestre}'
unique_slugify(self, slug_str)
if self.is_active:
with transaction.atomic():
Calendario.objects.filter(
is_active=True).update(is_active=False)
return super(Calendario, self).save(*args, **kwargs)
else:
return super(Calendario, self).save(*args, **kwargs)
def get_fields(self):
""" Permite usar for no template para exibir todos os atributos do objeto"""
return [(field.verbose_name, field.value_to_string(self)) for field in Calendario._meta.fields]
class Curso(models.Model):
"""Cursos existente e ativos com matriz"""
nome = models.CharField(max_length=30)
abreviacao = models.CharField(
'Abreviação', max_length=3, help_text='Máximo 3 letras')
matriz = models.CharField(
max_length=4, help_text='Ano de aprovação de matriz do curso')
is_active = models.BooleanField('Ativo', default=True)
slug = models.SlugField(max_length=20)
class Meta():
ordering = ['-is_active', 'nome']
def save(self, *args, **kwargs):
slug_str = self.abreviacao + self.matriz
unique_slugify(self, slug_str)
self.abreviacao = self.abreviacao.upper()
super(Curso, self).save(*args, **kwargs)
def __str__(self):
return f'{self.abreviacao}/{self.matriz}'
def get_absolute_url(self):
return reverse("curso:curso-detail", kwargs={"slug": self.slug})
class Disciplina(models.Model):
"""Modelo disciplina"""
codigo = models.CharField(("Código"), max_length=12, primary_key=True, unique=True)
nome = models.CharField(("Nome da disciplina"), max_length=50)
curso = models.ManyToManyField('Curso')
def __str__(self):
return f'{self.codigo} - {self.nome}'
def get_absolute_url(self):
"""Url para o template com detalhes de uma disciplinas especifica"""
return reverse("curso:disciplina-detail", kwargs={"pk": self.codigo})
{{ form.instance.solicitante }} e {{ form.instance.solicitante.curso }}
Did what i wanted
Related
views.py
def product_display_detail(request, id, *args, **kwargs):
obj21 = Product.objects.filter(id=id).values()
obj3 =Stock.objects.filter(product_id=id).values()
obj1 =Product_type.objects.all()
context = {
"object21" : obj21,
"object1" : obj1,
"object3" : obj3
}
return render(request,"product_detail.html",context)
html file
{% for s in object3 %}
<div class="custom-control custom-radio custom-control-inline">
<input type="radio" class="custom-control-input" id="size-1" name="size">
<label class="custom-control-label" for="size-1">{{ s.size_id.size_name }}</label>
</div>
{% endfor %}
models.py
class Size(models.Model):
size_name = models.CharField(max_length=20)
class Colour(models.Model):
col_name = models.CharField(max_length=40)
class Product(models.Model):
product_name = models.CharField(max_length=120)
product_type = models.ForeignKey(Product_type, null=False, on_delete=models.PROTECT)
product_desc = models.TextField(max_length=500 , blank=False)
product_price = models.DecimalField(max_digits = 5,decimal_places = 2)
product_qty = models.IntegerField()
product_image = models.ImageField(null=False,blank=False,upload_to="images/")
def __str__(self):
return self.product_name
class Stock(models.Model):
product_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE)
size_id = models.ForeignKey(Size, null=True,on_delete=models.CASCADE)
colour_id = models.ForeignKey(Colour,null=True,on_delete=models.CASCADE)
qty = models.IntegerField()
product_details = models.TextField(max_length=500 , null=True , blank=True)
image = models.ImageField(null=False,blank=False,upload_to="images/")
i want size name from size table using stock object
I'm trying to make a list of employees that each day contains information ("today_note") if they are present at work or are sick.
I had no problem to do this in Flask, I simply rendered a template as below:
def employees_list():
all_employees = Employee.query.order_by(Employee.name).all()
today = date.today()
for employee in all_employees:
today_sick = db.session.query(SickLeave).filter(SickLeave.start_date <= today).filter(
SickLeave.end_date >= today).filter(SickLeave.person_id == employee.id).all()
if len(today_sick) != 0:
employee.today_note = "C"
else:
employee.today_note = "✓"
return render_template("employees_list.html", all_employees=all_employees)
and could access today_note for each employee in the template:
{% for employee in all_employees %}
{{ employee.today_note }}
{% endfor %}
Now I need to do the same in django. I can't figure out how to pass today_note to each instance of User model to be able to display it in the template.
class AllEmployeesList(ListView):
template_name = "users/all_employees.html"
model = User
context_object_name = 'employees'
def get_context_data(self, **kwargs):
context = super(AllEmployeesList, self).get_context_data(**kwargs)
all_employees = User.objects.all()
today = date.today()
for employee in all_employees:
today_sick = Sickleave.objects.filter(Q(start_date__lte=today)&Q(end_date__gte= today)&Q(employee__id=employee.id)).all()
if len(today_sick) != 0:
employee.today_note = "C"
else:
employee.today_note = "✓"
return context
I'm aware that here I completely miss reference to context
Edit: here are models
class Sickleave(models.Model):
TYPE_CHOICES = (
('C', 'Sickleave'),
('O', 'Other'),
)
employee = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, related_name='sickemployee', default=""
)
type_name = models.CharField(max_length=10, choices=TYPE_CHOICES, default='C')
start_date = models.DateField(null=True)
end_date = models.DateField(null=True)
class User(AbstractBaseUser):
username = models.CharField('Username', max_length=15, unique=True)
email = models.EmailField('Email', null=True, blank=True)
first_name = models.CharField('First name', max_length=30)
last_name = models.CharField('Last name', max_length=50)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
# (...)
USERNAME_FIELD = 'username'
objects = UserManager()
def has_perm(self, perm, obj=None):
return self.is_superuser
def has_module_perms(self, app_label):
return self.is_superuser
def get_full_name(self):
return self.first_name+" "+self.last_name
def __str__(self):
return self.first_name + " "+ self.last_name
I want to make a button to filter product by category.. Example Salad or Meat. Without Model ProductAtribuut im able to do it, but now i added the model, so im real confused how i can get the data of a Foreign Key inside a Foreign Key
ProductAtribuut -> Product(FK) -> Categorie(FK)
Models.py
class Categorie(models.Model):
naam = models.CharField(max_length=150,db_index=True)
slug = models.SlugField(unique=True)
class MPTTMeta:
order_insertion_by = ['naam']
class Meta:
ordering=('-naam',)
def __str__(self):
return self.naam
def get_absolute_url(self):
return reverse('JavaKitchen:product_by_categorie', args=[self.slug])
#property
def get_products(self):
return Product.objects.filter(categorie__naam=self.naam)
class Groente(models.Model):
groente = models.CharField(max_length=100)
def __str__(self):
return self.groente
class Vlees(models.Model):
vlees = models.CharField(max_length=100)
def __str__(self):
return self.vlees
class Product(models.Model):
slug = models.SlugField(unique=True, primary_key=True)
titel = models.CharField(max_length=200)
beschrijving = models.TextField(blank=True, null=True)
categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE)
class Meta:
ordering=('-titel',)
def __str__(self):
return self.titel
def get_title_uppercase(self):
return self.titel.upper()
def get_absolute_url(self):
return reverse('JavaKitchen:product_detail',args=[self.id,])
class ProductAtribuut(models.Model):
def groente():
return Groente.objects.filter(groente='geen').first()
def vlees():
return Vlees.objects.filter(vlees='geen').first()
product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=False)
groente = models.ForeignKey(Groente, on_delete=models.CASCADE, default=groente)
vlees = models.ForeignKey(Vlees, on_delete=models.CASCADE, default=vlees)
prijs = models.FloatField(default=0)
afbeelding = models.ImageField(blank=True, upload_to='gerechten/') #later upgrade..
zichtbaar = models.BooleanField(default=True)
def __str__(self):
return self.product.titel
def image_tag(self):
return mark_safe('<img src="/media/%s" width="80" height="auto" />' % (self.afbeelding))
image_tag.short_description = 'Image'
Views.py
def product_list(request,categorie_slug=None):
categorie = None
javakitchen = JavaKitchen.objects.get(id=1)
openings_tijden = Openings_tijden.objects.all()
categories = Categorie.objects.all().filter(zichtbaar=True)
product = Product.objects.all()
productatribuut = ProductAtribuut.objects.all().filter(zichtbaar=True)
if categorie_slug:
categorie = get_object_or_404(Categorie,slug=categorie_slug)
product = productatribuut.filter(product=product)
context = { 'categories':categories,
'categorie':categorie,
'product':product,
'form':form,
'javakitchen':javakitchen,
'openings_tijden': openings_tijden,
'productatribuut': productatribuut
}
return render(request, 'pages/index.html', context)
HTML template
<div class="categories">
<h1>{% if categorie %}{{ categorie.naam }}{% else %} ALLE GERECHTEN {% endif %}</h1>
<ol class="type">
<li><a class="page-scroll" href='{% url "JavaKitchen:product_list" %}#dinner'>Alles</a></li>
{% for c in categories %}
<li><a class="page-scroll" href="{{ c.get_absolute_url }}#dinner">{{ c.naam }}</a></li>
{% endfor %}
</ol>
<div class="clearfix"></div>
</div>
I used this before to get the category. when i didnt have class ProductAtribuut
if categorie_slug:
categorie = get_object_or_404(Categorie,slug=categorie_slug)
product = product.filter(categorie=categorie)
but now i dont know how i do get the category
ProductAtribuut -> Product(fk) -> Categorie(fk)
I have a form created in django and I want to put a constraint on it so the amount_sold must be > 0 or < coins_remaining , is this possible and if so how would I go about it?
Sale form HTML below
<div>
<form method="POST">
{% csrf_token %}
<fieldset class ="form-group">
<legend class="border-bottom mb-4">Enter Sale</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class ="btn btn-outline-info" type="submit">Enter</button>
</div>
</form>
</div>
Sale form model below
class SaleForm(forms.ModelForm):
amount_sold = forms.IntegerField()
total_price_sold = forms.DecimalField()
date_sold = forms.DateField(
widget=forms.TextInput(
attrs={'type': 'date'}
)
)
note = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Keep a Note?'}))
class Meta:
fields = ['date_sold', 'amount_sold', 'total_price_sold', 'note']
model = Sale
Sale model below
class Sale(models.Model):
amount_sold = models.IntegerField()
total_price_sold = models.DecimalField(max_digits=8, decimal_places=2)
date_sold = models.DateTimeField(default=timezone.now)
note = models.TextField(default="")
transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales")
amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False)
def __str__(self):
return str(self.pk)+','+str(self.amount_sold) + ', '+self.note
def save(self, *args, **kwargs):
self.amount_per_coin_sold = self.total_price_sold / self.amount_sold
super(Sale, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('sale-detail', kwargs={'pk': self.pk})
#property
def profit_loss(self):
return (self.amount_per_coin_sold - self.transaction.amount_per_coin) * self.amount_sold
#property
def profit_loss_percent(self):
value = ((self.total_price_sold - (self.transaction.amount_per_coin * self.amount_sold))/self.total_price_sold) * 100
return round(value, 1)
Transaction model below/ where I'm getting value coins_remaining from
class Transaction(models.Model):
currency = models.CharField(max_length=20)
amount = models.IntegerField()
total_price = models.DecimalField(max_digits=8, decimal_places=2)
date_purchased = models.DateTimeField()
note = models.TextField(default="")
owner = models.ForeignKey(User, on_delete=models.CASCADE)
amount_per_coin = models.DecimalField(max_digits=8, decimal_places=2, editable=False)
def save(self, *args, **kwargs):
self.amount_per_coin = self.total_price / self.amount
super(Transaction, self).save(*args, **kwargs)
def __str__(self):
return str(self.pk)+','+self.currency + ', '+str(self.amount)
def get_absolute_url(self):
return reverse('transaction-detail', kwargs={'pk': self.pk})
#property
def coins_remaining(self):
return self.amount - sum(self.sales.all().values_list('amount_sold', flat=True))
#property
def coin_value(self):
return get_currency_price(self.currency)
#property
def total_value(self):
value = self.coin_value * self.amount
return round(value, 2)
#property
def profit_loss(self):
value = float(self.total_value) - float(self.total_price)
return round(value, 2)
#property
def profit_loss_percent(self):
value = ((float(self.total_value) - float(self.total_price))/self.total_value)*100
return round(value, 1)
Using the last() method will return the last object in a queryset. If no ordering is provided then the default ordering will be done on the basis of id. I am assuming that you want amount_sold < last_transaction.coins_remaining
For validating a particular field in django form you need to write a custom method. The convention is- for any form field field1 name of the method will be clean_field1
In your case your form should look as follows to satisfy your desired validation -
class SaleForm(forms.ModelForm):
amount_sold = forms.IntegerField()
total_price_sold = forms.DecimalField()
date_sold = forms.DateField(widget=forms.TextInput(
attrs={'type': 'date'}))
note = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Keep a Note?'}))
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(SaleForm, self).__init__(*args, **kwargs)
class Meta:
fields = ['date_sold', 'amount_sold', 'total_price_sold', 'note']
model = Sale
def clean_amount_sold(self):
data = self.cleaned_data['amount_sold']
if data <= 0:
raise forms.ValidationError('Invalid Value')
transaction = Transaction.objects.filter(owner=self.user).last()
if data >= transaction.coins_remaining:
raise forms.ValidationError('Invalid Value')
return data
In your view instantiate the form as follows -
if request.method == 'POST':
form = SaleForm(request.POST, user=request.user)
else:
form = SaleForm(user=request.user)
I'm trying to display a manytomany field in my template, but all I get is a blank...I'm displaying it as below:
{% for vehicle in vehicle.features.features %}
<li>vehicle.features</li>
{% endfor %}
My model is as follows:
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
feature_sets = models.ManyToManyField(FeatureSet, blank=True)
features = models.ManyToManyField(Feature, blank=True)
def __unicode__(self):
return self.stock_number
The classes I'm linking to are:
class Feature(models.Model):
name = models.CharField(max_length=32)
type = models.ForeignKey(FeatureType)
def __unicode__(self):
return self.name
class FeatureSet(models.Model):
name = models.CharField(max_length=12)
features = models.ManyToManyField(Feature)
def __unicode__(self):
return self.name
Use this:
{% for feature in vehicle.features.all %}
<li>{{ feature }}</li>
{% endfor %}