How to rewrite data from a template in JSON? - django

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??

Related

Filtering foreign Key content in django templated using if statement

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.

active state and city display only in django template ForeignKey

I have country state city model and here is my view
class Country(models.Model):
name = models.CharField(max_length = 100)
def __str__(self):
return "%s" %(self.name)
class State(models.Model):
name = models.CharField(max_length = 100)
country = models.ForeignKey(Country, on_delete = models.CASCADE)
is_active = models.BooleanField(default = True)
def __str__(self):
return "%s" %(self.name)
class City(models.Model):
name = models.CharField(max_length = 100)
state = models.ForeignKey(State, on_delete = models.CASCADE)
is_active = models.BooleanField(default = True)
def __str__(self):
return "%s" %(self.name)
here is my view
class CountryList(ListView):
def get_template_names(self, *args, **kwargs):
return ['albums/list.html']
def get_queryset(self, *args, **kwargs):
return Country.objects.all()
now i want to show country with active state and active cities only how can do this in my template ?
my view
{% for x in object_list %}
{{x.name}} : <br>
{% for state in x.state_set.all %}
{{ state.name }} >>
{%for city in state.city_set.all %}
------#
{{ city.name }}
{% endfor %}
<br>
{% endfor %}
</br>
{% endfor %}

Django Formset issue - POST doesn't seems to work

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.

How to get image connected by Foreign Key via Template in django

i want to get the images form the image model in the template.
class Products(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
class Image(models.Model):
property = models.ForeignKey(Products, related_name='images')
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html',
locals(),
context_instance=RequestContext(request))
{% for query in queryset %}
<img src='/ {{ query.????? }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
i want to get the images which is connected to that product
i have readed that link
i have tried:
{% for query in queryset %}
<img src='/ {{ query.images_all.0.image }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
but no success ..
just try to understand the model that how i get the image url from models which related with foreignkey relationship.
my models:
class Product(models.Model):
title = models.CharField(max_length = 400)
slug = models.SlugField(max_length = 400,unique=True,null=True,blank=True)
is_popular = models.BooleanField(default=True)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
subcategory = models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True,blank=True)
childcategory = models.ForeignKey(Childcategory,on_delete=models.CASCADE,null=True,blank=True)
brand = models.ForeignKey(Brand,on_delete=models.CASCADE,null=True,blank=True)
description = models.TextField()
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = unique_slug_generator(self)
super(Product, self).save(*args, **kwargs)
def show_image(self):
return self.productmeaserment_set.first().first_image()
class ProductMeaserment(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
measerment = models.ForeignKey(Measerment,on_delete=models.CASCADE,null=True,blank=True)
selling_price = models.DecimalField(max_digits=20,decimal_places=2)
offer_price = models.DecimalField(max_digits=20,decimal_places=2)
available_quantity = models.IntegerField();
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.measerment.name
def first_image(self):
return self.productmeasermentimage_set.first()
class ProductMeasermentImage(models.Model):
productmeaserment = models.ForeignKey(ProductMeaserment,on_delete=models.CASCADE)
image = models.FileField(upload_to='uploads/products')
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.productmeaserment.product.title
views.py
from products.models import Product
def adminpanel(request):
products=Product.objects.all()
return render(request,'adminpanel/index.html',{'productsall':products})
templates/adminpanel/index.html
{% for item in productsall %}
<tr>
<div class="border1">
<td class="image-cell">
<img src="{{item.show_image.image.url}}"> #this is how i got image url.
</td>
</div>
<td data-label="title">{{item.title}}</td>
<td data-label="category">{{item.category}}</td>
<td data-label="subcategory">{{item.subcategory}}</td>
<td data-label="brand">
{{item.brand}}
</td>
<td data-label="description">
{{item.description}}
</td>
<td class="created">
{{item.created_date}}
</td>
</tr>
<tr>
{% endfor %}
There is so much wrong with your code, I suggest that you do the Django Tutorial first.
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
But if you wan't it working, here is how:
models.py
class Product(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
def first_image(self):
# code to determine which image to show. The First in this case.
return self.images[0]
class ProductImage(models.Model):
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
product = models.ForeignKey(Product, related_name='images')
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html', {'products': queryset})
index.html
{% for product in products %}
<img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}

Return address in ListView

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 }}