#models.py
class Orders(models.Model):
orderid = models.IntegerField(db_column='orderID', primary_key=True)
createdate = models.DateField(db_column='createDate', blank=True, null=True)
pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True)
returndate = models.DateField(db_column='returnDate', blank=True, null=True)
pickupstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='pickupStore', blank=True, null=True,related_name = 'pickupstore')
returnstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='returnStore', blank=True, null=True,related_name = 'returnstore')
rentedvehicle = models.ForeignKey('Vehicles', models.DO_NOTHING, db_column='rentedVehicle', blank=True, null=True)
customer = models.ForeignKey(Customer, models.DO_NOTHING, db_column='customer', blank=True, null=True)
class Vehicles(models.Model):
vehicleid = models.IntegerField(db_column='vehicleID', primary_key=True)
make = models.CharField(max_length=45, blank=True, null=True)
model = models.CharField(max_length=45, blank=True, null=True)
series = models.CharField(max_length=45, blank=True, null=True)
#views.py
def topcar(request):
topCar = Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).annotate(num_car =Count('orders')).order_by('-num_car')[:20]
return render(request, 'web/topcar.html',{'topCar':topCar, 'state':request.POST['state'])
#topcar.html
{% for car in topCar %}
<tr>
<td>{{car.make}} {{car.model}} {{car.series}} {{car.year}}</td>
<td>{{car.seatcapacity}}</td>
<td>{{the latest car return store}}</td>
</tr>
{% endfor %}
In views.py, topCar variable is the list of top 20 vehicles (in Vehicles model) that have high orders in Orders model.The field rentedvehicle in Orders model is foreign key refers to Vehicles model.
I want to get the latest returnstore (a field in Orders model) for each car in topCar variable. I want it to be displayed in {{the latest car return store}} in topCar.html
How should I do that?
I find out that I can do this :
Orders.objects.filter(rentedvehicle = car.vehicleid).latest('returndate').returnstore
to get the latest returnstore for a vehicleid. However, I don't know how to use that for getting the result that I want.
You can only use simple lookup logic in Django templates, so you wouldn't be able to do the latest('returndate') filtering there.
Instead, you could add a method to your Vehicle model to get the latest order:
class Vehicles(models.Model):
vehicleid = models.IntegerField(db_column='vehicleID', primary_key=True)
make = models.CharField(max_length=45, blank=True, null=True)
model = models.CharField(max_length=45, blank=True, null=True)
series = models.CharField(max_length=45, blank=True, null=True)
def latest_order(self):
return self.orders_set.latest('returndate')
Then you should be able to modify your template to:
{% for car in topCar %}
<tr>
<td>{{car.make}} {{car.model}} {{car.series}} {{car.year}}</td>
<td>{{car.seatcapacity}}</td>
<td>{{car.latest_order.returnstore}}</td>
</tr>
{% endfor %}
Related
How should I query when I use pk with annotate?
I need to redirect to user profile when a guest click in link.
Models
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.content1)
class Profil(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
age = models.PositiveIntegerField(blank=True, null=True)
country = models.CharField(max_length=50)
user = models.OneToOneField(Account, on_delete=models.CASCADE)
avatar = models.ImageField(default="avatar.png", upload_to="images",validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
slug = models.SlugField(blank=True)
gender = models.CharField(max_length=6, choices=GENDER)
friends = models.ManyToManyField(Account, blank=True, related_name="Friends")
social_facebook = models.CharField(max_length=250, null=True, blank=True)
social_instagram = models.CharField(max_length=250, null=True, blank=True)
social_twitter = models.CharField(max_length=250, null=True, blank=True)
social_youtube = models.CharField(max_length=250, null=True, blank=True)
social_linkedin = models.CharField(max_length=250, null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
Views
if tag == None:
my_tag = Posty.objects.annotate(
latest_comment = Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('content1').order_by('-date_posted')[:1]),
my_author=Subquery(CommentPost.objects.filter(post=OuterRef('id')).values('user__user__username').order_by('-date_posted')[:1]),
)
I got a correct username, but I can't get a correct redirect:
Unfortunately, you need to annotate the CommentPost's id information as well with the queryset just like you added the username information. That will end up being a lot of subquery added to the original queryset. Rather I would suggest to use prefetch related to preload the CommentPost information with the original queryset (for reducing DB hits) and directly access that information from template. For example:
# view
my_tag = Posty.objects.prefetch_related('commentpost_set')
# template
{% for post in my_tag %}
<span> {{post.commentpost_set.last.content1}}<span>
<span> {{post.commentpost_set.last.user.username}}<span>
{% endfor %}
Also, last is a queryset function which returns the last object of a given queryset. I can access the CommentPost queryset from a Posty object by reverse querying.
I have the following code at views.py to sort TvShows by there latest released episode (release_date) within 90 days:
def tv_show_by_set_just_released(request):
latest_episodes = TvShows.objects.filter(episode_show_relation__release_date__gte=now() - datetime.timedelta(days=90))
...
For each element found, I now also want to display a cover. But the cover is located at a different table and I don't really know how to pull it out probably in this query context. In the end I want to display the very first TvShowSeasons.cover for each element of my query from above. Is it somehow possible to marry these two elements, latest_episodes and TvShowSeasons.cover to display them properly at a template?
Please also see models.py
class TvShows(models.Model):
objects = RandomManager()
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.TextField(verbose_name=_("Title"), blank=False, null=True, editable=False, max_length=255)
genre_relation = models.ManyToManyField(through='GenreTvShow', to='Genre')
date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added"))
class TvShowSeasons(models.Model):
objects = RandomManager()
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
show = models.ForeignKey(TvShows, on_delete=models.CASCADE, related_name='season_show_relation')
season_number = models.IntegerField(verbose_name=_("Season Number"), blank=True, null=True, editable=False)
cover = models.ImageField(verbose_name=_("Cover"), blank=True, null=True, upload_to=get_file_path_images)
cover_tn = models.ImageField(verbose_name=_("Cover Thumbnail"), blank=True, null=True, upload_to=get_file_path_images)
total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True)
rating = models.CharField(verbose_name=_("Rating"), blank=True, null=True, editable=False, max_length=255)
copyright = models.TextField(verbose_name=_("Copyright"), blank=True, null=True, editable=False, max_length=255)
date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added"))
Thanks in advance
That is what related_name argument in ForeignKey is meant to be. Assuming you return latest_episodes as context, here is how you can access cover for each episode in templates:
{% for episode in latest_episodes %}
<p>Episode name: {{ episode.title }}</p>
<img src="{{ episode.season_show_relation.first.cover.url }}">
{% endfor %}
I need to display some product's supplier, next to {{product.description}} but I can't get it to show on my table.
models.py
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
sku = models.IntegerField(null=True)
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(null=True, max_length=99, unique=True)
image = models.ImageField(null=True, blank=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.description
views.py
def products(request):
products = Product.objects.all()
suppliers = Supplier.objects.all()
context = {'products': products,
'suppliers': suppliers}
return render(request, 'crmapp/products.html', context)
products.html
<tr>
{% for product in products %}
<td>{{product.id}}</td>
<td><h6><strong>{{product.description}}</strong></h6></td>
<td >{{products.supplier}}</td>
<td>£{{product.costprice |floatformat:2}}</td>
<td>£{{product.retailprice |floatformat:2}}</td>
<td>{{product.barcode}}</td>
</tr>
{% endfor %}
Spelling mistake, I think.
<td >{{products.supplier}}</td>
Must be:
<td >{{product.supplier}}</td>
Notice I've removed the s in products.
Also, you don't need this in your views.py:
suppliers = Supplier.objects.all()
{{product.supplier}} will trigger a query to the db. To avoid that, use prefetch_related.
products = Product.objects.all().prefetch_related('supplier')
Note that this is optional. It will just improve efficency, but merely fixing the spelling mistake answers your question.
I'm trying to do a simple loop but in Django I can't get it to output properly.
It's printing everything like one big string.
In python it loops through fine and it is a valid list, created an inputted into the postgres database.
This is my function in my views.py
def pages(request, id):
obj = rtves_programas.objects.get(id=id)
context = {'title': obj.title,
'show_date': obj.show_date,
'script' : obj.script,
'script_eng': obj.script_eng,
'description': obj.description,
'description_eng': obj.description_eng,
'show_id':obj.show_id,
'url': obj.url,
}
return render(request, 'rtves/pages.html', context)
this element is a list → 'script_eng': obj.script_eng, and I want to printout the elements of the list.
this is my code on the template.
{% if script %}
{% for sentence in script %}
{{ sentence }}
{% endfor %}
{% else %}
<p>Nothing here</p>
{% endif %}
But it's printing out everything in the list not the elements of the list, it looks like this
if I just add this to the template it {{ script }}
Similar to the loop but without the space
Here is the model definition
class rtves_programas(models.Model):
title = models.CharField(unique=True, max_length=250)
script = ArrayField(models.CharField(max_length=8000))
created_on = models.DateTimeField()
show_date = models.CharField(max_length=300, blank=True, null=True)
script_eng = models.CharField(max_length=8000, blank=True, null=True)
description = models.CharField(max_length=2000, blank=True, null=True)
description_eng = models.CharField(max_length=2000, blank=True, null=True)
url = models.CharField(max_length=200, blank=True, null=True)
show_id = models.CharField(max_length=200, blank=True, null=True)
Ok after looking at the models I decided to recreate them, I inheritable the tables from a legacy database and
class programas(models.Model):
title = models.CharField(unique=True, max_length=250)
script = ArrayField(models.CharField(max_length=8000, blank=True))
created_on = models.DateTimeField()
show_date = models.CharField(max_length=300, blank=True, null=True)
script_eng = ArrayField(models.CharField(max_length=8000, blank=True))
description = models.CharField(max_length=2000, blank=True, null=True)
description_eng = models.CharField(max_length=2000, blank=True, null=True)
url = models.CharField(max_length=200, blank=True, null=True)
show_id = models.IntegerField(primary_key=True)
id = models.IntegerField(default=1)
Then the models won't update in the postgres database so I cleared migrations, so When the migrations didn't work
I ran this code
SELECT * FROM "public"."django_migrations";
DELETE FROM "public"."django_migrations" WHERE "id"=replace with your Id;
So now I can loop through but I still have to work on a few other things.
All my CreateViews are working fine, but this one is not (although this is UpdateView). After checking, trying to identify differences, I find none. Must be something I'm still missing.
Template:
<form method="POST">{% csrf_token %}
{{ form.non_field_errors }}
{{ form.errors }}
{{ form.make }}
{{ form.make.errors }}
{{ form.model}}
{{ form.model.errors }}
{{ form.year}}
{{ form.year.errors }}
<button type="submit"> Save</button>
Close
</form>
Url paterns in URLS.py:
url(r'^update/(?P<pk>\w+)/$',UpdateView.as_view(
model=Vehicles,
form_class=VehiclesForm,
success_url="/main/",
template_name="vehicle_detail.html")),
Model:
from django.db import models
class Vehicles(models.Model):
stock = models.CharField(max_length=10, blank=False, db_index=True)
vin = models.CharField(max_length=17, blank=False, db_index=True)
vinlast8 = models.CharField(max_length=8, blank=False, db_index=True)
make = models.CharField(max_length=15, blank=False)
model = models.CharField(max_length=15, blank=False)
year = models.CharField(max_length=4, blank=False)
deal = models.IntegerField(blank=False, db_index=True, null=True)
sold = models.DateField(blank=True, null=True, db_index=True)
origin = models.ForeignKey('origins.Origins', db_column='origin')
#origin = models.CharField(max_length=10, blank=True)
bank = models.ForeignKey('banks.Banks', db_column='bank', null=True)
vehtype = models.ForeignKey('vehtypes.Vehtypes', db_column='vehtype', verbose_name='Veh Type')
status = models.ForeignKey('status.Status', db_column='status')
imported = models.DateField()
clerk = models.CharField(max_length=10, blank=False, db_index=True, verbose_name='Clerk')
completed = models.DateField(blank=True, null=True)
registry = models.IntegerField(blank=True, verbose_name='Reg #', null=True)
plate = models.CharField(blank=True, null=True, max_length=10)
tagno = models.IntegerField(blank=True, null=True, verbose_name='Tag #')
tag_exp = models.DateField(blank=True, null=True, verbose_name='Tag Exp')
unit_linked = models.IntegerField(blank=False, verbose_name='Link')
salesperson = models.CharField(max_length=20, blank=False, verbose_name='S/person', null=True)
agent = models.ForeignKey('agents.Agents', db_column='agent', blank=True, null=True)
tradein1 = models.CharField(max_length=10, blank=True, null=True, verbose_name='stock')
tr1vin = models.CharField(max_length=17, blank=True, db_index=True, null=True, verbose_name='vin')
tr1make = models.CharField(max_length=15, blank=True, null=True, verbose_name='make')
tr1model = models.CharField(max_length=15, blank=True, null=True, verbose_name='model')
tr1year = models.CharField(max_length=4, blank=True, null=True, verbose_name='year')
tradein2 = models.CharField(max_length=10, blank=True, null=True, verbose_name='stock')
tr2vin = models.CharField(max_length=17, blank=True, db_index=True, null=True,verbose_name='vin')
tr2make = models.CharField(max_length=15, blank=True, null=True,verbose_name='make')
tr2model = models.CharField(max_length=15, blank=True, null=True,verbose_name='model')
tr2year = models.CharField(max_length=4, blank=True, null=True,verbose_name='year')
lhtrade1 = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lh1docreq = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lh1docrec = models.DateField(blank=True, null=True, verbose_name='D/Received')
lhtrade2 = models.CharField(max_length=15, blank=True, null=True, verbose_name='L/holder')
lh2docreq = models.DateField(blank=True, null=True, verbose_name='D/Requested')
lh2docrec = models.DateField(blank=True, null=True, verbose_name='D/Received')
cust1name = models.CharField(max_length=40, blank=True, db_index=True, null=True,
verbose_name='name')
cust1lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
cust1addr = models.CharField(max_length=40, blank=True, null=True, verbose_name='address')
cust1city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
cust1state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
cust1zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
cust1email = models.EmailField(blank=True, null=True, verbose_name='email')
cust1tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
cust1tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
cust1ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
cust2name = models.CharField(max_length=30, blank=True, db_index=True, null=True,
verbose_name='name')
cust2lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
cust2addr = models.CharField(max_length=25, blank=True, null=True, verbose_name='address')
cust2city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
cust2state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
cust2zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
cust2email = models.EmailField(blank=True, null=True, verbose_name='email')
cust2tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
cust2tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
cust2ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
class Meta:
db_table = 'vehicles'
def __unicode__(self):
return self.stock
def save(self, *args, **kwargs):
self.stock = self.stock.upper()
return super(Vehicles, self).save(*args, **kwargs)
Form:
from django import forms
from models import Vehicles
class VehiclesForm(forms.ModelForm):
class Meta:
model = Vehicles
It's a modelform. Firebug and console do report the POST is actually occuring, but record is not updated.
Appreciate anything you realize it's wrong.
Since, there is no answer...
At first, since you don't modify in any way your form you don't to specify it - ModelForm is implicitly meant in UpdateView by default. So, you don't need this:
form_class=VehiclesForm
Then, in your model (which is huge) you don't need blank=False - it's also defaults.
Your problem, I think, is in field validation procedure. Your template html-form renders only some of fields, but your model has much more (and what is important - they aren't optional and they have no default values).
Because of this, you simply don't see validation errors.
if you render whole form like this:
<form method="POST">{% csrf_token %}
{{ form.as_p }}
<button type="submit"> Save</button>
Close
</form>
...you'll see validation errors!
PS: If you wanted to render only those fields you must:
1) specify fields attribute with list of those fields:
# django doc example
class AuthorUpdate(UpdateView):
model = Author
fields = ['name']
template_name_suffix = '_update_form'
2) ensure that you provide all needful data (default or explicitly through form fields) for model instance saving.
3) read the Django docs - it is very detailed and meticulous, good luck!
For me I have to change
<form action="." .....>
to
<form action="" ..... >