my models:
class Aula(models.Model):
nome_aula = models.CharField(max_length=255)
descricao_aula = models.TextField()
...
def __str__(self):
return self.nome_aula
class Modulos(models.Model):
numero_modulo = models.CharField(default="Módulo 1",max_length=400)
aulas = models.ManyToManyField(Aula)
def __str__(self):
return self.numero_modulo
my views:
def aulasdomodulo(request, id):
mod = get_object_or_404(Modulos, pk=id)
aulas = mod.aulas.all()
return render(request, 'wtic/aulasdomodulo.html', {'aulas':aulas, 'mod':mod})
def conteudodaaula(request, id):
mod2 = get_object_or_404(Modulos, pk=id)
aula = mod2.aulas.all()
...
return render(request,'wtic/conteudo_aula.html', {'aula':aula})
my html where it shows the objects assigned that module accesses them
{% for aula in aulas %}
{{aula.nome_aula}}
Acessar
{% endfor %}
but when I try to access classes I get it
how can i access these objects one per page?
Related
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 am new to Django, trying to save my form data in the database.created two model classes PatientInfo and patientHist, which is inheriting PatientInfo class. I do not understand where I am going wrong.
'.I am not getting any error,my tables are created in database, but no data is saving when i click on submit button'
models.py
from django.db import models
# Create your models here.
class PatientInfo(models.Model):
sex = (
('M', 'Male'),
('F', 'Female')
)
first_name = models.CharField(max_length=35)
middle_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length= 30)
sex = models.CharField(max_length=1,choices=sex)
date_of_birth = models.DateField()
height = models.FloatField()
weight = models.FloatField()
phone_no =models.CharField(max_length=15)
class PatientHist(PatientInfo):
Yes_No = (
(True, 'Yes'),
(False, 'No'),
)
Veg_nonveg =(
(True,'Veg'),
(False,'Non-Veg'),
)
diabetes = models.BooleanField(default=False,choices=Yes_No)
diabetes_long = models.CharField(max_length=20)
hypertension = models.BooleanField(default=False,choices=Yes_No)
hypertension_long = models.CharField(max_length=20)
obesity = models.BooleanField(default=False,choices=Yes_No)
obesity_long = models.CharField(max_length=20)
pcod = models.BooleanField(default=False,choices=Yes_No)
pcod_long= models.CharField(max_length=20)
thyroid = models.BooleanField(default=False,choices=Yes_No)
thyroid_long = models.CharField(max_length=20)
heartdiease = models.BooleanField(default=False,choices=Yes_No)
heartdiease_long = models.CharField(max_length=20)
liverdisease = models.BooleanField(default=False,choices=Yes_No)
liverdisease_long = models.CharField(max_length=20)
kidney = models.BooleanField(default=False,choices=Yes_No)
kidney_long = models.CharField(max_length=20)
familyhistory = models.BooleanField(default=False,choices=Yes_No)
currentmed = models.CharField(max_length=20)
foodhabit= models.BooleanField(default=False,choices= Veg_nonveg)
hba1c = models.FloatField(max_length=20)
fasting = models.FloatField(max_length=20)
pp = models.FloatField(max_length=20)
forms.py
from django import forms from .models import *
class Patient_form(forms.ModelForm):
class Meta:
model = PatientInfo
fields = "__all__"
class PatientHistory_form(forms.ModelForm):
class Meta:
model = PatientHist
widgets = {
'diabetes': forms.RadioSelect,
'hypertension': forms.RadioSelect,
'obesity': forms.RadioSelect,
'pcod': forms.RadioSelect,
'thyroid': forms.RadioSelect,
'heartdiease': forms.RadioSelect,
'liverdisease': forms.RadioSelect,
'kidney':forms.RadioSelect,
'familyhistory' : forms.RadioSelect,
'currentmed':forms.RadioSelect,
'foodhabit':forms.RadioSelect,
}
fields = "__all__"
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import Patient_form,PatientHistory_form
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views import generic
# Create your views here.
#def home(request):
#return render(request,'home/base.html',{})
#def patient_view(request):
#context = {}
# context['form'] = Patient()
#return render(request, 'home/Patient_info.html', context)
#def patienthistory_view(request):
# context = {}
# context['history'] = PatientHistory_form
# return render(request, 'home/Patient_info.html', context)
def patienthistory_view(request):
if request.method == 'POST':
patientmedinfo = PatientHistory_form(request.POST)
if patientmedinfo.is_valid():
myid = patientmedinfo.save()
myid.save()
return HttpResponse( print(patientmedinfo.errors))
else:
patientmedinfo = PatientHistory_form()
return render(request, 'home/Patient_info.html', {'form': patientmedinfo})
patient_Info.html
{% extends "home/base.html" %}
{% block title %}Patient Information{% endblock title %}
{% block content %}
<form enctype="multipart/form-data" action=" " method="post" >
{% csrf_token %} <table align="center" border="0">
<tr>
<td><h4 align="center">Patient Information</h4></td>
<td>{{form}}</td>
<td><input align="center" type="submit" value=" Next--> "></td>
</tr> </table> </form>
{% endblock content %}
Hi finally I found your error.
you have a field currentmed which is CharField.
But in forms.py you assigned forms.RadioSelect widget to it. So it throws an error for required field.
So just remove 'currentmed':forms.RadioSelect, from widget dict of PatientHistory_form.
That's it.
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)
In main.html:
{% for item in count_list %}
{{ item }}<br>
{% endfor %}
In views.py:
def four(request):
count_list = PDivContent.objects.filter(divv = '5')
return render(request, 'main.html', {'count_list': count_list})
The problem is that the count_list list, contains data repeated for twice like this:
طلا و جواهرات
بدلیجات و نقره سرا
اجناس کادویی
اسباب بازی فروشی
صنایع دستی
فروش و تعمیر ساعت
طلا و جواهرات
بدلیجات و نقره سرا
صنایع دستی
اجناس کادویی
اسباب بازی فروشی
How can I solve it?
models.py:
class PDivContent(models.Model):
chest = models.IntegerField()
divv = models.IntegerField()
txt = models.TextField()
img = models.TextField()
symbol = models.TextField()
def __str__(self):
return self.txt
class Meta:
managed = False
db_table = 'p_div_content'
And in the db, data are not repeated for twice.
How about trying .distinct() in your query?
def four(request):
count_list = PDivContent.objects.filter(divv = '5').distinct()
return render(request, 'main.html', {'count_list': count_list})
I have these 4 models . There is a section where the user would be able to view all incomplete tasks. How would I go about displaying these using the ListView and DetailView ?
In all the examples in the django docs they always give an example just with one model. Can this be done using the CBV or are there alternatives?
Models
class task_a(models.Model):
created_by = models.ForeignKey('auth.User')
task_complete = models.BooleanField(default=0)
q1 = models.CharField(max_length=60)
q2 = models.DateField()
q3 = models.TimeField()
q4 = models.TextField()
class Meta:
verbose_name_plural = "task_a"
def get_absolute_url(self):
return reverse('task_a')
def __unicode__(self):
return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)
class task_b(models.Model):
created_by = models.ForeignKey('auth.User')
task_complete = models.BooleanField(default=0)
q1 = models.CharField(max_length=60)
q2 = models.DateField()
q3 = models.TimeField()
q4 = models.TextField()
class Meta:
verbose_name_plural = "task_b"
def get_absolute_url(self):
return reverse('task_b')
def __unicode__(self):
return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)
class task_c(models.Model):
created_by = models.ForeignKey('auth.User')
task_complete = models.BooleanField(default=0)
q1 = models.CharField(max_length=60)
q2 = models.DateField()
q3 = models.TimeField()
q4 = models.TextField()
class Meta:
verbose_name_plural = "task_c"
def get_absolute_url(self):
return reverse('task_c')
def __unicode__(self):
return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)
class task_d(models.Model):
created_by = models.ForeignKey('auth.User')
task_complete = models.BooleanField(default=0)
q1 = models.CharField(max_length=60)
q2 = models.DateField()
q3 = models.TimeField()
q4 = models.TextField()
class Meta:
verbose_name_plural = "task_d"
def get_absolute_url(self):
return reverse('task_d')
def __unicode__(self):
return u'%s %s %s %s %s' % (self.q1, self.q2, self.q3, self.q4,self.q5)
You can add extra context variables by overriding the get_context_data() function in your class:
class MultipleModelsListView(ListView):
model = TaskA # Class names should use capitalized CamelCase
def get_context_data(self, **kwargs):
kwargs = super(MultipleModelListView, self).get_context_data(**kwargs)
kwargs.update({
'taskb_list': TaskB.objects.all(), # or with some filter applied
'taskc_list': TaskC.objects.all(),
'taskd_list': TaskD.objects.all(),
})
return kwargs
This will give you, additional to the default context supplied by a ListView, the context variables taskb_list, taskc_list and taskd_list to iterate over.
You can iterate over these in your template like this:
{% for task in object_list %} {# default supplied by ListView #}
{{ task.whatever }}
{% endfor %}
{% for task in taskb_list %}
{{ task.whatever }}
{% endfor %}
{# etc. #}