How to return address in DealershipList with ListView?
I try in views.py
class DealershipList(ListView):
template_name = 'dealership_list.html'
model = Dealership
def get_queryset(self):
pass
def get_context_data(self, **kwargs):
context = super(DealershipList, self).get_context_data(**kwargs)
address = Dealership.objects.get(pk=self.kwargs['address'])
context['address'] = self.address
return context
I need in templates.
{% for dealership in dealership_list %}
<div class="col-lg-6">
<h4>{{ dealership.dealership }}</h4>
<p>{{ address.address }}</p>
<p>Site: {{ dealership.site }}</p>
</div>
{% endfor %}
Address:
Av. One, 2
Dealership:
dealership name
Av. One, 2
models.py
class Address(models.Model):
address = models.CharField(_(u'endereço'), max_length=80)
address_number = models.PositiveIntegerField(_(u'número'))
district = models.CharField(_('bairro'), max_length=80)
city = models.CharField(_('cidade'), max_length=80)
class Dealership(models.Model):
dealership = models.CharField(_(u'concessionária'), max_length=50)
address = models.ForeignKey(
"Address", verbose_name=u'endereço', related_name='dealership_address')
site = models.CharField(_('site'), max_length=100, null=True, blank=True)
Now i try:
class DealershipList(ListView):
template_name = 'core/dealership/dealership_list.html'
model = Dealership
def get_context_data(self, **kwargs):
id_address = Address.objects.get(pk=self.kwargs['pk'])
address = Dealership.objects.filter(address=id_address)
context = super(DealershipList, self).get_context_data(**kwargs)
context['address'] = address
return context
But not work
urls.py
url(r'^dealerships/$', DealershipList.as_view(), name='dealership_list'),
Resolved.
{{ dealership.address.address }}
Related
In my code of invoice food name and food price both are showing food name on localhost portal so look into my foreign keys And also guide how to multiply product price and quantity. I am showing you both add product table and invoice table and their forms also look out and guide me for this
models.py
class AddFood(models.Model):
food_name = models.CharField(max_length=20)
food_price = models.PositiveIntegerField()
company = models.ForeignKey(CompRegister, on_delete=models.CASCADE)
res = models.ForeignKey(ResRegister, on_delete=models.CASCADE)
def __str__(self):
return self.food_name
class GenerateInvoice(models.Model):
foods_name = models.ForeignKey(AddFood, null=True, on_delete=models.CASCADE, related_name='food_n')
foods_price = models.ForeignKey(AddFood, null=True, on_delete=models.CASCADE, related_name='food_p')
quantity = models.PositiveIntegerField()
company = models.ForeignKey(CompRegister, on_delete=models.CASCADE)
res = models.ForeignKey(ResRegister, null=True, on_delete=models.CASCADE)
start_date = models.DateTimeField(auto_now_add=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __str__(self):
return self.res, self.foods_name
def total_price(self):
return AddFood.food_price * self.quantity
forms.py
class FoodForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(FoodForm, self).__init__(*args, **kwargs)
self.fields['res'].queryset = ResRegister.objects.filter(res=True, company__user_id=user)
class Meta:
model = AddFood
exclude = ['company','price','food']
fields = '__all__'
class InvoiceForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(InvoiceForm, self).__init__(*args, **kwargs)
self.fields['foods_name'].queryset = AddFood.objects.filter(company__user_id=user)
self.fields['foods_price'].queryset = AddFood.objects.filter(company__user_id=user)
class Meta:
model = GenerateInvoice
exclude = ['company','res','start_date',]
fields = '__all__'
views.py
def generate_invoice(request):
u = CompRegister.objects.get(user_id=request.user)
if request.method == 'POST':
form = InvoiceForm(request.user, request.POST)
if form.is_valid():
form_r = form.save(commit=False)
form_r.company = u
form_r.save()
return redirect('company:cart_page')
else:
print(form.errors)
else:
form = InvoiceForm(request.user)
return render(request, 'comp/generate_invoice.html', {'form': form})
generate_invoice.html
<!DOCTYPE html>
{% extends 'Comp_base.html' %}
{% block head %}
<meta charset="UTF-8">
<title>Generate Invoice</title>
{% endblock %}
{% block body %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Generate Invoice</button>
</form>
{% endblock %}
</html>
I have two models with one being a foreign key to another. A user can only submit an answer. am trying to use the if statement to check if an answer exit for a user then the submit answer button should change the update button the template.
class Assignment(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=500)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
class_or_level = models.ForeignKey(StudentClass, on_delete=models.CASCADE)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
file = models.FileField(upload_to='assignment', blank=True, null=True)
Text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
date_expire = models.DateTimeField()
class Answer(models.Model):
slug = models.SlugField(max_length=500)
assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
file = models.FileField(upload_to='assignment')
date_added = models.DateTimeField(auto_now_add=True)
My View
class AssignmentView(LoginRequiredMixin, ListView):
template_name = 'assignment.html'
context_object_name = 'all_couses'
now = timezone.now()
queryset = Course.objects.all()
def get_context_data(self, **kwargs):
now = timezone.now()
context = super(AssignmentView, self).get_context_data(**kwargs)
context.update({
'assignment_list': Assignment.objects.filter(class_or_level=self.request.user.student.class_or_level, date_expire__gte=now).order_by('-date_expire'),
})
return context
this the template> What the users submitted answer to show if he does submit one else show the form like to submit answer
{% for assignment in assignment_list %}
<h4>{{ assignment.title|truncatewords:12 }}</h4>
{% if assignment.answer %}
{{ assignment.answer.file }}
<button> Update Answer</button>
{% else %}
<button> Summit Answer</button>
{% endif %}
{% endfor %}
You can change your view or create a template tag to identify if an assignment has a response of a specific user, I decided to change the view and add a new variable to the assignment object that will have the information of if the user who requested the page has an answer to that assignment:
class AssignmentView(LoginRequiredMixin, ListView):
template_name = 'assignment.html'
context_object_name = 'all_couses'
now = timezone.now()
queryset = Course.objects.all()
def get_context_data(self, **kwargs):
now = timezone.now()
context = super(AssignmentView, self).get_context_data(**kwargs)
assignment_list = Assignment.objects.filter(
class_or_level=self.request.user.student.class_or_level,
date_expire__gte=now
).order_by('-date_expire')
for assignment in assignment_list:
try:
assignment.student_answer = Answer.objects.get(
assignment=assignment,
student=self.request.user
)
except Answer.DoesNotExist:
pass
context.update({
'assignment_list': assignment_list,
})
return context
Then, inside of your template you can do the following:
{% for assignment in assignment_list %}
<h4>{{ assignment.title|truncatewords:12 }}</h4>
{% if assignment.student_answer %}
{{ assignment.student_answer.file }}
<button> Update Answer</button>
{% else %}
<button> Summit Answer</button>
{% endif %}
{% endfor %}
By doing that you'll achieve what you're looking for.
I have this model:
class Category(models.Model):
name = models.CharField(max_length=150, unique=True)
description = models.CharField(max_length=250)
def get_absolute_url(self):
return reverse('categories_url', args=[str(self.id)])
class Company(models.Model):
name = models.CharField(max_length=150, unique=True)
country = models.CharField(max_length=50)
class Motobike(models.Model):
name = models.CharField(max_length=150)
company = models.ForeignKey('Company', on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
And in view i do so..
class CategoryView(DetailView):
model = Category
template_name = 'bikes_site/categories_detail.html'
pk_url_kwarg = 'pk'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = self.get_object()
context['motobikes'] = Motobike.objects.filter(category_id=category.pk)
return context
And display everythng in the template
{% for motobike in motobikes %}
<ul>
<p> Name: {{ motobike.name }}</p>
<p> Company: {{ company.name }}</p>
<p> Category: {{ object.name }}</p>
<p> Description: {{ object.description }} </p>
</ul>
{% endfor %}
How to rewrite it to be displayed in JSON format(such task)? It's necessary through HttpResponse.
Here's my test:
client = Client()
category_id = Category.objects.get(name='Мотоциклы').id
response = client.get(f'/categories/{category_id}/')
assert response.status_code == 200
response_data = json.loads(response.content.decode('utf-8'))
assert len(response_data) == 2
assert response_data[1]['name'] == 'Ninja Turbo'
assert response_data[1]['vendor'] == 'Kawasaki'
assert response_data[1]['category'] == 'Мотоциклы'
assert response_data[1]['description'] == ''
How else to push the name of the company??
I'm trying to use django formset for the first time in order to combine both forms on the same page.
My form is well displayed but I don't overvome to save data in my database. When I click on submit button, nothing happens.
This is my model.py file :
class Publication(models.Model):
title = models.CharField(max_length=512, verbose_name=_('title'), null=False)
category = models.ForeignKey(Category, verbose_name=_('category'), null=False)
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('publication')
verbose_name_plural = _('publication')
def __str__(self):
return f"{self.title}"
class Document(models.Model):
FORMAT_CHOICES = (
('pdf', 'pdf'),
('epub', 'epub'),
)
format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False)
title = models.CharField(max_length=512, verbose_name=_('title'), null=False)
publication = models.ForeignKey(Publication, verbose_name=_('publication'), null=False)
upload = models.FileField(upload_to='media/', default="")
creation_date = models.DateTimeField(auto_now_add=True, verbose_name=_('creation date'), null=False)
modification_date = models.DateTimeField(auto_now=True, verbose_name=_('modification date'), null=False)
class Meta:
verbose_name = _('document')
verbose_name_plural = _('document')
def __str__(self):
return f"{self.age_id} : {self.title}"
My form file is very simple too with defined Formset :
class PublicationForm(forms.ModelForm):
class Meta:
model = Publication
fields = ('title', 'category')
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ['publication', 'format', 'title', 'upload']
DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1)
My view is a bit more complicated :
class PublicationCreateUpdateView(AgePermissionRequiredMixin, UpdateView):
""" Display a form to create or update a publication
Only for age admin.
**Context**
``subtitle``
Title of the page
**Template:**
:template:`app/category_form.html`
"""
model = Publication
form_class = PublicationForm
success_url = reverse_lazy('app:app-publication-list')
template_name = 'app/publication_form.html'
permission_required = 'publication.change_webapplication'
def get_object(self, queryset=None):
try:
return super(PublicationCreateUpdateView, self).get_object(queryset)
except AttributeError:
return None
def get_title(self):
if self.object:
return _('Edit publication: ') + str(self.object)
return _('Add new publication')
def get_context_data(self, **kwargs):
context = super(PublicationCreateUpdateView, self).get_context_data(**kwargs)
if self.request.POST :
context['documents'] = DocumentFormSet(self.request.POST)
else :
context['documents'] = DocumentFormSet()
context.update({
'subtitle': self.get_title(),
})
return context
def form_valid(self, form):
context=self.get_context_data()
documents = context['documents']
with transaction.atomic():
self.object = form.save()
if documents.is_valid():
documents.instance = self.object
documents.save()
return super(DocumentCreateUpdateView, self).form_valid(form)
And finally my template looks like this :
{% extends "publication/base_backend.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block main %}
<form method="post" novalidate>
{% csrf_token %}
{% crispy form %}
{{ documents.management_form }}
{{ documents.non_form_errors }}
{% crispy documents %}
<br>
<input type="submit" class="btn btn-default" value="{% trans 'Save' %}" />
{% trans 'Cancel' %}
</form>
{% endblock main %}
I don't understand where I could make a mistake, furthermore I'm pretty new with Django Class Based View.
I m beginner.
I'm trying to access a related item of the model Product in the template layer of a ProductDetailView. How can I retrieve the ImageFields of the Products' Brand's BrandImages? I have to traverse one forward and one reverse ForeignKey.
Edited to include get_logo_url
What is wrong with the get_logo_url function?
products/models.py
class Product(models.Model):
brand = TreeForeignKey('Brand', verbose_name='parent category', related_name='products', default='')
title = models.CharField(max_length=120)
description = models.TextField(max_length=500, blank=True, null=True)
price = models.DecimalField(decimal_places=2, max_digits=20)
active = models.BooleanField(default=True)
category = TreeForeignKey('Category', verbose_name='parent category', related_name='products', default='')
slug = models.SlugField(default='')
objects = ProductManager()
class Meta:
unique_together = ('slug', 'category')
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk":self.pk})
def __unicode__(self):
return self.title
def get_image_url(self):
img = self.productimage_set.first()
if img:
return img.image.url
return img
brands/models.py
def image_upload_to(instance, filename):
title = instance.brand.title
slug = slugify(title)
file_extension = filename.split(".")[1]
new_filename = "%s.%s" % (instance.id, file_extension)
return "products/%s/%s" % (slug, new_filename)
class BrandImage(models.Model):
brand = models.ForeignKey('Brand', related_name='brandimages')
is_slider = models.BooleanField(default=False)
is_featured = models.BooleanField(default=False)
is_logo = models.BooleanField(default=False)
image = models.ImageField(upload_to=image_upload_to)
def __unicode__(self):
return self.brand.title
def get_logo_url(self):
if is_logo:
img = self.brandimage_set.first()
if img:
return img.image.url
return img
def thumb(self):
if self.image:
return u'<img src="%s" width=120 height=120 />' % (self.image.url)
else:
return u'No image file found'
thumb.allow_tags = True
class Brand(MPTTModel):
title = models.CharField(max_length=50, default='')
parent = TreeForeignKey('self', null=True, blank=True, verbose_name='parent brand', related_name='brands')
slug = models.SlugField(unique=True)
def get_absolute_url(self):
return reverse('brands', kwargs={'path': self.get_path()})
def __unicode__(self):
return self.title
template
<div class="rightpart">
<div class="prodbrand h2">
<h1>{{ product.brand }}</h1>
<div class="brandlogo">
{% for image in product.brand.brandimages.all %}
<img src="{{image.get_logo_url }}"/>
{% endfor %}
</div>
</div>
<div class="prodtitle"><h2>{{ product.title }}</h2>
</div>
views.py
class ProductDetailView(DetailView):
model = Product
template_name = 'products/product.html'
def get_context_data(self , *args , **kwargs):
context = super(ProductDetailView , self).get_context_data(*args,**kwargs)
instance = self.get_object()
context["related"] = Product.objects.get_related(instance)
return context
urls.py
url(r'^$', ProductDetailView.as_view(), name='products'),
is there a way to access foreign fields in django templates like this?
As you are using a ListView to display your products there's several things to notice:
get_context_data() must return a dictionary: return context is missing
super().get_context_data should be called with *args,**kwargs incase you decide to subclass the ProductListView at a later point in time.
super().get_context_data will contain a object_list key which contains the list of objects returned by get_queryset(), in your case objects of class Product.
When accessing a property from a template, django will attempt to call it without parameters if it is callable. This is often useful e.g.: for {{ request.user.is_authenticated }} or product.brand.brandimages.all
Your template should look like this:
product_list.html
{% for product in object_list %}
<div class="rightpart">
<div class="prodbrand h2">
<h1>{{ product.brand }}</h1>
<div class="brandlogo">
{% for image in product.brand.brandimages.all %}
<img src="{{image.image.url}}"/>
{% endfor %}
</div><!-- End brandlogos -->
</div><!-- End prodbrand -->
<div class="prodtitle">
<h2>{{ product.title }}</h2>
</div>
</div><!-- End rightpart -->
{% endfor %}
Take into account that this will incur several database lookups from the template. You generally want to avoid the case that your presentation layer reaches into the database, which is why you should prefer to do the database lookup in the corresponding View. Also for property access consider using select_related and prefetch_related as appropriate to avoid unneeded database queries.
views.py
class ProductListView(ListView):
model = Product
queryset = Product.objects.all().active()
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
context["now"] = timezone.now()
return context
def get_queryset(self, *args, **kwargs):
# We call super() for potential subclasses
queryset = super(ProductListView, self).get_context_data(*args, **kwargs)
queryset.prefetch_related('brand__brandimages')
return queryset