When I enter my user profile page, I want it to see the total number of orders until today. i tried aggregate and annonate but it's not work. I hope so i use filter method but i don't know how to do it.
Orders count = adet in model
I added ""if siparis.bayi_id == user.id"" so that the user entering can take action on his orders.
Temp Html
{% for siparis in siparis %}
{% if siparis.bayi_id == user.id %}
<strong>{{ a }}</strong><br><small>Siparişler Toplamı</small>
{% endif %}
{% endfor %}
Model Siparis means order
class Siparis(models.Model):
bayi = models.ForeignKey('auth.User', verbose_name='bayi', on_delete=models.CASCADE, related_name='bayi',limit_choices_to={'groups__name': "BayiGrubu"})
urun = models.ForeignKey(Urun, on_delete=models.CASCADE)
adet = models.IntegerField()
tarih = models.DateTimeField()
status = models.BooleanField()
#property
def miktar(self):
return (self.adet * self.urun.fiyat)
#property
def fiyat(self):
return self.urun.fiyat
class Meta:
verbose_name = 'Bayi Sipariş'
verbose_name_plural = 'Bayi Siparişleri'
views
def bayi_bayidetay(request):
siparis = Siparis.objects.all()
urunler = Urun.objects.all()
bayiler = bayi_bilgi.objects.all()
a = Siparis.objects.aggregate(Sum("adet"))
return render(request,'bayi/bayi_detay.html',{'bayiler':bayiler,'siparis':siparis,'urunler':urunler, 'a': a})
Thank you
You can try add filter after a, like this:
a = Siparis.objects.filter(bayi=request.user).aggregate(Sum("adet"))
Related
My models:
class customer(models.Model):
cstid = models.AutoField(primary_key=True, unique=True)
insurance_number = models.CharField(max_length=100, blank=True, null=True)
name = models.CharField(max_length=35)
ageyrs = models.IntegerField(blank=True)
class Admission(models.Model):
id = models.AutoField(primary_key=True, unique=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
customer = models.ForeignKey(customer, on_delete=models.CASCADE)
diagnosis = models.CharField(max_length=2000, default='', blank=True)
date_admission = models.DateTimeField(default=timezone.now)
ward = models.ForeignKey(Ward, on_delete=models.CASCADE)
bed = models.ForeignKey(Bed, on_delete=models.CASCADE)
discharged = models.BooleanField(default=False)
ip_number = models.IntegerField(blank=True)
ip_prefix = models.CharField(max_length=20, default='', blank=True)
My objective: Set a variable to a query filter, adding a property, 'is_admitted' to the queryset, so that I can pass this query set to the template and use the property while displaying data.
Code:
def is_admitted(cust):
admission = Admission.objects.filter(customer=cust, discharged=False)
admission_results = len(admission)
if admission_results > 0:
return True
return False
my_q = or_q_if_truthfull(
cstid=HospitalID,
name__lower__contains=name.lower() if name else None,
ageyrs=ageyrs if ageyrs.isdigit() else None,
agemnths=agemnths if agemnths.isdigit() else None,
mobile__contains=mobile if mobile else None,
alternate__contains=alternate if alternate else None,
email__lower__contains=email.lower() if email else None,
address__lower__contains=address.lower() if address else None,
city__lower__contains=city.lower() if city else None
)
ORSearchResult = customer.objects.filter(my_q, linkedclinic=clinicobj)
cust_set = []
cust_admission_status = []
for cust in ORSearchResult:
cust_set.append(cust)
cust_admission_status.append(is_admitted(cust))
print(f"Customer name: {cust.name} Admission status: {is_admitted(cust)}")
cust_templ_set = zip(cust_set, cust_admission_status)
And in template, I will do:
{% for cust, status in cust_templ_set %}
{{ cust.name }} {{ status }}
{% endfor %}
I want to understand how I can convert my above code by generating an aggregate over the queryset, so that I can use a property of the query, and change the template code to the following, and avoid the loop in the view, and the zip. So that the template code becomes:
{% for cust in customers %}
{{ cust.name }} {{ cust.is_admitted }}
{% endfor %}
I am not sure whether I am making complete sense, and can explain further.
I'm not sure I understood you right, perhaps you might want this:
cust = customer.objects.filter(my_q, linkedclinic=clinicobj)
is_admitted_sub_q = Admission.objects.filter(customer=OuterRef('pk'), discharged=False)
cust_templ_set = cust.annotate(is_admitted=Exists(is_admitted_sub_q), )
this will return a list of customers with additional field is_admitted which will be True if there exists at least one linked (to this customer) record in Admission.
OuterRef, Exists
One option could be to use conditional-expressions together with annotate(). It could look like this:
from django.db import models
qs = Customer.objects.filter(...) # your filter conditions go here
# now add a field to the resulting queryset
qs = qs.annotate(
active_admissions=models.Count(
models.Case(
models.When(admission__discharged=False, then=1),
output_field=models.IntegerField())))
Now each object in the queryset will have an additional attribute called active_admissions which will contain the number of active admissions.
This could be used in the template like this:
{% for cust in qs %}
{{ cust.name }} {{ cust.active_admissions }}
{% endfor %}
Maybe you need to modify the subquery to fit your specific needs. Does that help?
I'm new in django.I want to retrieve all the records from related models and display the dynamic data in templates. I tried by using raw sql also but i could not display dynamic data templates.
models.py:
class NewRegistration(models.Model):
houseowner_name_en = models.CharField(max_length=30)
ward_no = models.ForeignKey(system_settings.models.Wardno)
contactno = models.CharField(max_length=30)
construction_type = models.ForeignKey(system_settings.models.ConstructionType)
taxpayer_id = models.CharField(max_length=30, blank=True, null=True)
cen = models.IntegerField()
is_forwarded = models.BooleanField(default=False)
class Application(models.Model):
registration_date = models.CharField(max_length=15)
building_use = models.ForeignKey(to=system_settings.models.BuildingUse)
building_category = models.CharField(max_length=30)
building_structure_category = models.ForeignKey(to=system_settings.models.BuildingStructureCategory)
building_storey = models.IntegerField(blank=True, null=True, default=0)
reg = models.ForeignKey(NewRegistration)
class Landowner(models.Model):
landowner_type = models.CharField(max_length=30)
lo_salutation = models.CharField(max_length=30)
lo_name_np = models.CharField(max_length=30)
lo_citizenship_issue_date = models.CharField(max_length=30)
reg = models.ForeignKey(NewRegistration)
views.py:
def export(request):
all_objects = NewRegistrationModel.objects.all()
# houseowner= all_objects.houseownerinfo_set.all()
app_all=Application.objects.all()
landinfo=Landinfo.objects.all()
return render(request, 'exports.html', {'all_objects': all_objects})
I did it like this.
views.py
def export(request):
all_objects = NewRegistration.objects.all()
return render(request, 'exports.html', {'all_objects': all_objects})
exports.html
# in template when displaying
{% for registration in all_objects %}
{{ registration.fiscalyear }}
{% for owner in registration.landowner_set.all %}
{{owner.landowner_type}}
{{owner.lo_wardno}}
{% endfor %}
{% endfor %}
you can use generic.ListView in your views.py file like that:
class Export(generic.ListView):
model = NewRegistration
template_name = "your_template_name.html"
def get_queryset(self):
return NewRegistration.objects.all()
def get_context_data(self, **kwargs):
context = super(Export, self).get_context_data(**kwargs)
context['app_all'] = Application.objects.all()
context['landinfo'] = Landingo.objects.all()
return context
you can accees the datas in your template like that {{ app_all }} or {{ landinfo }}.
The problem is, when i'm trying to compare two properties which are the same when we check them in shell, but the condition is not complete and i have no idea why. I mean this condition: {% if c.author = member.name %}
views:
cvs = Cv.objects.all()
cv = Cv.objects.filter(author = request.user)
per = Person.objects.all()
gr = Group.objects.filter(members__name=request.user)
for c in cvs:
print c.author
mem = Membership.objects.all()
form = GroupForm()
context = {
'gr': gr,
'per':per,
'mem':mem,
'form': form,
'cvs':cvs,
'cv':cv,
}
return render(request, 'groups.html', context)
models.py:
class Cv(models.Model):
author = models.ForeignKey('auth.User')
name = models.CharField(max_length=25, null = True)
surname = models.CharField(max_length=25, null = True)
address = models.CharField(max_length=100, blank=True)
telephone = models.IntegerField()
birth_date = models.DateField(blank=True, null=True)
email = models.EmailField(max_length=50, null=True)
skills = models.TextField(null=True)
specialization = models.CharField(max_length=30, blank=True, null=True)
interests = models.TextField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True)
#property
def age(self):
return int((datetime.datetime.now().date() - self.birth_date).days / 365.25 )
def zapisz(self):
self.save()
def __str__(self):
return self.surname
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self): # __unicode__ on Python 2
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self): # __unicode__ on Python 2
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person)
leader = models.BooleanField(default=False)
group = models.ForeignKey(Group)
groups.html:
{% block profile %}
{% for g in gr %}
<div class="jumbotron">
<p><b>GROUP:</b> {{g.name}}</p>
{% for c in cvs %}
{% for member in g.members.all %}
{% if c.author = member.name %}
{{member.name}}
{% endif %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
{% endblock %}
Thanks for answer!
Firstly, please give your variables descriptive names. "c" and "gr" are impossible to understand.
Secondly, you are not comparing the right things at all. c.author is an instance of User; member is an instance of Person and member.name is a string. Comparing a User instance with a string will always fail.
Finally, this whole thing is horribly inefficient - and probably totally unnecessary. Three nested for loops means a huge number of iterations. If you could explain what the output needs to be, then we can almost certainly come up with a better way of doing it.
To test for equality in a Django template you need to use the equality operator == as follows:
{% if c.author == member.name %}
{{member.name}}
{% endif %}
You should compare c.name with member.name or c.author.first_name with member.name. So both of the variable to be strings.
I am working on a product app on Python 2.7 / Django 1.7.
I have a model for product namely 'product_profile' and I want to allow my customer (end user) to ask any thing regarding specific products using a form.
However I am unable to allow user to automatically select the product (foreign key) and the customer has to select from a drop-down which quite irrational. I have also assigned the foreign key in url-variable.
here is my code:
MODEL.PY
class ProductProfile(models.Model):
category = models.ForeignKey(Category)
brand = models.ForeignKey(Brand)
product_name = models.CharField(max_length=128)
model_name = models.CharField(max_length=128)
generation = models.CharField(max_length=128)
processor = models.CharField(max_length=128)
ram = models.DecimalField(max_digits=2, decimal_places=0)
hdd = models.DecimalField(max_digits=6, decimal_places=2)
optical_drive = models.CharField(max_length=128)
display = models.CharField(max_length=128)
card_reader = models.CharField(max_length=128)
blue_tooth = models.CharField(max_length=128)
web_cam = models.CharField(max_length=128)
warranty = models.CharField(max_length=128)
price = models.DecimalField(max_digits=9, decimal_places=2)
condition = models.TextField()
product_image = models.ImageField(upload_to=update_Product_image_filename)
post_date = models.DateTimeField(db_index=True, auto_now_add=True)
# Override th __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.product_name
class Customer_ps_contact(models.Model):
name = models.CharField(max_length=128)
email = models.EmailField(max_length=75)
subject = models.CharField(max_length=128 )
product = models.ForeignKey(ProductProfile)
message = models.TextField()
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format:
'+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], blank=True, max_length=15) # validators should be a
list
def __unicode__(self):
return self.name
FORM.PY
class Customer_ps_contactForm(forms.ModelForm):
class Meta:
model = Customer_ps_contact
product = forms.ModelChoiceField(queryset=ProductProfile.objects.all(),
widget=forms.HiddenInput())
fields = ('name','email', 'product','subject','message', 'phone_number')
VIEWS.PY
def product_inquiry(request, product_id):
product = ProductProfile.objects.get(pk=product_id)
if request.method == 'POST':
#form = Customer_ps_contactForm(request.POST, initial = {'product': product})
#form = Customer_ps_contactForm(initial = {'product': product.id})
form = Customer_ps_contactForm(request.POST)
if form.is_valid():
form_data_dict = form.cleaned_data
print form_data_dict['product']
mail_customer_enquriy(form_data_dict) # Function to send email to admin
thank_u_customer(form_data_dict) # Function to send email to customers
form = form.save(commit=False)
form.product = product
form.save()
return home(request)
else:
print ("form is not valid")
print (form.errors)
else:
form = Customer_ps_contactForm()
context_dict = {'form':form, 'product': product}
return render(request, 'product/product_inquiry2.html',context_dict)
URL Patterns
urlpatterns = patterns('',
url(r'^inquiry/(?P<product_id>\d+)/$', views.product_inquiry, name='price'), # Only relevent url given
)
Template : product_inquiry2.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block body_block %}
{% block title %}Product Inquiry{% endblock %}
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h2 style="font-weight:bold">Enquiry regarding '{{product.product_name}}'</h2>
<hr>
<form id="contact_form" method="post" action=""/>
{% csrf_token %}
{{ form | crispy }}
<input class="btn btn-primary pull-right " type="submit" name="submit" value="Submit the Message" />
</form>
</div>
</div>
{% endblock %}
What should I do?
You know what the product is from the id in the url, so there's no need to include it in your form.
To check that the product exists in the database, you can use the get_object_or_404 shortcut.
def product_inquiry(request, product_id):
product = get_object_or_404(ProductProfile, pk=product_id)
Then leave out 'product' from your list of fields, and remove the ModelChoiceField with hidden input widget.
class Customer_ps_contactForm(forms.ModelForm):
class Meta:
model = Customer_ps_contact
fields = ('name','email','subject','message','phone_number')
You are already setting the product when you save it, but it would be clearer to use the variable name instance to make it clearer what's going on. If you change your mail_customer_enquriy and thank_u_customer methods to use the instance instead of cleaned_data, then you won't have to do anything with form.cleaned_data.
if form.is_valid():
instance = form.save(commit=False)
instance.product = product
instance.save()
mail_customer_enquriy(instance) # Function to send email to admin
thank_u_customer(instance) # Function to send email to customers
return home(request)
How can I display country, and city of an UserType1 object in template?
class UserType1(models.Model):
user=models.OneToOneField(User,parent_link=True,primary_key=True)
country = models.CharField(max_length=50)
city = models.CharField(max_length=50)
def __str__(self):
return str(self.user)
def get_country(self):
return self.country
def get_city(self):
return self.city
I have the below in views.py
def profile(request,userid):
basic_info = User.objects.get(pk=int(userid))
profile = UserType1.objects.filter(user=int(userid))
template_name = 'users/profile.html'
return render(request, template_name, {'userid':userid,'basic_info':basic_info, 'profile':profile})
and the following in template
{% if profile %}
{{ profile.get_city }}
{{ profile.city }}
{% endif %}
Neither worked. Thanks!
It looks like you are accessing properties on a queryset, rather than a model instance, as you haven't called get on UserType1.
Try:
profile = UserType1.objects.get(user=int(userid))
As an aside though, a small change would simplify your code a little:
user = models.OneToOneField(User, parent_link=True, primary_key=True, related_name='profile')
...
basic_info = User.objects.get(pk=int(userid))
profile = basic_info.profile