Can anyone explain me, why i get Post.CommentPost.None?
How to correct connect CommentPost with Posty in query? I need get {{posty.comments.user}} my result is Post.CommentPost.None
Here something about my models and functions.
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
test_wyswietlenia = models.IntegerField(default=0, null=True, blank=True)
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
VIEWS
tag = request.GET.get('tag')
if tag == None:
my_tag = Posty.objects.prefetch_related('comments')
my_view = Posty.objects.prefetch_related('my_wyswietlenia')
else:
my_tag = Posty.objects.filter(created_tags__tag=tag)
my_view = Posty.objects.prefetch_related('my_wyswietlenia')
TEMPLATES
{% for post in my_tag %}
{% if post.comments.last.user == None %}
<span class="forum_tag_author">Komentarz » Brak komentarza</span><br/>
<span class="forum_tag_author">Stworzony przez » {{post.author}} </span><hr/>
{% else %}
<span class="forum_tag_author">Komentarz » {{post.comments.last.content1}}</span><br/>
<span class="forum_tag_author">Odpowiadający » Dodany przez: {{post.comments.last.user}} </span><hr/>
{% endif %}
{% endfor %}
And this
{{post.comments}} give a request Post.CommentPost.None
What is problem? What i do bad?
You can use a Subquery expression [Django-doc] to obtain the latest content1 comment and author with:
from django.db.models import OuterRef, Subquery
last_comment = CommentPost.objects.filter(post=OuterRef('pk')).order_by('-date_posted')
my_tag = Posty.objects.annotate(
last_comment=Subquery(last_comment.values('content1')[:1]),
last_comment_user=Subquery(last_comment.values('user__name')[:1]),
last_comment_user_pk=Subquery(last_comment.values('user')[:1])
).prefetch_related('my_wyswietlenia')
The __name might be different, since it depends on the fields of you Profil model.
Then you can render the content and the last author with:
{% for post in my_tag %}
{{ post.last_comment }} by {{ post.last_coment_user }}
{% enfor %}
Related
I want to access the region of the user in my template:
{% if object.seller.profile.post_code %}{{ object.seller.profile.post_code }} {% endif %}{% if object.seller.profile.city%}{{ object.seller.profile.city }}<br/>{% endif %}
{% if object.seller.profile.region.name %}{{ object.seller.profile.region.name }}, {% endif %}{% if object.seller.profile.region.country.name %}{{ object.seller.profile.region.country.name }}{% endif %}
This is my model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics',
verbose_name='Profilbild')
post_code = models.CharField(max_length=5, blank=True, verbose_name='Postleitzahl')
region = models.ForeignKey(Region, on_delete=models.CASCADE,
null=True, blank=True, verbose_name='Region', help_text='Bundesland oder Kanton')
city = models.CharField(max_length=50, blank=True, verbose_name='Stadt')
street = models.CharField(max_length=50, blank=True, verbose_name='Straße')
class Region(models.Model):
name = models.CharField(max_length=30, verbose_name='Region', help_text='Bundesland oder Kanton', default='Berlin')
symbol = models.CharField(max_length=30, verbose_name='Region-Kürzel', default='BER')
country = models.ForeignKey('Country', on_delete=models.CASCADE, null=True,
verbose_name='Land', default=0)
class Country(models.Model):
name = models.CharField(max_length=30, verbose_name='Land', default='Deutschland')
symbol = models.CharField(max_length=4, verbose_name='Kürzel', default='DE')
But I don't want to force the user to enter their adress data. But if the ForeignKey-Fields are not filled I get
'NoneType' object has no attribute 'country'
Is there a more a elegant way than checking each field if it is filled in the views.py and adding it separately to the context?
Can add some shortcuts to your Profile model to help with this:
views.py:
class Profile(models.Model):
...
#property
def country_name(self):
return self.region.country.name if self.region and self.region.country else None
template.html:
...
<div> {{object.seller.profile.country_name }} </div>
I want to count how many Product variations available in each Market. For now I'm only able to count Product variations for each Distributor. I'm thinking about using 'add' built-in template tag to sum Product variation in each Distributor to solve this problem, but don't know how to implement this in template for loop. Or is there any better solution? I'm open for suggestions.
My 5 related models in Django:
class Market(models.Model, RecordStatus):
name = models.CharField(max_length=100)
class Country(models.Model):
market = models.ForeignKey(Market, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=100)
class Distributor(models.Model, RecordStatus):
headquarter = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=100, null=True, blank=True)
class Product(models.Model, RecordStatus):
video = models.URLField(verbose_name='Video URL', max_length=250, null=True, blank=True)
class ProductStock(models.Model):
distributor = models.ForeignKey(Distributor, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
stock = models.PositiveIntegerField(null=True, blank=True)
My views.py:
def market_list_view(request):
markets = Market.objects.all()
context = {
'market_list': markets,
}
return render(request, 'product_visualizers/market_list.html', context)
My current attempt on market_list.html template:
{% for market in market_list %}
<h3>{{market.name}}</h3>
<p>{% for country in market.country_set.all %}
{% for distributor in country.distributor_set.all %}
{{ distributor.productstock_set.all|length }} # should I write |add besides |length to sum the numbers?
{% endfor %}
{% endfor %}</p>
{% endfor %}
What should I code in the nested for inside the template?
You can use:
class Market(models.Model, RecordStatus):
name = models.CharField(max_length=100)
def get_product_variations(self):
return Product.objects.filter(productstock__distributor__country__market=self).count()
and for your template:
{% for market in market_list %}
<h3>{{market.name}}</h3>
<p>Product variations: {{ market.get_product_variations }}</p>
{% endfor %}
I have a case, where on my template view I would like to display list of all objects (Issues) and categories (Sprints). I already applied also another filtering to display Issues that belongs to particular Project.
I've managed so far to display Sprints and within each Sprint I am displaying list of issues. How can I apply additional filtering on issues, that only issues belongs to particular sprint will be displayed?
Final result should be to display list of all issues divided per sprint.
My code below:
#views.py
class ProjectBacklogView(DetailView):
model = Project
template_name = 'project-backlog.html'
context_object_name = 'backlog'
def get_context_data(self, **kwargs):
context = super(ProjectBacklogView, self).get_context_data(**kwargs)
context['project'] = Project.objects.all()
context['issue'] = Issue.objects.all().order_by('sprint')
# context['epic'] = Epic.objects.all()
# context['initiative'] = Initiative.objects.all()
context['sprint'] = Sprint.objects.all()
return context
# template.html
{% extends 'base-project.html' %}
{% block content %}
{% for sprint in backlog.sprint_set.all %}
<h4>{{ sprint.name }}</h4>
<div id="simpleList" class="list-group" style="margin-bottom: 2%;">
{% for issue in backlog.issue_set.all %}
<div class="list-group-item">
<div style="float:left;"><strong>{{ issue.title }}</strong></div>
<div style="float: right;"><i class="fas">{{ issue.remaining_estimate }}</i></div>
<br /><br /><hr style="border-top: dashed 1px;"></hr>
<div style="float: left;"><small>Assignee: <strong>{{ issue.assignee }}</strong></small></div>
<div style="float: right;"><small>Initiative: <strong>{{ issue.initiative }}</strong></small></div><br />
<div style="float: left;"><small>Priority: <strong>{{ issue.priority }}</strong></small></div>
<div style="float: right;"><small>Epic: <strong>{{ issue.epic }}</strong></small></div>
</div>
{% endfor %}
<br />
</div>
{% endfor %}
{% endblock %}
#models.py
class Project(models.Model):
PROJECT_TYPE = (
('SCR', 'Scrum'),
('KAN', 'Kanban'),
)
# slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
alias = models.CharField(max_length=8, primary_key=True)
name = models.CharField(max_length=160)
project_type = models.CharField(max_length=10, choices=PROJECT_TYPE, default="SCR")
lead = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
# Definicja nazwy modelu w Adminie Django
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('project-detail', args=[str(self.alias)])
class Sprint(models.Model):
# sprint_type = models.TextField(default='Sprint', editable=False)
name = models.CharField(max_length=32)
goal = models.TextField(null=True, blank=True)
start_date = models.DateField()
end_date = models.DateField()
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Issue(models.Model):
ISSUE_PRIORITY = (
('Critical', 'C'),
('High', 'H'),
('Medium', 'M'),
('Low', 'L'),
)
issue_type = models.TextField(default='Issue', editable=False)
issue_id = models.AutoField(primary_key=True)
# slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
description = models.TextField(null=True, blank=True)
initiative = models.ForeignKey(Initiative, on_delete=models.CASCADE, null=True, blank=True)
epic = models.ForeignKey(Epic, null=True, blank=True, on_delete=models.CASCADE)
sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, null=True, blank=True)
priority = models.CharField(max_length=8, choices=ISSUE_PRIORITY, default='Medium')
assignee = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='assignees', null=True, blank=True) # zczytywane z tabeli userów
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='authors') # zczytywane z tabeli userów
remaining_estimate = models.IntegerField(null=True, blank=True, default='0') # w minutach
time_logged = models.IntegerField(default='0') # w minutach
attachment = models.FileField(null=True, blank=True) # To Do - multiple files??
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('issue-detail', args=[str(self.issue_id)])
My issue is I don't know how to apply dynamically filter (based on field sprint) as sprints are listed in for loop
Django-haystack has examples of how to make one app searchable. We'll that is great!
However, when you have more than one app and each one is related to the User, how would you go about
having haystack (faceted) to allow you search for what you want. Let's say on all three of these models.
Example: Show me all male users who have a keyword of "experienced" in their description who also have
a skill with the name "Analyst" whose Info keywords contains "bla".
I googled with no result. So, I am looking at bringing few apps under the same search page.
class UserProfile(models.Model):
GENDER_MALE = 1
GENDER_FEMALE = 2
GENDER_CHOICES = (
(GENDER_MALE, 'Male'),
(GENDER_FEMALE, 'Female'),
)
user = models.OneToOneField(User, related_name="%(class)s", unique=True)
full_name = models.CharField(
_("Full name"),
max_length=200,
blank=True,
)
gender = models.IntegerField(
_('Gender'),
choices=GENDER_CHOICES,
blank=False,
null=True,
)
# common
country = CountryField(
_('Country'),
null=True,
blank=False,
)
# common
about = models.TextField(
_('About Me'),
blank=True,
validators=[MaxLengthValidator(400)],
)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __unicode__(self):
return u'%s' % (self.user.username)
class Skill(models.Model):
user = models.ForeignKey(
User,
related_name="%(class)s"
)
name = models.CharField(
_('Skill Name'),
max_length=70,
null=False
)
category = models.ForeignKey(
'self',
blank=True,
null=True
)
is_active = models.BooleanField(
default=True
)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __unicode__(self):
return u'%s' % (self.name)
class Info(models.Model):
user = models.ForeignKey(
User,
related_name="%(class)s",
null=False
)
description = models.TextField(
blank=False,
)
keywords = models.CharField(
blank=True,
null=True,
max_length=56,
)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
def __unicode__(self):
return u'%s' % self.title
I think if i am not wrong your question is to how to make facets work for multiple apps.
In url.py try something like
sqs = SearchQuerySet().facet('field1').facet('field2').facet('field3')
urlpatterns += patterns('haystack.views',
url(r'^$', FacetedSearchView(form_class=FacetedSearchForm, searchqueryset=sqs), name='haystack_search'),)
In search.html
{% if facets.fields.field1 %} {% for type1 in facets.fields.field1 %}
{{ type1.0 }} ({{ type1.1 }}) {% endfor %} {% else %}
No type1 facets.
{% endif %}
{% if facets.fields.field2 %} {% for author in facets.fields.field2 %}
{{ type2.0 }} ({{ type2.1 }}) {% endfor %} {% else %}
No type2 facets.
{% endif %}
{% if facets.fields.field3 %} {% for author in facets.fields.field3 %}
{{ type3.0 }} ({{ type3.1 }}) {% endfor %} {% else %}
No type3 facets.
{% endif %}
Your Apps should have individual search_index files .
Check the output of rebuild_index and update_index, whther indexing is done properly or not.
I've defined the following models:
class Topic(models.Model):
class Meta:
ordering = [
'title']
objects = models.Manager()
highlighted = HighlightedTopicManager()
highlight = models.BooleanField(
default=False,
help_text='Show this topic on the home page?',
db_index=True)
highlight_order = models.PositiveSmallIntegerField(
default=0,
help_text='In what order do you want this to be added on the home page?'\
' Leave blank for alphabetic order.',
db_index=True)
title = models.CharField(
max_length=2048,
db_index=True)
slug = models.SlugField(
max_length=128,
db_index=True)
excerpt = models.TextField(
null=True,
blank=True)
description = models.TextField()
def _get_content(self):
if self.excerpt:
return self.excerpt
return self.description
content = property(_get_content)
#models.permalink
def get_absolute_url(self):
return ('academic_projects_topic_detail', (), {'slug': self.slug})
def __unicode__(self):
return self.title
class Project(models.Model):
class Meta:
ordering = [
'topic',
'modified',
'created']
objects = models.Manager()
highlighted = HighlightedProjectManager()
highlight = models.BooleanField(
help_text='Highlight this in the projects\' main page?'\
' Only the most recently modified one will be displayed.')
redirect_to = models.URLField(
blank=True,
null=True,
help_text='Use this for old or extenal projects.')
short_title = models.CharField(
max_length=1024,
db_index=True)
slug = models.SlugField(
max_length=128,
db_index=True)
title = models.CharField(
max_length=2048,
db_index=True)
created = models.DateTimeField(
auto_now_add=True)
modified = models.DateTimeField(
auto_now=True)
excerpt = models.CharField(
max_length=1024,
null=True,
blank=True,
help_text='Concise description to show in the listing page.')
description = models.TextField(
null=True,
blank=True,
help_text='This content will be rendered right after the title.')
downloads = models.ManyToManyField(
Download,
null=True,
blank=True,
help_text='Downloadable files')
footer = models.TextField(
null=True,
blank=True,
help_text='This content will be rendered at the bottom of the page.')
people = models.ManyToManyField(
Person,
help_text='People involved in this project.',
related_name='projects')
organizations = models.ManyToManyField(
Organization,
help_text='Organizations involved other than the lab.',
blank=True,
null=True,
related_name='projects')
publications = models.ManyToManyField(
Publication,
blank=True,
null=True)
topic = models.ForeignKey(
Topic,
verbose_name=_('Main topic'),
help_text='This is the main topic.',
related_name='projects')
sponsors = models.ManyToManyField(
Sponsor,
blank=True,
null=True,
help_text='sponsored_projects')
related_topics = models.ManyToManyField(
Topic,
null=True,
blank=True,
help_text='Optional related topics.',
related_name='secondary_projects')
def __unicode__(self):
return self.short_title
#models.permalink
def get_absolute_url(self):
return ('academic_projects_project_detail', (), {'slug': self.slug})
And use the following template to produce this page (http://seclab.cs.ucsb.edu/academic/projects/):
{% extends "academic/project_base.html" %}
{% block content_title %}Projects{% endblock %}
{% block title %}Projects - {{block.super}}{% endblock %}
{% block content %}
{% regroup object_list|dictsort:"topic" by topic as topic_list %}
{% for topic in topic_list %}
<h2 id="{{ topic.grouper.slug }}">{{ topic.grouper }} #</h2>
{% for project in topic.list %}
<h3>{{ project }}</h3>
<p>{{ project.title }}</p>
{% endfor %}
{% endfor %}
{% endblock %}
The view behind this is a generic one, and invoked as:
url(r'^$',
cache_page(ListView.as_view(
queryset=Project.objects.order_by('topic'),
template_name='academic/project_list.html')),
name='academic_projects_project_list'),
So, Projects are already sorted by Topic. Unfortunately, this code yields to duplicate gorups and, sometimes, the groups change at each refresh (or, at least, they change when I reboot the server).
Any idea of why is this happening? The entire code, besides templates', resides here: https://bitbucket.org/phretor/django-academic/src/
The dictsort filter is only for lists of dicts, you don't need it at all here. Your template should read
{% regroup object_list by topic as topic_list %}