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 %}
Related
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 %}
Models
attendance_choices = (
('absent', 'Absent'),
('present', 'Present')
)
class Head_of_department(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=30)
def __str__(self):
return self.first_name
class Employee(models.Model):
first_name = models.CharField(max_length=200, unique=True)
last_name = models.CharField(max_length=200, unique=True)
head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
email = models.EmailField(max_length=100)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Attendance(models.Model):
head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
employee = models.ForeignKey('Employee', on_delete=models.CASCADE, )
attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True)
Views
class Attendancecreate(CreateView):
model = Attendance
fields = ['employee']
success_url = '/dashboard/'
def get_context_data(self,** kwargs):
context = super(Attendancecreate, self).get_context_data(**kwargs)
context['formset'] = AttendanceFormset(queryset=Attendance.objects.none())
context['attendance_form'] = Attendanceform()
email = self.request.user.email
hod = Head_of_department.objects.get(email=email)
context["employees"] = Employee.objects.filter(head_of_department =hod)
return context
def get_initial(self):
email = self.request.user.email
hod = Head_of_department.objects.get(email=email)
initial = super(Attendancecreate , self).get_initial()
initial['employee'] = Employee.objects.filter(head_of_department=hod)
return initial
def post(self, request, *args, **kwargs):
formset = AttendanceFormset(request.POST)
if formset.is_valid():
return self.form_valid(formset)
def form_valid(self, formset):
instances = formset.save(commit=False)
for instance in instances:
instance.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email)
instance.save()
return HttpResponseRedirect('/dashboard/')
Forms
class Attendanceform(ModelForm):
class Meta:
model = Attendance
fields = ('employee','attendance','head_of_department')
AttendanceFormset = modelformset_factory(Attendance,fields=('attendance',))
Template
{% csrf_token %}
{{ formset.management_form }}
{% for employee in employees %}
{% for form in formset %}
{{employee.first_name}} {{ form }}
{ % endfor %}<br><br>
{% endfor %}
The webapp has a login feature. The headofdepartment can mark the attendance . List of employees are rendered in the template without any issues , I want to mark attendance to the respective employees sorted in ascending order of their first_name .
That is when marking attendance employees will be listed in template, and to the right attendance form will be displayed for all the employees . It is saving only one object and not assigning the initial value for employee
Requirement :
Following dirkgroten I was able to solve the issue, answer allow to render a list employees under the head_of_department(logged in hod) and mark respective attendance .
Models
attendance_choices = (
('absent', 'Absent'),
('present', 'Present')
)
class Head_of_department(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
email = models.CharField(max_length=30)
def __str__(self):
return self.first_name
class Employee(models.Model):
first_name = models.CharField(max_length=200, unique=True)
last_name = models.CharField(max_length=200, unique=True)
head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
email = models.EmailField(max_length=100)
def __str__(self):
return self.first_name + ' ' + self.last_name
class Attendance(models.Model):
head_of_department = models.ForeignKey('Head_of_department', on_delete=models.SET_NULL, blank=True, null=True)
employee = models.ForeignKey('Employee', on_delete=models.CASCADE, )
attendance = models.CharField(max_length=8, choices=attendance_choices, blank=True)
Views
class Attendancecreate(CreateView):
model = Attendance
form_class = Attendanceform
success_url = '/dashboard/'
def get_context_data(self,** kwargs):
context = super(Attendancecreate, self).get_context_data(**kwargs)
context['formset'] = AttendanceFormset(queryset=Attendance.objects.none(), instance=Head_of_department.objects.get(email=self.request.user.email), initial=[{'employee': employee} for employee in self.get_initial()['employee']])
return context
def get_initial(self):
email = self.request.user.email
head_of_department = Head_of_department.objects.get(email=email)
initial = super(Attendancecreate , self).get_initial()
initial['employee'] = Employee.objects.filter(head_of_department=head_of_department)
return initial
def post(self, request, *args, **kwargs,):
formset = AttendanceFormset(request.POST,queryset=Attendance.objects.none(), instance=Head_of_department.objects.get(email=self.request.user.email), initial=[{'employee': employee} for employee in self.get_initial()['employee']])
if formset.is_valid():
return self.form_valid(formset)
def form_valid(self,formset):
instances = formset.save(commit=False)
for instance in instances:
instance.head_of_department = get_object_or_404(Head_of_department, email=self.request.user.email)
instance.save()
return HttpResponseRedirect('/dashboard/')
Forms
class Attendanceform(ModelForm):
class Meta:
model = Attendance
widgets = {'employee' : HiddenInput}
fields = ('employee','attendance','hod')
AttendanceFormset = inlineformset_factory(Head_of_department,Attendance,form=Attendanceform,fields=('attendance','employee'))
Template
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form.employee.initial }} {{ form.employee}} {{ form.attendance }}
<br><br>
{% endfor %}
How might I query through a ManytoMany field to list the shows an Artist has played (along with their genre which has been completed). I am fairly new to Django with just finishing up the Tango with Django tutorial, but what I have so far is below.
models.py
class Genre(models.Model):
name = models.CharField(max_length=20, unique=True, blank=False)
def __unicode__(self):
return self.name
class Artist(models.Model):
name = models.CharField(max_length=50, unique=True, blank=False)
photo = models.ImageField(upload_to='artist_photos', blank=True)
logo = models.ImageField(upload_to='artist_logos', blank=True)
genre = models.ManyToManyField(Genre)
twitter = models.URLField(blank=True)
facebook = models.URLField(blank=True)
instagram = models.URLField(blank=True)
def __unicode__(self):
return self.name
class Venue(models.Model):
name = models.CharField(max_length=50, unique=True, blank=False)
logo = models.ImageField(upload_to='venue_logos', blank=True)
capacity = models.IntegerField(blank=False)
address = models.CharField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
state = models.CharField(max_length=50, blank=True)
zip_code = models.IntegerField(max_length=50, blank=True, null=True)
website = models.URLField(blank=True)
twitter = models.URLField(blank=True)
facebook = models.URLField(blank=True)
instagram = models.URLField(blank=True)
def __unicode__(self):
return self.name
class Show(models.Model):
venue = models.ForeignKey(Venue)
date_time = models.DateTimeField(blank=False)
attendance = models.IntegerField(blank=False)
bands = models.ManyToManyField(Artist)
views.py
def artists(request):
context = RequestContext(request)
artists = Artist.objects.order_by('name')
shows = Show.objects.order_by('-date_time')
# artist_shows = Show.objects.filter(????????)
context_dic = {'artists': artists, 'shows': shows}
return render_to_response('artistdb/artists.html', context_dic, context)
artist.html
<h2>Artists</h2>
{% if artists %}
<ul>
{% for artist in artists %}
<li>{{ artist.name }}<br />
<ul>
{% for g in artist.genre.all %}
<li>{{ g.name }}</li>
{% endfor %}
</ul>
</li>
<br />
{% endfor %}
</ul>
{% else %}
There are no artist.
{% endif %}
To get the shows that an artist has played, you can do this:
artist = Artist.objects.get(name="johndt6")
artist.show_set.all() # Will return all shows related to the artist
A recommendation is to set a related_name argument on your foreign keys and many to many fields. So, under the Show model, the many to many relation to artist would read:
bands = models.ManyToManyField(Artist, related_name="shows")
Then, you could query an artist's shows as follows:
artist.shows.all() # Will return all of the artists shows
You can also use normal queries if you wish:
shows = Show.objects.filter(bands__in=artist) # Will return all of an artist's shows
However, this isn't quite as nice as using Django's built in relations.
See documentation here
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 %}
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/"