I have this models:
class roles(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=False)
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.name
class freelancers(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
company = models.ForeignKey(Company, blank=True, null=True, on_delete=models.SET_NULL)
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
role = models.ManyToManyField(roles)
I try to get the name that is related to the user at the roles table.
In my view.py It looks like this:
def company_details(request,id):
obj = Company.objects.get(id=id)
pro = Projects.objects.filter(company=id)
free = freelancers.objects.filter(company=id)
#free = freelancers.objects.all()
return render(request, 'company/company_details.html',
{
'obj':obj,
'pro':pro,
'free':free,
}
)
And in the HTML:
{% for f in free %}
{{ f.user }} // <br/>
{% endfor %}
{{ f.role.all }}
{% endfor %}
I have been trying different ways to get the name to show up.
Like: {{ f.role.name }}.
So any tips to make this work?
I think you will have to iterate through the f.role.all
Related
I want to display a music album on my website, the Problem is that the album itself has two discs and each disc has x tracks. Now I'm wondering how I can display this split-up on my Django template as I want it to look like that:
Disc 1
- Title - 1
- Title - 2
- Title - 3
- Title - 4
...
Disc 2
- Title - 1
- Title - 2
- Title - 3
- Title - 4
...
This is my View:
def music_album_detail(request, pk):
music_album = get_object_or_404(MusicAlbums, pk=pk)
music_album_tracks = MusicTracks.objects.filter(album=music_album).order_by('track')
args = {
'music_album': music_album,
'music_album_tracks': music_album_tracks,
}
return render(request, 'App/music_album_detail.html', args)
At my Template I currently only do this:
{% for music_album_track in music_album_tracks %}
<td>{{ music_album_track.track }}</td>
...
This is how my model looks like:
class MusicAlbums(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)
artist = models.ForeignKey(MusicArtists, on_delete=models.CASCADE, related_name='album_artist')
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)
release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False)
genre_relation = models.ManyToManyField(through='GenreMusicAlbum', to='Genre')
total_discs = models.IntegerField(verbose_name=_("Total Discs #"), blank=True, null=True,)
total_tracks = models.IntegerField(verbose_name=_("Total Tracks #"), blank=True, null=True,)
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"))
class MusicTracks(models.Model):
objects = RandomManager()
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
file = models.ForeignKey(Files, on_delete=models.CASCADE, related_name='track_file')
bitrate = models.IntegerField(verbose_name=_("Bitrate (bps)"), blank=True, null=True, editable=False)
duration = models.FloatField(verbose_name=_("Duration"), blank=True, null=True, editable=False, max_length=255)
size = models.BigIntegerField(blank=True, null=True, verbose_name=_("Size (byte)"))
title = models.TextField(verbose_name=_("Title"), blank=True, null=True, max_length=255)
artist = models.ForeignKey(MusicArtists, on_delete=models.CASCADE, related_name='track_artist')
album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, related_name='track_album')
release_date = models.DateField(verbose_name=_("Release Date"), blank=True, null=True, editable=False)
disc = models.IntegerField(verbose_name=_("Disc #"), blank=True, null=True,)
track = models.IntegerField(verbose_name=_("Track #"), blank=True, null=True,)
date_added = models.DateTimeField(auto_now_add=True, blank=True, verbose_name=_("Date Added"))
Any Idea how I can setup such a depiction at my template?
You can order the queryset by disc first, and then by track:
MusicTracks.objects.filter(album=music_album).order_by('disc', 'track')
This will order all the tracks in the album by the disc number, and then by the tracks within those discs.
EDIT:
To display them by disc, you can do something like this:
def music_album_detail(request, pk):
music_album = get_object_or_404(MusicAlbums, pk=pk)
music_album_tracks_by_disc = {}
for track in MusicTracks.objects.filter(album=music_album).order_by('track'):
if track.disk in music_album_tracks_by_disc:
music_album_tracks_by_disc[track.disk].append(track)
else:
music_album_tracks_by_disc[track.disk] = [track]
context = {
'music_album': music_album,
'music_album_tracks_by_disc': music_album_tracks_by_disc,
}
return render(request, 'App/music_album_detail.html', context=context)
{% for disc, tracks in music_album_tracks_by_disc.items %}
<td>Disc {{ disc }}</td>
{% for track in tracks %}
<td>{{ track.track }}</td>
{% endfor %}
{% endfor %}
You should use disc in another model and set FK for that:
class MusicAlbums(models.Model):
...
class MusicDiscs(models.Model):
album = models.ForeignKey(...)
number = models.IntegerField(...) # For example
class MusicTracks(models.Model):
disc = models.ForeignKey(...)
Now in this way, every album has few discs, and every disc has it's tracks
And now you can get discs in your view, and pass it with it's tracks to template:
def music_album_detail(request, pk):
music_album_discs = Musicdiscs.objects.filter(...)
and in your templates:
{% for music_disc in music_album_discs %}
<td>{{ music_disc.number }}</td>
{% for music_track in music_album_tracks %}
<td>{{ music_track.track }}</td>
I've got three models, "Property", "Owners" and "ContactsOwner", these last one is where I save the owners contacts.
# APP: Owners - models.py
class Owner(models.Model):
name = models.CharField(db_column='Owner_Name', max_length=200)
surname = models.CharField(db_column='Owner_Surname', max_length=30)
nif = models.IntegerField(db_column='Nif_Number', blank=False, null=False, default='000000000')
doc_number = models.CharField(db_column='Document_Number', max_length=20, blank=True, null=True)
doc_type = models.CharField(db_column='Document_Type', max_length=20, blank=True, null=True, choices=DOCUMENT_TYPE_CHOICES)
address = models.CharField(db_column='Address', max_length=200, blank=True, null=True)
post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True)
nationality = models.CharField(db_column='Country', max_length=20, blank=True, null=True)
notes = models.CharField(db_column='Notes', max_length=250, blank=True, null=True)
property = models.ManyToManyField(Property)
class Meta:
db_table = 'Owner'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("owners:owner_detail",kwargs={'pk':self.pk})
class ContactsOwner(models.Model):
owner = models.ForeignKey(Owner, models.DO_NOTHING, db_column='Owner', related_name='owner_contact') # Field name made lowercase.
type = models.CharField(db_column='Type', choices=CONTACT_TYPE_CHOICES, max_length=25, blank=True, null=True) # Field name made lowercase.
number = models.IntegerField(db_column='Number', blank=True, null=True) # Field name made lowercase.
email = models.CharField(db_column='Email', max_length=100, blank=True, null=True) # Field name made lowercase.
class Meta:
db_table = 'Contacts_Owner'
verbose_name_plural = "Owners Contacts"
# APP: Properties - models.py
class Property(models.Model):
property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase.
address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase.
post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase.
type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase.
bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase.
bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase.
usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase.
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
feature_image = models.ImageField(null=True)
class Meta:
db_table = 'Property'
def __str__(self):
return self.property_reference
def get_absolute_url(self):
return reverse("properties:property_detail",kwargs={'pk':self.pk})
In my template I can access the Owner name and surname with this loop:
{% for object in property.owner_set.all %}
<h4>{{ object.name }} {{ object.surname }}</h4>
<h6>Owner</h6>
{% endfor %}
But now I need to access the contact number on "ContactsOwner" model and I can't figure out a way to filter this.
I've tried these:
{% for contact in property.owner_set.owner_contact.all %}
<div class="card-body border-top">
{{ contact.number }}
<br>
</div>
{% endfor %}
But so far I didn't find a solution. Could you please help me with this?
You can not access a related manager of a related manager, you can use a double {% for ... %} loop here, but this is not advisable:
{% for owner in property.owner_set.all %}
{% for contact in owner.owner_contact.all %}
<div class="card-body border-top">
{{ contact.number }}
<br>
</div>
{% endfor %}
{% endfor %}
It is better to perform queries in the view, since that is mainly business logic. You can retrieve all OwnerContacts for a given property with:
ContactsOwner.objects.filter(owner__property=property)
I am trying to write a Quiztool with Django. I have created an index where all surveys are listed. Clicking at one brings you in the detail view. Right now there are listed all questions with answers with a submit button going to nothing. What i am asking for is how to manage there will be only one question and when I submit the answer the next question will aply wihtout jumpin out of the detail view. If the answer is to easy i also would be happy for just getting a hint about what I have to read...
Here is some Code from my views.py
def detail(request, survey_id):
#try:
question = Survey.objects.get(pk=survey_id).question.all()
question_dict = {
'question': question,
}
return render(request, 'survey/detail.html', question_dict)
And here is my deatil.html
{% if question %}
<form method="post">
{% for x in question %}
<fieldset style="width:10%;">
<legend>{{x.question_text}}</legend>
{% for y in x.answer.all %}
<p style="display: flex;justify-content: space-between;">
<label for="{{ y.answer_id }}">{{ y.answer_text }}</label>
<input name="{{x.question_id}}" type="radio" value="{{y.answer_id}}" id="{{y.answer_id}}"/></p>
{% endfor%}
</fieldset>
{% endfor %}
<input type="button" value="Senden" onclick="var Sende=()=>{console.log('gesendet');}; Sende();">
</form>
{% else %}
<p>No questions are available.</p>
{% endif %}
And my Model
class Answer(models.Model):
answer_id = models.AutoField(blank=False, null=False, primary_key=True)
answer_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Antwort'))
# Internal fields
date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am'))
date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am'))
def __str__(self):
return self.answer_text
class Meta:
# db_table = 'data'
verbose_name = _(u'Antwort')
verbose_name_plural = _(u'Antworten')
ordering = ['answer_id']
class Question(models.Model):
question_id = models.AutoField(blank=False, null=False, primary_key=True)
# Fields
answer = models.ManyToManyField('Answer', through='Question_Answer', related_name='+')
question_text = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Text der Frage'))
# Internal fields
date_created = models.DateTimeField(blank=False, null=True, auto_now_add=True, verbose_name=_(u'Erstellt am'))
date_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name=_(u'Geändert am'))
#Typunterscheidung der Fragen
QUESTION_TYPES = (
('0', 'Vezweigt'),
('1', 'Wahr/Falsch'),
('2', 'Punkte'),
('3', 'Umfrage'),
)
type_id = models.CharField(blank=False, null=False, max_length=1, choices=QUESTION_TYPES)
# String
def __str__(self):
return self.question_text
# Meta class
class Meta:
# db_table = 'data'
verbose_name = _(u'Frage')
verbose_name_plural = _(u'Fragen')
ordering = ['question_id']
# Hilfstabelle für many to many Feld mit informationen für die Frage Logik
class Question_Answer(models.Model):
question_answer_id = models.AutoField(blank=False, null=False, primary_key=True)
question = models.ForeignKey('Question', on_delete=models.SET_NULL, null=True, related_name='+')
answer = models.ForeignKey('Answer', related_name='+', on_delete=models.SET_NULL, null=True)
is_correct = models.NullBooleanField(blank=True, null=True, default=False, verbose_name=_(u'Richtige Antwort'))
next_question = models.IntegerField(blank=True, null=True, verbose_name=_(u'Naechste Frage(Verzw.)'))
points = models.IntegerField(blank=True, null=True, verbose_name=_(u'Wertigkeit der Antwort'))
class Survey(models.Model):
survey_id = models.AutoField(blank=False, null=False, primary_key=True)
question = models.ManyToManyField('Question', through='Survey_Question', related_name='+')
survey_titel = models.CharField(blank=False, null=True, max_length=500, verbose_name=_(u'Titel des Fragebogens'))
class Meta:
# db_table = 'data'
verbose_name = _(u'Fragebogen')
verbose_name_plural = _(u'Fragebögen')
ordering = ['survey_id']
class Survey_Question(models.Model):
survey_question_id = models.AutoField(blank=False, null=False, primary_key=True)
question = models.ForeignKey('Question', related_name='+', on_delete=models.SET_NULL, null=True)
survey = models.ForeignKey('Survey', on_delete=models.SET_NULL, null=True, related_name='+')
order = models.IntegerField(blank=True, null=False, verbose_name=_(u'Rangfolge der Antwort'))
Thank you in advance Flotzen
I think the most straightforward approach would be to keep your code the same in Django, and use Javascript to handle what the user sees on the browser. Then, upon completion, you can submit the answers like a traditional form post.
This sound like something where you would throw your objects into a Paginator (with `per_page of 1) and then you could walk through them.
See: https://docs.djangoproject.com/en/2.0/topics/pagination/
I have the following models:
# models.py
class Site(models.Model):
name = models.CharField(max_length=75)
slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
link = models.CharField(max_length=150)
created_on = models.DateTimeField(auto_now_add=True, editable=False)
modified_on = models.DateTimeField(auto_now=True)
class SiteRatings(models.Model):
site = models.ForeignKey('Site', related_name='siterating', blank=True, null=True)
overall_rating = models.FloatField(blank=True, null=True)
plans_rating = models.FloatField(blank=True, null=True)
prices_rating = models.FloatField(blank=True, null=True)
design_rating = models.FloatField(blank=True, null=True)
support_rating = models.FloatField(blank=True, null=True)
def save(self, *args, **kwargs):
self.overall_rating = (self.plans_rating + self.prices_rating + self.design_rating + self.support_rating)/4
super(SiteRatings, self).save(*args, **kwargs)
def __str__(self):
return self.site.name
My views
# views.py
def home(request):
print(user_language)
site_list = Site.objects.order_by('-date_launched')
return render_to_response('index.html', {'site_list': site_list}, RequestContext(request))
In template
# template
{% for site in site_list %}
<h4><span class="label label-info">{{ site.name }}</span></h4>
<h4><span class="label label-info">{{ site.siterating.overall_rating }}</span></h4>
{% endfor % }
The problem is that when I try to access {{ site.siterating.overall_rating }} nothing is being returned, I tried to change for {{ site.siterating.0.overall_rating }} and it is not displaying yet.
I solved my problem. First in models I created a method to get the site rating (thank you karthikr for your suggestion):
#models
class Site(models.Model):
name = models.CharField(max_length=75)
slug = models.SlugField(_('slug'), max_length=75, blank=True, null=True)
link = models.CharField(max_length=150)
created_on = models.DateTimeField(auto_now_add=True, editable=False)
modified_on = models.DateTimeField(auto_now=True)
def get_site_rating(self):
return self.siterating.filter(site = self)
After, I went to my template and used the class method that I had created:
{% for site in site_list %}
<h4><span class="label label-info">{{ site.name }}</span></h4>
<h4><span class="label label-info">{{ site.get_site_rating.0.overall_rating }}</span></h4>
{% endfor % }
Please, note that I used ...get_site_rating.0... just because in my case I have just 1 rating/site.
I get this error:
'Searches' object has no attribute 'object'. I am using the generic ListView and I iterate over object_list in template. That is where the error comes in. My view is simple. Just attaching the model. All the relevant code is here.
Thanks
urlpatterns:
urlpatterns = patterns('',
url(r'^create/$','customsearches.views.create_search' , name='create_search'),
url(r'^list/$', SearchListView.as_view(template_name='search_list.html'), name='search_list'),
)
my model:
class Searches(models.Model):
SELLER_CHOICES=(('OWNER','owner'),
('DEALER','dealer'),
('BOTH','both'), )
#search_id = models.IntegerField(primary_key=True)
user = models.ForeignKey(User)
make = models.CharField(max_length=100, blank=True)
model = models.CharField(max_length=100, blank=True)
keywords = models.CharField(max_length=100, blank=True)
max_price = models.IntegerField(blank=True, null=True)
min_price = models.IntegerField(blank=True, null=True)
max_year = models.IntegerField(blank=True, null=True)
min_year = models.IntegerField(blank=True, null=True)
pic_only = models.NullBooleanField()
search_title_only = models.NullBooleanField()
owner_dealer_all = models.CharField(max_length=10,choices=SELLER_CHOICES,verbose_name='owner/dealer')
class Meta:
#managed = False
db_table = 'Searches'
verbose_name_plural = "Searches"
def __unicode__(self):
return "%s %s %s-%s" %(self.make,self.model,self.max_year,self.min_year)
def get_absolute_url(self):
return reverse('postings.views.detail',args=[model_to_dict(self.object)])
view:
class SearchListView(ListView):
model=Searches
template:
{% extends "base.html" %}
{% block content %}
{% for obj in object_list %}
<p>{{ obj }}</p>
{% endfor %}
{% endblock %}
The problem is on the line:
return reverse('postings.views.detail',args=[model_to_dict(self.object)])
Searches model doesn't really have an object attribute.
model_to_dict() needs a model instance:
model_to_dict(self)
Hope that helps.