I am sure I have made a rookie mistake somewhere down here.
So I have a details page for a particular link. Suppose I have list of incubators on my page, and if I click on one of them, I want to show its details. I am sure this can be done by using primary key but I keep getting errors.
models.py
class Incubators(models.Model):
# I have made all the required imports
incubator_name = models.CharField(max_length=30)
owner = models.CharField(max_length=30)
city_location = models.CharField(max_length=30)
description = models.TextField(max_length=100)
logo = models.FileField()
verify = models.BooleanField(default = False)
def get_absolute_url(self):
return reverse('main:details', kwargs={'pk': self.pk})
def __str__(self): # Displays the following stuff when a query is made
return self.incubator_name + '-' + self.owner
class Details(models.Model):
incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE)
inc_name = models.CharField(max_length = 30)
inc_img = models.FileField()
inc_details = models.TextField(max_length= 2500)
inc_address = models.TextField(max_length = 600, default = "Address")
inc_doc = models.FileField()
inc_policy = models.FileField()
def __str__(self):
return self.inc_name
views.py
def details(request, incubator_id):
inc = get_object_or_404(Incubators, pk = incubator_id)
return render(request, 'main/details.html', {'inc': inc})
This is my urls.py but I'm sure there's no error here:
url(r'^incubators/(?P<pk>[0-9]+)', views.details, name = 'details'),
Can you explain a little why I am getting this error?
TypeError at /incubators/9
details() got an unexpected keyword argument 'pk'
Request Method: GET
Request URL: http://127.0.0.1:8000/incubators/9
Django Version: 1.11.3
Exception Type: TypeError
Exception Value:
details() got an unexpected keyword argument 'pk'
In your URL patterns, you're calling the variable "pk" but in your view you're calling it incubator_id
To fix this, change your URL pattern from:
url(r'^incubators/(?P<pk>[0-9]+)', views.details, name = 'details'),
to
url(r'^incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'),
Related
I have a strange problem.
I have a page that uses url parameters. Users can reach this site based on their project id and name and the group(csoport) name that stored in three models. This is a link for an example page:
/performance/monthlyfeedback/{{ request.user.profile.csoport }}
That link works fine if the name of the csoport is a number. If it is any kind of a text it gives me 404 error that I can't figure out why.
models.py
class Profile(models.Model):
def __str__(self):
return str(self.user)
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
csoport = models.CharField(max_length=100, null=True, blank=True)
class Projekt_perf(models.Model):
def __str__(self):
return str(self.projekt_perf)
projekt_perf = models.CharField(max_length=250)
jogosult_01_perf = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
class Performance_profile(models.Model):
def __str__(self):
return str(self.user_name)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
projekt_perf = models.ForeignKey(Projekt_perf,on_delete=models.CASCADE)
views.py
I am using raw query in the views.
def obj_results(request, projekt_perf_id, projekt_perf, user_name_id, csoport):
person = Projekt_perf.objects.raw('SELECT * FROM performance_projekt_perf INNER JOIN performance_performance_profile ON performance_projekt_perf.id = performance_performance_profile.projekt_perf_id INNER JOIN stressz_profile ON performance_performance_profile.user_name_id = stressz_profile.user_id WHERE performance_projekt_perf.id = %s AND projekt_perf = %s AND stressz_profile.user_name_id = %s AND stressz_profile.csoport = %s',[projekt_perf_id, projekt_perf, user_name_id, csoport])
context = {
'person': person,
}
return render(request, 'performance/obj-results.html', context)
urls.py
app_name = 'performance'
urlpatterns = [
path('monthlyfeedback/<int:projekt_perf_id>', login_required(views.Performance_test), name='performance_feedback'),
path('list/<int:projekt_perf_id>/<projekt_perf>', login_required(views.list), name='performance_list'),
path('obj-results/<int:projekt_perf_id>/<projekt_perf>/<int:user_name_id>/<csoport>', login_required(views.obj_results), name='obj_results'),
]
What am I doing wrong?
In urls.py:
path('monthlyfeedback/<int:projekt_perf_id>'
You have defined the “project_perf_id” as int. Change it.
Can you try with <str:csoport> but I reccomend you to use slugs.
path('obj-results/<int:projekt_perf_id>/<projekt_perf>/<int:user_name_id>/<str:csoport>', login_required(views.obj_results), name='obj_results'),
I have a function in my models.py that adds the news I pass to it via a URL using OpenGraph. This process works fine, but there are some websites that give me an error, how can I use a try except to control this error and the application does not crash?
When the error occurs, I would like the application in the admin panel to return me to the same place where it was before, but indicating the error.
Best regards and thank you very much!
My models.py:
class Post(models.Model):
title = models.CharField(max_length=200, verbose_name="Título", null=True, blank=True)
content = RichTextField(verbose_name="Contenido", null=True, blank=True)
published = models.DateTimeField(verbose_name="Fecha de publicación", default=now, null=True, blank=True)
image = models.ImageField(verbose_name="Imagen", upload_to="blog", null=True, blank=True)
author = models.ForeignKey(UserManegement, verbose_name="Autor", on_delete=models.CASCADE)
categories = models.ManyToManyField(Category, verbose_name="Categorias", related_name="get_posts")
url_web = models.URLField(verbose_name="URL", null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creacion')
updated = models.DateTimeField(auto_now=True, verbose_name='Fecha de ediccion')
class Meta:
verbose_name = "entrada"
verbose_name_plural = "entradas"
ordering = ['-created']
def __str__(self):
return self.title
The function in which I want to insert the try except. It is in the same models.py:
#receiver(pre_save, sender=Post)
def url_processor(sender, instance, *args, **kwargs):
if instance.url_web:
title, description, image = web_preview(instance.url_web)
instance.title = title
instance.content = description
path = 'blog/' + uuid.uuid4().hex + '.png'
instance.image = path
img_data = requests.get(image).content
with open('media/' + path, 'wb') as handler:
handler.write(img_data)
else:
return
This is the error when entering this url: Web error
requests.exceptions.MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?
The error from what I have been seeing, is due to the 21 of the URL, which the Python request library in version 3.6.10 takes it as an error. It only happens with URLs that have some number in their domain.
Instead of signals use this code in model clean method.
from django.core.exceptions import ValidationError
Class YourModel(models.Model):
# fields
def clean(self, *args, **kwargs):
try:
# your signal code here
except:
raise ValidationError('Your message')
hello im new to django i am making a blog site i am getting an error when i try to acces my blog
my code:
views.py:
from django.http import request
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from .models import Item, Blog
# Create your views here.
class BlogView(ListView):
model = Blog
template_name = "main/blog.html"
context_object_name = "blog"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
search_input = self.request.GET.get('search') or ''
if search_input:
context['blog'] = context['blog'].filter(title__icontains=search_input)
return context
class Detail(DetailView):
model = Item
template_name = "main/item.html"
context_object_name = "items"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
obj = Item.objects.get()
context['items'] = Item.objects.filter(blog_id=obj.blog_id)
return context
models.py:
from django.db import models
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=200)
image = models.ImageField(null=True, blank=True)
created = models.DateField(auto_now_add=True, null=True)
def __str__(self):
return self.title
class Meta:
ordering = ['created']
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ""
return url
class Item(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(max_length=1000)
image = models.ImageField(null=True, blank=True)
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
def __str__(self):
return self.title
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ""
return url
any help would be appreciated on this error:
MultipleObjectsReturned at /detail/2/
get() returned more than one Item -- it returned 2!
Request Method: GET
Request URL: http://127.0.0.1:5000/detail/2/
Django Version: 3.2
Exception Type: MultipleObjectsReturned
Exception Value:
get() returned more than one Item -- it returned 2!
Exception Location: /home/moeez/.local/lib/python3.8/site-packages/django/db/models/query.py, line 439, in get
Python Executable: /usr/bin/python3
Python Version: 3.8.5
Python Path:
['/home/moeez/Python Projects/blogsite',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/moeez/.local/lib/python3.8/site-packages',
'/usr/local/lib/python3.8/dist-packages',
'/usr/local/lib/python3.8/dist-packages/buildozer-1.2.0.dev0-py3.8.egg',
'/usr/local/lib/python3.8/dist-packages/virtualenv-20.4.3-py3.8.egg',
'/usr/local/lib/python3.8/dist-packages/sh-1.14.1-py3.8.egg',
'/usr/local/lib/python3.8/dist-packages/filelock-3.0.12-py3.8.egg',
'/usr/local/lib/python3.8/dist-packages/distlib-0.3.1-py3.8.egg',
'/usr/local/lib/python3.8/dist-packages/appdirs-1.4.4-py3.8.egg',
'/usr/lib/python3/dist-packages']
Server time: Wed, 12 May 2021 14:31:09 +0000
The problem is you are using Item.objects.get() with no arguments. You should use get the same way as filter, but get may return only one object, and filter may return a queryset.
For example:
obj = Item.objects.get(id=some_id)
You should use lookups that are guaranteed unique while using get method, such as the primary key or fields in a unique constraint if get() method returns more than one object, it raises a Model.MultipleObjectsReturned exception as in your case here Item.objects.get() finds more than 1 object and it raises an exception.
To handle this problem pass the pk captured from url to get method.You can access the same from kwargs dictionary with key named as 'pk'.
Change line in your code:
obj = Item.objects.get()
To :
obj = Item.objects.get(id=self.kwargs.get('pk'))
I want use category_slug or id_slug for detailview as productdetailview
and show all of product that category there but i don't know how do that
i used this views but i get errors 404. why is different between productdetailview and categorydetailview? could plz help me to solve this problem?
models.py
class Category(models.Model):
name = models.CharField(max_length=120,unique=True)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Brand(models.Model):
name = models.CharField(max_length=120,unique=True)
class Product(models.Model):
category = models.ManyToManyField(Category,blank=True)
brand = models.ForeignKey(Brand,on_delete=models.CASCADE)
car = models.ForeignKey(Car,on_delete=models.CASCADE)
title = models.CharField(max_length=120,unique=True)
slug = models.SlugField(unique=True)
description = models.TextField(max_length=10000)
price = models.DecimalField(max_digits=10,decimal_places=2)
stock = models.PositiveIntegerField()
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True,auto_now=False)
updated = models.DateTimeField(auto_now=True,auto_now_add=False)
defalut = models.ForeignKey(Category,related_name="defalut_category",blank=True,null=True,on_delete=models.CASCADE)
class Meta:
ordering = ['-timestamp']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('products:product_detail',kwargs={"slug":self.slug})
views.py
def ProductDetail(request,slug):
product = get_object_or_404(Product,slug=slug,active=True)
context = {
"product":product
}
template_name = "product_detail.html"
return render (request,template_name,context)
def CategoryDetail(request,category_slug):
category = get_object_or_404(Category,slug = category_slug)
product = Product.objects.filter(category=category)
context = {
'category':category,
'product': product
}
template_name ="category_detail.html"
return render(request,template_name,context)
urls.py
app_name ='category'
urlpatterns = [
path('category-list/',views.CategoryList,name="category_list" ),
re_path(r'^(?P<category_slug>[-\w]+)/$', views.CategoryDetail, name='category_detail'),
My error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/category/elctroinc/
Raised by: products.views.CategoryDetail
No Category matches the given query.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Problem was in category_slug as two friends said that #Manjo Jadhav ,#JPG
i used id instead of category_slug and it's working .
tnx for help friends.
I am using the get_absolute_url method to get the url for a dynamic query, however when the link is displayed, it only shows the first parameter and not the second in the get_absolute_url method. It only does this when I use the ForeignKey of the model as the first parameter. Below is the code.
class Topic(models.Model):
topic_id = models.AutoField(primary_key=True)
forum_id = models.ForeignKey(Forum)
topic_title = models.CharField(max_length=400)
topic_date_time = models.DateTimeField(auto_now_add=True)
topic_user_id = models.IntegerField()
topic_views = models.IntegerField(default=0)
topic_replies = models.IntegerField(default=0)
topic_is_locked = models.BooleanField(default=False)
topic_is_sticky = models.BooleanField(default=False)
def __unicode__(self):
return '%s' % _(u'self.topic_title')
def get_absolute_url(self):
**return '/forums/%i/%i/' % (self.forum_id, self.topic_id)**
How can I fix this? Thanks!
def get_absolute_url(self):
return '/forums/%s/%s/' % (str(self.forum_id.pk), self.topic_id)
edit: jerzyk comment mentions these other points:
using #permalink with get_absolute_url and reversing the url using the view and arguments so you don't have to hardcode the urls.
using _id instead of .pk
def get_absolute_url(self):
return '/forums/%s/%s/' % (self.forum_id_id, self.topic_id)