Why do I get either NoReverseMatch or FieldError - python

I am working on a project, and want to create a report on a film. (That it doesn´t exist) At the moment I only get error when I try to go to either film// or film//report. Can anybody help me?
When I try film//: NoReverseMatch; Reverse for 'film-report' with no arguments not found. 1 pattern(s) tried: ['film/(?P[0-9]+)/report$']
And film//report gives: FieldError; Unknown field(s) (reported) specified for Report
models.py
class Report(models.Model):
title = models.CharField(default="", max_length=100)
comment = models.TextField(default="")
reporter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Reporter")
# receiver = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name="Receiver"
# )
reports = models.ForeignKey(Film, on_delete=models.CASCADE)
def __str__(self): # pragma: no cover
return f"{self.reporter.username} reports {self.reports.title}"
urls.py
urlpatterns = [
path("", views.films_view, name="board-home"),
path("film/add", FilmAddView.as_view(), name="film-add"),
path("film/<int:pk>/", FilmDetailView.as_view(), name="film-detail"),
path("film/<int:pk>/report", FilmReport.as_view(), name="film-report")
]
views.py
class FilmReport(LoginRequiredMixin, UpdateView):
model = Report
fields = ["title", "reported"]
# def __str__(self):
# return self.title
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
This should be the page where I can click on "Report", and then be redirected to a report page.
film_detail.html
{% extends "board/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle film-img" src="/media/{{object.poster}}">
<!-- Mulighet for å ha en "add review"-knapp på siden der hvor filmene vises. -->
<i class="material-icons right">rate_review</i>add review
<i class="material-icons right">report</i>report
<!-- <a onclick="myFunction()" class="waves-effect waves-light red darken-4 btn"><i class="material-icons right">report</i>report</a>
<script>
function myFunction() {
var txt;
if (confirm("Are you sure you want to report this film?")) {
$("#inline2").fadeIn(300);
$(".overlay-fixed").fadeIn(300);
$(".fancybox-opened").fadeIn(300);
return false;
} else {}
}
</script> -->
<div class="media-body">
<h2 class="film-title">{{ object.title }}</h2>
<p class="film-plot">{{ object.plot }}</p>
</div>
</article>
{% endblock content %}

In your class FilmReport you can just take the fileds from your model Report.
The field "reported" does not exist. You should take "reporter" or "reports".
You can just try the urls you have specified, either film nor film/report are valid urls. You need to have at least one Film object in your database to get access to the url
film/1/report.

Related

ValueError at /category/economy/: Field 'id' expected a number but got 'economy'

I try to add new path and this happen "Field 'id' expected a number but got 'economy'."
in traceback the highlighted line is in the views.py file which i mentioned below.
category_posts = Post.objects.filter(category=cats)
I am sharing my files plz help me to get rid of the issue.
urls.py
urlpatterns = [
path('',views.allpost,name="allpost"),
path('search', views.search, name="search"),
path('contact/', views.contact, name="contact"),
path('success/', views.successView, name="success"),
path('category/<str:cats>/', views.CategoryView, name ="category"),
path('<int:blog_id>/',views.detail,name="detail"),
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
here i used str:cats, yet it shows "Field 'id' expected a number but got 'economy'."
views.py
def CategoryView(request, cats): # here cats is same which mentioned in dynamic url.
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
"category_posts = Post.objects.filter(category=cats)" this line of code shows in traceback
models.py
from django.db import models
class Category(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
title = models.CharField(max_length=255, verbose_name="Title")
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=
True, null=True)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
public_date = models.DateField(null=True)
public_time = models.TimeField(null=True,default="")
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category", null=True)
image = models.ImageField(upload_to='images/',null=True, blank=True)
body = models.TextField()
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ['public_date']
def summary(self):
return self.body[:100]
def pub_date(self):
return self.public_date.strftime('%b %e,%y')
# to give layout for time and date
def __str__(self):
return self.title
categories.html
{% extends 'base.html' %}
{%block content%}
<h1> Category: {{ cats }} </h1>
{% for post in category_posts %}
<div class="container mt-3">
<div class="row mb-2">
<div class="col-md-6">
<div class="card flex-md-row mb-4 box-shadow h-md-250">
<div class="card-body d-flex flex-column align-items-start">
<strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong>
<h3 class="mb-0">
<a class="text-dark" href="{% url 'detail' post.id %}">{{post.title}}</a>
</h3>
<div class="mb-1 text-muted">{{ post.public_date }}</div>
<p class="card-text mb-auto">{{ post.summary }}</p>
Continue reading
</div>
<img class="card-img-right flex-auto d-none d-md-block" data-src="holder.js/200x250?theme=thumb" alt="Thumbnail [200x250]" style="width: 200px; height: 250px;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20250%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_182c981dfc3%20text%20%7B%20fill%3A%23eceeef%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A13pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_182c981dfc3%22%3E%3Crect%20width%3D%22200%22%20height%3D%22250%22%20fill%3D%22%2355595c%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2256.20000076293945%22%20y%3D%22131%22%3EThumbnail%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<h2>Sorry this page does not exist....</h2>
{% endif %}
{%endblock%}
I am confused it demands. can someone help me to solve it plz.
Its because you are querying it wrong:
So instaed of doing this:
# views.py
def CategoryView(request, cats): # here cats is same which mentioned in dynamic url.
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
Try something with this query. I'm supposing you want to query all the posts of a specific category that will be coming from your URL.
from django.shortcuts import get_object_or_404
def CategoryView(request, cats):
# method 1
category_posts = Post.objects.filter(category__title=cats)
# method 2
category = Category.objects.get(title=cats)
category_posts = category.Category.all() # here .Category is the related_name you used in your Post model
# method 3:
category = get_object_or_404(Category, title=cats) # will raise 404 if no category found with the given title
category_posts = category.Category.all()
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
PS: When you don't know what your ForeignKey related_name should be. Then go for the plural name of the model. Like in the current case:
# models.py
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="posts", null=True)
This way we can query like this category_posts = category.posts.all()

django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)'

I am working on my project and the main idea is to add some items to the watchlist or "bookmark" some items:
when I render the page to see the watchlist that I add them by clicking on the "Add to watchlist button " Django give me this error:
NoReverseMatch at /watchlist/
Reverse for 'viewList' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9]+)$']
my code:
Model.py file
class Post(models.Model):
#data fields
title = models.CharField(max_length=64)
textarea = models.TextField()
#bid
price = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)
imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True)
creator = models.ForeignKey(User, on_delete=models.PROTECT)
date = models.DateTimeField(auto_now_add=True)
# for activated the Category
activate = models.BooleanField(default=True)
buyer = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="auctions_Post_creator")
############################### this is the watchers
watchers = models.ManyToManyField(User, blank=True, related_name='favorite')
def __str__(self):
return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}"
urls.py
urlpatterns =[
# Watchlist
path('Post/<int:id>/watchlist_post/change/<str:reverse_method>',
views.watchlist_post, name='watchlist_post'),
path('watchlist/', views.watchlist_list, name='watchlist_list')
path('Post/<int:id>', views.viewList, name='viewList'),
]
views.py
#start watchlist
def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
if listing.watchers.filter(id=request.user.id).exists():
is_watched = True
else:
is_watched = False
context = {
'listing': listing,
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'Bidform': BidForm(),
# IS_WATCHED method
'is_watched': is_watched
}
return render(request, 'auctions/item.html', context)
#login_required
def watchlist_post(requset, id, reverse_method):
listing = get_object_or_404(Post, id=id)
if listing.watchers.filter(id=requset.user.id).exists():
listing.watchers.remove(requset.user)
else:
listing.watchers.add(requset.user)
if reverse_method == "viewList":
return viewList(requset, id)
return HttpResponseRedirect(reverse(reverse_method))
#login_required
def watchlist_list(request):
user = requset.user
watchers_items = user.favorite.all()
context = {
'watchers_items': watchers_items
}
return render(requset, 'auctions/watchlist.html', context)
HTML FILE: (item.html) this file for showing the post for exapmple : (title/ description/ date etc..)
<!-- check to add to watchlist -->
<div class="col">
{% if is_watched %}
Remove To Watchlist
<!-- remove it -->
{% else %}
Add To Watchlist
{% endif %}
</div>
HTML FILE (layout.html) for adding a link to the navbar for the page
<li class="nav-item">
<a class="nav-link" href="{% url 'watchlist_list' %}">Watchlist</a>
</li>
HTML FILE(whitchlsit page)
{% for post in watchers_items %}
<div class="col-sm-4">
<div class="card my-2">
<img src="{{post.imageurl}}" class="img-fluid">
<div class="card-body">
<div class="text-center py-2">
<h5 class="card-title text-info">{{post.title}}</h5>
<p class="alert alert-info">{{post.textarea}}</p>
<ul class="list-group">
<li class="list-group-item list-group-item-info">category: {{post.category.name}}</li>
<li class="list-group-item list-group-item-info">Price: {{post.price}}$</li>
<li class="list-group-item list-group-item-info">Created by: {{post.creator}}</li>
</ul>
</div>
<!-- Buttons -->
<div class="row">
<div class="col">
View
</div>
</div>
</div>
<div class="card-footer">
<small class="text-muted">Created since:{{post.date}}</small>
</div>
</div>
{% endfor %}
The culprit of this problem is that you are calling "{% url 'viewList' listing.id %}" even though viewList does not exist in your urls.py.
So, you can create one like this:
path("some/path", views.some_func, name="viewList")
EDIT
As the error says, listing.id is empty ({% url 'viewList' listing.id %}). So, you might want to do post.id instead because you are looping with the name of post.

django view dont show anything

I'm working to create an event page in my Django work.
Although I wrote a code to obtain database data when I try to load the front page(from exhibition_view.html), just the exhibition.view_html loads and no article return and does not show in that page.
the weird thing is that seminar_view and exhibition_view are the same, and seminar_view does work!
I tried very much to solve the issue, but had no idea what is happening!
below is my code:
Model.py
from django.db import models
from django.utils import timezone
from tinymce.models import HTMLField
class EventType(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Meta:
verbose_name_plural = "Event Types"
def get_deleted_event_type():
return EventType.objects.get(name='no-category')
class Event(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
EVENT_CHOICES = (
('seminar', 'seminar'),
('exhibition', 'exhibition'),
)
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=250,
unique_for_date='publish', allow_unicode=True, unique=True)
body = HTMLField()
publish = models.DateTimeField(default=timezone.now)
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
events = models.ForeignKey(EventType, on_delete=models.SET(get_deleted_event_type))
event_type = models.CharField(max_length=15,
choices=EVENT_CHOICES,
default='seminar')
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
event_index = models.IntegerField()
class Meta:
ordering = ('-publish',)
verbose_name_plural = "Events"
def __str__(self):
return self.title
Views.py
from django.shortcuts import render
from .models import Event
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
def seminar_detail(request, slug):
seminars = Event.objects.get(slug=slug)
context = {
'seminars': seminars
}
return render(request, "seminar_detail.html", context)
def exhibition_detail(request, events, slug):
cr1 = Q(events='2')
cr2 = Q(slug=slug)
exhibitions = Event.objects.get(cr1 & cr2)
context = {
'exhibitions': exhibitions
}
return render(request, "exhibition_detail.html", context)
def seminar_view(request):
criterion1 = Q(status='published')
criterion2 = Q(event_type="seminar")
seminars = Event.objects.filter(criterion1 & criterion2).order_by('event_index')
context = {
'seminars': seminars
}
return render(request, "seminar_view.html", context)
def exhibition_view(request):
criterion3 = Q(status='published')
criterion4 = Q(event_type="exhibition")
exhibitions_view = Event.objects.filter(criterion3 & criterion4).order_by('event_index')
context = {
'exhibitions_view': exhibitions_view
}
return render(request, "exhibition_view.html", context)
exhibition_view.html
{% extends 'base.html' %}
{% load static %}
<head>
<title>{% block title %}exhibitions{% endblock %}</title>
</head>
{% block page_content %}
<div class="page" id="page-container" >
<div class="top-bread">
<div class="breadcrumbs">
<ul>
<li class="home">
home
<span>»</span>
</li>
<li class="socialvoice">
<strong>exhibitions</strong>
</li>
</ul>
</div>
</div>
</div>
<div class="page">
<div class="main-container col1-layout">
<div class="main">
<div class="col-main">
<div class="shopbybrand-list">
<div class="brands">
<ul class="col">
{% for myevent in exhibitions_view %}
<li class="box">
<span>
<a href="{% url 'events:exhibition_view' event.slug %}">
<b>
<h2>{{ myevent.title }}<br/>{{ myevent.created_on.date }}</h2>
</b>
</a>
</span>
<b>
<p>
<p style="text-align: justify;">{{ myevent.body | safe | slice:":400" }}</p>
</p>
<a class="button" href="{% url 'events:exhibition_view' myevent.slug %}">
<span>
<span>ادامه مطلب</span>
</span>
</a>
</b>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
</div>
</div><!-- END page -->
{% endblock %}
and my app urls.py:
from django.urls import path
from . import views
from django.urls import re_path
app_name = 'events'
urlpatterns = [
path('seminar/', views.seminar_view, name="seminar_view"),
path('exhibition/', views.exhibition_view, name="exhibition_view"),
re_path(r'seminar/(?P<slug>[-\w]+)/', views.seminar_detail, name="seminar_detail"),
re_path(r'exhibition/(?P<slug>[-\w]+)/$', views.exhibition_detail, name="exhibition_detail"),
]

Filtering many-to-one in Django template

Let's say I have these models:
class Profile(models.Model):
headline = models.CharField(max_length=200)
class ProfilePhoto(models.Model):
photo = models.ImageField(upload_to='profiles/photos')
owner = models.ForeignKey(Profile, related_name='photos', on_delete=models.CASCADE)
type_choices = (
('PR', 'Primary'),
('AD', 'Additional'),
)
type = models.CharField(max_length=2, choices=type_choices, default='AD')
and the following view:
def profiles(request):
# Retrieve all active profiles
profiles = Profile.objects.filter(status='AC').order_by('-updated_at')#.filter(photos__)
context = {'profiles': profiles}
return render(request, 'profiles.html', context)
and this in my template file:
{% for profile in profiles %}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-body">
<p>{{ profile.headline }}</p>
<img src="{{ MEDIA_URL }}profiles/thumbs/{{ profile.photos.first.photo }}">
</div>
</div>
</div>
{% endfor %}
Here I get one photo for each profile because of profile.photos.first.photo in the template but what I want instead is to select a single photo for each profile with the condition that it has a type of 'PR'. Any help would be appreciated.
You can use a model method. Something like this:
class Profile(models.Model):
headline = models.CharField(max_length=200)
#property
def primary_profile_photo(self):
primary_photo = self.photos.filter(type='PR').order_by('?').first()
return primary_photo.photo
That would get you a random (order_by='?') photo, with type PR, that you could then access as primary_profile_photo in the template.

Django: how to update model attribute through a view?

I have albums and songs. When at specific album page I want to add a song by clicking "Add Song" button and return to that album's page:
Album's page
The from opens fine and lets me input song title.
But when I click "Submit" it breaks with this exception:
Exception
Here is a portion of template code where form is called:
{% block body %}
<div class="container-fluid" style="position:relative; padding-left: 100px; padding-top: 50px;">
<img src="{{ album.album_logo.url }}" class="img-responsive" height="200" width="200">
<h1>{{ album.album_title }}</h1>
<h3>{{ album.artist }}</h3>
{% for song in album.song_set.all %}
{{ song.song_title }}
{% if song.is_favorite %}
<img src="http://vignette1.wikia.nocookie.net/defendersquest/images/1/17/Yellow_star_small.png/revision/latest?cb=20120430053933"
height="10" width="10"/>
{% endif %}
<br>
{% endfor %}
<a href="{% url 'music:song-add' album.pk %}">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add Song
</a>
</div>
{% endblock %}
Here is urls.py:
urlpatterns = [
# /music/
url(r'^$', views.IndexView.as_view(), name='index'), # "$" sign means nothing more was requested from user
# /music/<album_id>/ - here album_id is an ID of specific Album for example
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # this will look for numbers 0-9 in user request
#and map it to variable named 'album_id'. Plus sign emplies to look for one or more numbers
#^-sign implies begingin of reg. expression and $-implies the end of it.
# /music/album/add/
url(r'album/add/$', views.AlbumCreate.as_view(), name='album-add'),
# /music/album/add/
url(r'song/add/(?P<album_pk>[0-9]+)/$', views.SongCreate.as_view(), name='song-add'),
# /music/album/album_id/
url(r'album/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'),
# /music/album/album_id/delete/
url(r'album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete')
]
Here is views.py portion:
class SongCreate(CreateView):
model = Song
fields = ['song_title']
def form_valid(self, form):
form.instance.album.pk = self.request.GET.get('album_pk')
return super(SongCreate, self).form_valid(form)
and here is models.py:
class Album(models.Model):
# attributes/columns:
artist = models.CharField(max_length=250) #CharField is the info on type of info that var holds
album_title = models.CharField(max_length=500)
genre = models.CharField(max_length=100)
album_logo = models.FileField()
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.pk})
def __str__(self): #string representation of Album objects
return self.album_title + ' - ' + self.artist
class Song(models.Model):
#attributes/columns:
album = models.ForeignKey(Album, on_delete=models.CASCADE) #linking songs to Albums!!!
file_type = models.CharField(max_length=10)
song_title = models.CharField(max_length=250)
is_favorite = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('music:detail', kwargs={'pk': self.album.pk})
def __str__(self):
return self.song_title
You're not setting the related ForeignKey object correctly. You can access the pk of the related field using the hidden _id field of the related object in the model instance:
form.instance.album_id = self.request.GET.get('album_pk')

Categories