I'm trying to get a list of all the doctor listings from the Doctor model in one of the templates. But the template is not showing anything. It's not like there is no data in the models, I can see it's populated through the admin panel.
here is the template doclistings.py
{% for doc in doctor.all %}
<p>{{doc.name}}</p>
<p>{{doc.specialization}}</p>
<p>{{doc.clinic}}</p>
{% endfor %}
Here is the views.py
def allDocs(request):
return render(request, 'meddy1/doclistings.html')
Here is the models.py
class Doctor(models.Model):
name = models.CharField(max_length=30)
specialization = models.ForeignKey(Specialization)
scope = models.CharField(max_length=100, blank = True)
clinic = models.ForeignKey(Clinic)
seekers = models.ManyToManyField(DoctorSeeker, through='Review')
language = models.ManyToManyField(Language)
education1 = models.CharField(max_length=100)
education2 = models.CharField(max_length=100, null = True)
gender_choices = ( ('M', 'Male'), ('F','Female'),)
gender = models.CharField(max_length=5, choices = gender_choices, null=True)
profile_pic = models.ImageField(upload_to='meddy1/images/', blank=True)
statement = models.TextField(null=True)
affiliation = models.CharField(max_length=100, null = True)
Here is urls.py
url(r'^doclistings/$', views.allDocs, name='allDocs'),
You need to pass the list to template from the view. In your code, the variable doctor is not defined in the template, so it doesn't show anything.
Change your view to pass doctlist as
def allDocs(request):
return render(request, 'meddy1/doclistings.html', {'doclist': Doctor.objects.all()})
Update template to use doclist to show each item.
{% for doc in doclist %}
<p>{{doc.name}}</p>
<p>{{doc.specialization}}</p>
<p>{{doc.clinic}}</p>
{% endfor %}
Related
So I'm building a real estate website for school. And one of the requirements is to have CRUD functionality on the front end for admins. But before i knew that i created in the backend admin page, all the fields that need to be filled before a listing can be published.
But now i need to display all of the fields i created on the backend admin page to show on the front end. I've tried writing the code to display it but its not really working. Im only seeing the submit button.
Im new to coding and stack overflow, so please do let me know if you need anything els from me or if ive done something wrong.
these are the fields that should be filled and show up in the front end for realtors to publish, edit and remove a listing:
models.py
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100)
state = models.CharField(max_length=100)
zipcode = models.CharField(max_length=20)
description = models.TextField(blank=True)
price = models.IntegerField()
bedrooms = models.IntegerField()
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
sqft = models.IntegerField()
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/')
photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
This is the code that Ive tried writing to display the code above on the front end so it can be edited.
forms.py
from django.forms import ModelForm
from listings.models import Listing
class listingForm():
class Meta:
model = Listing
fields = '__all__'
create_listing.html
{% extends 'base.html' %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" name="submit">
</form>
{% endblock %}
views.py
def createListing(request):
form = listingForm()
context = {'form': form}
return render(request, 'accounts/create_listing.html')
You didn't pass in the context to the render function, the code should look like this:
def createListing(request):
form = listingForm()
context = {'form': form}
return render(request,'accounts/create_listing.html', context)
Also a suggestion for your code is optimising the photos for your Listing model, here is a good material to watch: https://youtu.be/-0nYBqY9i5w
I want my reviews that are on that particular product to be shown only on that product not on any other . I do not know how to filter it. Recently it is showing all the reviews on every product.
My models.py file is:
class Review(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product , on_delete=models.CASCADE, null=True)
date = models.DateTimeField(auto_now_add=True)
text = models.TextField(max_length=3000 , blank=True)
rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES)
likes= models.PositiveIntegerField(default=0)
dislikes = models.PositiveIntegerField(default=0)
def __str__(self):
return self.user.full_name
my product models.py is:
class Product(models.Model):
title = models.CharField(max_length=110)
slug = models.SlugField(blank=True, unique=True)
status = models.CharField(choices=CATEGORY_CHOICES, max_length=10)
price = models.DecimalField(decimal_places=2, max_digits=6)
quantity=models.IntegerField(default=1)
discount_price=models.FloatField(blank=True, null=True)
size = models.CharField(choices=SIZE_CHOICES, max_length=20)
color = models.CharField(max_length=20, blank=True, null=True)
image = models.ImageField(upload_to=upload_image_path)
description = RichTextField(max_length=1000)
featured = models.BooleanField(default=False)
author = models.ForeignKey(User, on_delete=models.CASCADE)
time_stamp = models.DateTimeField(auto_now_add=True)
my product detail views.py is:
class ProductDetailSlugView(ObjectViewedMixin,DetailView):
queryset = Product.objects.all()
context_object_name = "object_list"
template_name = "product_detail.html"
def get_context_data(self, *args ,**kwargs):
context = super(ProductDetailSlugView , self).get_context_data(*args, **kwargs)
context['reviews'] = Review.objects.all()
# context['reviews'] = Review.objects.filter(product=self.request.product)
cart_obj, new_obj = Cart.objects.new_or_get(self.request)
context['cart'] = cart_obj
# context['comments'] = Comment.objects.all()
return context
my product_detail.html is:
<!-- {% for review in reviews %}-->when i do this with my code it show me all the product
<!-- <h1>{{review.text}}{{review.rate}}</h1>-->
<!-- {% endfor %}-->
{% for review in product.review_set.all %}
{{ review.text }}
{% endfor %}
You do not need to make a query separately for your reviews. You can simply loop over them using your instance of Product in the template. Also for some reason you have set context_object_name = "object_list" try this:
{% for review in object.review_set.all %}
{{ review.text }}
{% endfor %}
Here review_set is simply the default related_name set by Django which is the related models name in lowercase with _set appended to it. You can chose to set the related name yourself like so if you want:
product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE, null=True)
Anyway if you insist on modifying the view you can simply do this:
class ProductDetailSlugView(ObjectViewedMixin,DetailView):
queryset = Product.objects.all()
context_object_name = "object_list"
template_name = "product_detail.html"
def get_context_data(self, *args ,**kwargs):
context = super(ProductDetailSlugView , self).get_context_data(*args, **kwargs)
context['reviews'] = Review.objects.filter(product=self.object)
cart_obj, new_obj = Cart.objects.new_or_get(self.request)
context['cart'] = cart_obj
# context['comments'] = Comment.objects.all()
return context
And then you can use this:
{% for review in reviews %}
{{ review.text }}
{% endfor %}
I want to fetch all the foreignkey table's attribute and show it in my HTML template. Here is my code in models, views and in the template:
models.py:
class OrderDashboard(models.Model):
title = models.CharField(max_length=100,default=None)
single_slug = models.SlugField(max_length=100, default=1)
description = models.TextField(max_length=1000)
thumb = models.ImageField()
date = models.DateField()
def __str__(self):
return self.title
class OrderScenario(models.Model):
webshop = models.CharField(max_length=100)
title = models.ForeignKey(OrderDashboard, default=None, on_delete=models.SET_DEFAULT)
order_qty = models.TextField(max_length=10)
order_date = models.DateField()
current_status = models.CharField(max_length=100)
ticket = models.CharField(max_length=200)
remark = models.TextField()
class Meta:
verbose_name_plural = "Scenario"
def __str__(self):
return self.webshop
Views.py:
def single_slug(request, single_slug):
report = OrderDashboard.objects.get(single_slug=single_slug)
return render(request, 'order_dashboard/report.html', {'report': report,
'OrderScenario': OrderScenario.objects.all})
I only want to view all the scenarios added in OrderScenario with respect to Title in OrderDashboard.
You should use backward relationship here; if you are passing the slug through the url, you can use:
views.py:
def single_slug(request, slug): # why you have self as the first argument?
report = OrderDashboard.objects.get(single_slug=slug)
return render(request, 'order_dashboard/report.html', {'report': report}
report.html:
{{ report.title }}
</p>Order Scenarios:</p>
{% for scenario in report.orderscenario_set.all %}
{{ scenario }}
{% endfor %}
I'm trying to display a manytomany field from doctor models in template. Every doctor has more than one language associated to it. So I'm trying to display languages associated to each doctor. The problem I have is that it's not showing me anything
Here is my template where I'm trying to show
{% for a in doctor.languages.all %}
<p>{{a}}</p>
{% endfor %}
Here is the models.py
class Language(models.Model):
'''
a = "English"
b = "Arabic"
c = "Hindi"
d = "Urdu"
e = "Bengali"
f = "Malayalam"
g = "French"
h = "Spanish"
'''
name = models.CharField(max_length=200)
def __unicode__(self):
return self.name
class Doctor(models.Model):
name = models.CharField(max_length=30)
specialization = models.ForeignKey(Specialization)
clinic = models.ForeignKey(Clinic)
seekers = models.ManyToManyField(DoctorSeeker, through='Review')
language = models.ManyToManyField(Language)
education1 = models.CharField(max_length=100)
education2 = models.CharField(max_length=100, null = True)
gender_choices = ( ('M', 'Male'), ('F','Female'),)
gender = models.CharField(max_length=5, choices = gender_choices, null=True)
profile_pic = models.ImageField(upload_to='uploads/', null=True)
statement = models.TextField(null=True)
affiliation = models.CharField(max_length=100, null = True)
def __unicode__(self):
return u"%s %s" % (self.name, self.specialization)
The field is called language, not languages:
{% for a in doctor.language.all %}
<p>{{ a }}</p>
{% endfor %}
In Django I need to filter the data and display the result like. for example
Alabama(20)
Iowa(12)
Here "Alabama,Iowa" are State Names and inside the brackets "20,12" are no. of jobs available by the particular States.
models.py
class User(models.Model):
first_name= forms.CharField(max_length=30,widget=forms.TextInput())
last_name = forms.CharField(max_length=30,widget=forms.TextInput())
username = forms.CharField(max_length=30,widget=forms.TextInput())
email = forms.EmailField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
companyname = forms.CharField(max_length=30,widget=forms.TextInput())
class jobs(models.Model):
emp = models.ForeignKey(User, unique=False)
title = models.CharField(max_length=30)
referencecode = models.CharField(max_length=30)
jobsummary = models.TextField()
jobdetails = models.TextField()
key_skills = models.CharField(max_length=30)
states = models.CharField(max_length=30)
I tried to give views.py is like
def search_result(request):
details = jobs.objects.annotate().order_by('state')
return render_to_response('searchresult.html', {'details': details})
templates
<ul>
{% for d1 in details %}
<li>{{ d1.state }}({{ d1.count }})</li>
{% endfor %}
</ul>
It displays only State name not a count. Give some clarification.
You can do this:
from django.db.models import Count
jobs.objects.values('states').annotate(count=Count('states'))
It seems to be tricky, but u can do this by refer "https://docs.djangoproject.com/en/dev/ref/models/querysets/"