django inability to find blog url while rendering the html page - python

I am newbie to django. I am trying to develop blog app in django.
I trying to render my fetched data into html but unable to do it for the following code
for which it is printing no blog found even data is being fetched properly.
This is my views.py
def blogpost(request):
latest_blog_list = BlogPost.objects.order_by('-pub_date')[:5]
print "" + str(latest_blog_list)
context = {'latest_poll_list' : latest_blog_list}
print "" + str(context)
#I can see the data is being fetched properly
return render(request,'polls/blogPostlist.html',context)
my blogPostlist.html
{% if latest_blog_list %}
<ul>
{% for blogpost in latest_blog_list %}
<li> <a href="/blog/{{ blogpost.slug }}"> blogpost.title </li>
{% endfor %}
</ul>
{% else %}
<p> test No blog avilable</p>
{% endif %}
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=255)
description = models.CharField(max_length=255)
post = models.TextField()
#media_file = models.ImageField(upload="")
pub_date = models.DateTimeField()
visit_count = models.IntegerField(default=0)
slug = models.SlugField(unique=True, max_length=255)
published = models.BooleanField(default=True)
tag = models.ManyToManyField(BlogTag)
catagory = models.ManyToManyField(BlogCategory)
def __unicode__(self):
return u'%s' % self.slug
class Meta:
ordering = ["pub_date"]
Along with that if I want to get title and slug for the blog, how to do it?

The context key name is wrong:
context = {'latest_poll_list' : latest_blog_list}
Instead it should be:
context = {'latest_blog_list' : latest_blog_list}

Related

How to pass parameter in current url to an html template in Django 3

I have:
Movie Model
class Movie(models.Model):
title = models.CharField(max_length=255)
synopsis = models.TextField()
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('movie_detail', args=[str(self.id)])
Discussion Model
class Discussion(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
movie = models.ForeignKey(
Movie,
on_delete=models.CASCADE,
related_name='discussion',
)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('discussion_detail', args=[str(self.movie.id), str(self.id)])
DiscussionListView
class DiscussionListView(LoginRequiredMixin, ListView):
model = Discussion
template_name = 'discussion_list.html'
login_url = 'login'
And I also have discussion_list.html
Here is what I want:
I’m in the url /article/1/discussion/. The integer 1 is a movie_pk because the url is defined as /article/<int:movie_pk>/discussion/ which in this case refer to the priority key of a Movie Model, for example StarWars I. This is a page of list of discussion titles related to this movie. (This has already been achieved)
There is a button “New” where, if i click on it, I will be directed to /article/1/discussion/new. There, I can create a new discussion. (The feature I want to add)
However:
In discussion_list.html, we require the url tag {% url discussion_new %} to have a parameter since discussion_new is defined as /article/<int:movie_pk>/discussion/new
Thus:
How to pass the movie_pk from the current url, then to DiscussionListView, then to the template discussion_list.html?
In detail view's template, you can send the object.id as parameter of url:
#template
{% url "discussion_new" movie_pk=object.pk %}
If you are in a List View template then probably you have a loop to go through all object_list. There you can implement like this:
{% for object in object_list %}
{% url "discussion_new" movie_pk=object.pk %}
{% endfor %}
{% url discussion_new %}
to
{% url "discussion_new" pk=movie_pk%}
And in list
{% for m in movie_list %}
{% url "discussion_new" movie_pk=m.pk %}
{% endfor %}

When I submit this form, neither data is saved onto database nor giving any error in my django project

models.py
here is my model
class Load_post(models.Model):
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False , blank=False , unique=True)
receiver_name = models.CharField(max_length=150)
sending_item = models.CharField(max_length=150)
weight = models.CharField(max_length=150)
metric_unit = models.CharField(max_length=30, default='SOME STRING')
quantity = models.PositiveIntegerField(default=1)
requested_shiiping_price = models.PositiveIntegerField()
pick_up_time = models.DateField()
drop_time = models.DateField()
paid_by = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now=True)
published_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
def publish(self):
self.published_date = timezone.now()
self.save()
def get_absolute_url(self):
return reverse('local')
class Meta:
ordering = ["-created_at"]
unique_together = ["sender_name", "receiver_name"]
please check the phone number
forms.py
this is form.py
class Loader_post_form(forms.ModelForm):
phone_number = PhoneNumberField()
metric_unit = forms.ChoiceField(choices=UNIT, required=True)
class Meta:
model = Load_post
fields = ("pick_up_station", "destination_station",
"sender_name", "phone_number", "receiver_name",
"sending_item","image_of_load","weight","metric_unit",
"quantity","requested_shiiping_price","pick_up_time",
"drop_time","paid_by")
views.py
This is my views.py
absolute URL used in models already
class Loader_post_view(CreateView, LoginRequiredMixin):
login_url = 'Driver/login/'
form_class = forms.Loader_post_form
model = Loader_Signup
template_name = "Driver/post.html"
def form_valid(self,form):
form.instance.user = self.request.user
form.save()
return super(Loader_post_view,self).form_valid(form)
post.html
this is html page (template)
{% extends "Driver/base.html" %}
{% block content %}
<h1>create a post</h1>
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
{% endblock content %}
this is html code
how to add it to the database
and I cannot see any error in my forms
thank you
am working on driver and client-side project
From what I see you html template cannot submit the form because you ae missing the <form> tags - if you do not have them hidden in your base.html.
Your html template should be something like this:
{% extends "Driver/base.html" %}
{% block content %}
<h1>create a post</h1>
<form method="POST">
{% csrf_token %}
{{form}}
<button type="submit">submit</button>
</form>
{% endblock content %}
The {{ form }} renders the form with all the inputs but does not create the tags needed for html forms.
In addition there are some other errors in the code you posted.
In your view the model you defined is called Loader_Signup, however the model you posted is Load_post. Either you posted the wrong model or you declared the wrong model in your view.
In your form one field is called image_of_load, however, this field is not part of you model.
In your model you have got a field called phone_number, you are defining a field with the same name in your form. The field in your form has got no connection to your model so take it out.
Unfortunately you are not providing any details about your PhoneNumberField so this cannot be checked.

nested loop in django template is not showing correct output

I am trying to print brand and it's links and I am using nested loops but it is not showing correct output
here is my code
{% for brand_report in brand_reports %}
<h1> REPORT for Brand: {{ brand_report.brand.name }}</h1>
{% for link in brand_report.links.all %}
<h3>link:</h3>{{link.url}}
{% endfor %}
{% endfor %}
Desired output is
REPORT for Brand: SizCom
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
REPORT for Brand: SizCom
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
But i am getting output like this
REPORT for Brand: SizCom
REPORT for Brand: SizCom
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
Don't know what i am doing wrong
model:
class Brand(models.Model):
"""For the brand"""
name = models.CharField(max_length=500)
description = models.TextField(blank=True, null=True)
context = models.ManyToManyField(Context, blank=True)
variation = models.ManyToManyField('BrandVariation', blank=True, related_name='brand')
status = models.BooleanField(default=False)
def __str__(self):
return self.name
class ResultLink(models.Model):
"""for results"""
url = models.URLField(max_length=1000)
country = models.ForeignKey(Country, blank=True, null=True)
parent_site = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True)
variation = models.ForeignKey(BrandVariation, on_delete=models.CASCADE, blank=True, null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True, related_name='link')
date = models.DateField(auto_now_add=True)
def __str__(self):
return "%s" % self.url
class BrandReport(TimeStampedModel):
""""""
brand = models.ForeignKey(Brand, related_name='counterfeit_report')
links = models.ManyToManyField(ResultLink, blank=True)
class Meta:
verbose_name = "Brand Report"
Views :
def view(request,brands):
template_path = 'profile_brand_report.html'
brand_reports = BrandReport.objects.filter(brand__id__in=brands)
context = {'brand_reports': brand_reports}
html = render_to_string(template_path, context)
I recreated your project. The only thing you missed providing was your view. So I suppose that is where your problem is. Here is my view:
def demoview(request):
objs = BrandReport.objects.all()
c = {
"brand_reports": objs,
}
return render(request, "blog/demoview.html", c)
And here is my template:
{% for brand_report in brand_reports %}
<h1> REPORT for Brand: {{ brand_report.brand.name }}</h1>
{% for link in brand_report.links.all %}
<h3>link:</h3>{{link.url}}
{% endfor %}
{% endfor %}
And my result is exactly how you have desired. Please check your view.
You obviously have a first BrandReport without any related link and a second BrandReport with two related links - check your database.
FWIW, I actually don't get what your BrandReport model is since you already have a foreignkey to Brand in ResultLink. Your BrandReport model is not only redundant (as far as we can tell) but also brittle since it allows to relate any ReportLink to any Brand without respecting the ReportLink.brand constraint.

How to loop within a loop in django while passing multiple context

I having trouble trying to access the foreign key element from my template. I am trying to pass multiple contexts using class view like this:
class HomeView(ListView):
template_name = "homepage/home.html"
queryset = Author.objects.all()
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['author_links'] = Author_link.objects.all()
context['categories'] = Category.objects.all()
context['extra_links'] = Extra_link.objects.all()
context['poems'] = Poem.objects.all()
return context
my models.py file:
class Author(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Author_link(models.Model):
url_text = models.CharField(max_length=100)
url = models.CharField(max_length=200)
author = models.ForeignKey(Author)
def __str__(self):
return self.url_text
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Extra_link(models.Model):
url_text = models.CharField(max_length=100)
url = models.CharField(max_length=200)
category = models.ForeignKey(Category)
def __str__(self):
return self.url_text
however when I am trying to loop through the context I can't seem to access the foreign key of each item:
{% for author in object_list %}
<li class = "collection-item">
<ul class="collapsible" data-collapsible="accordion">
<li>
<div class="collapsible-header">{{author.name}}</div>
<div class="collapsible-body">
{% for item in author.item_set.all %}
<p>{{item.url}}</p>
{% endfor %}
</div>
</li>
</ul>
</li>
{% endfor %}
what I am trying to do is loop through the authors and at the same time under each author loop through the urls that are associated with each author.
where you have
{% for item in author.item_set.all %}
<p>{{item.url}}</p>
{% endfor %}
you should have something like
{% for item in author.author_link_set.all %}
<p>{{item.url}}</p>
{% endfor %}
This manager (author.author_link_set) is added to each author because there is a foreign key from Author_link to Author.
side note: the convention for class names in python is Pascal Case, e.g., AuthorLink not Author_link. I mention this because I'm not 100% sure if I have correctly guessed the name of the reverse relation on author (it might be author.authorlink_set, I've never seen an underscore in a model name - django may do something special in that case)

Can I use filter() in django template?

What I'd like to do is using filter() in django template like belows:
models.py
from django.db import models
From Django. utils import Timezone
class Category(models.Model):
url = models.CharField(max_length=200)
site_name = models.CharField(max_length=50)
board_name = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField(blank=True)
category = models.ForeignKey(Category)
created_date = models.DateField(blank=True, null=True)
crawl_date = models.DateTimeField()
num_of_comments = models.PositiveSmallIntegerField(default=0, blank=True, null=True)
notice = models.BooleanField(default=False)
views.py
def post_list(request, site_name=None, page=1):
categories = Category.objects.filter(site_name=site_name.upper()).order_by('board_name')
return render(request, 'SNU/post_list.html', {'site_name':site_name.upper(), 'categories':categories})
post_list.html
{% for category in categories %}
<p> {{category}} </p>
{% for post in category.post_set.filter(notice=True) %}
<li>{{ post.title }}</li>
{% endfor %}
{% endfor %}
In post_list.html, {% for post in category.post_set.filter(notice=True) %} occurs error. Only category.post_set.all is the one that I can use in template?
You can do it on view level by
def post_list(request, site_name=None, page=1):
categories = Category.objects.filter(site_name=site_name.upper(),
notice=True).order_by('board_name')
return render(request, 'SNU/post_list.html',{'site_name':site_name.upper(),
'categories':categories})
If for some reason you need all categories, not just those having notice = True,
add one more query without notice=True in filter and pass it in the dictionary.
Alternatively, you can create custom tag and provide filter - see https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

Categories