How to solve url parameter problem in Django? - python

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'),

Related

How to hide or modify <pk> in url in Django app?

In my url.py I have:
path('gpd/<pk>/', views.gpd, name='gpd'),
my view.py looks like:
#login_required(login_url='login')
def gpd(request,pk):
current_gpd = get_gpd(pk)
context = {'current_gpd ':current_gpd ,
'pk':pk, }
return render(request, 'app/gpd/gpd_form.html', context)
def get_gpd(id):
return GPD.objects.get(id=id)
I have noticed, that when my logined user change manually pk - then he has an access to page with another pk. How to prevent it?
my GPG model:
class GPD(models.Model):
id = models.AutoField(primary_key=True)
employee = models.ForeignKey(Employee, verbose_name='Employee', on_delete = models.CASCADE, related_name='+')
class Employee(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30, verbose_name='Name')
def get_gpd(id,user):
return GPD.objects.get(id=id, employee=user)
so pass in the request.user

How to display Django BooleanFields selected true in template?

I created a model object.
This object has several boolean fields.
# models.py
class TeamCharacteristic(models.Model):
team = models.ForeignKey('Teams',on_delete=models.CASCADE)
power1 = models.BooleanField(null=True, blank=True)
power2 = models.BooleanField(null=True, blank=True)
power3 = models.BooleanField(null=True, blank=True)
power4 = models.BooleanField(null=True, blank=True)
power5 = models.BooleanField(null=True, blank=True)
class Meta:
verbose_name = 'Team style'
verbose_name_plural = 'Teams style'
def __str__(self):
return "{} 's style".format(
self.team,
)
Some of them are right and others are wrong.
I want to show only the fields that have the correct value in the template.
How can I do this in a shorter way instead of checking each field individually?
# views.py
from django.shortcuts import render, get_object_or_404
from .models import Matches
from denemee.apps.home.models import TeamCharacteristic
def matches_details(request, page_id=None, team=None, **kwargs):
m_detail = get_object_or_404(Matches, id=page_id)
home_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.h_team)
away_team_chr = get_object_or_404(TeamCharacteristic, team=m_detail.a_team)
payload = {
'm_detail': m_detail,
'home_team_chr': home_team_chr,
'away_team_chr': away_team_chr
}
return render(request, 'match_detail.html', payload)
You can send your home_team_chr and home_team_chras serialized objects and then iterate over the fields and check for the True values in booleans.
Check out this answer for more details.

why i cant use category detailview ? if use it get 404 in django?

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.

DJango CreateView not setting DB Key with Class-Based Views

I am using CreateView from DJango to save data to the DB. To do this, I am following the instructions here: Form handling with class-based views
According to my understanding, after the data is saved to the DB, the control is to be passed to a type of "success screen" - in this case, for my scenario, control is to be passed to a "details page". The details page is represented by the following URL:
url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(),
name='owner-contact-details'),
Below (in the class Mstrstoreheadcontact) the "details page" is being called by the get_absolute_url function (which is part of the Mstrstoreheadcontact model)
from the models.py file
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True, default=0)
genderid = models.BigIntegerField(blank=True, null=True, default=0)
firstname = models.CharField(max_length=20, blank=True, null=True)
lastname = models.CharField(max_length=20, blank=True, null=True)
officephoneno = models.CharField(max_length=20, blank=True, null=True)
cellphoneno = models.CharField(max_length=20, blank=True, null=True)
class Meta:
managed = False
db_table = 'MstrStoreHeadContact'
def get_absolute_url(self):
return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid})
For me the code: return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid} is supposed to take the control to the "details page" that will display the new record that has been added to the DB.
The problem
When the code above is executed, the variable self.contactid is set to 0. See below:
This results in the following URL to be placed in the address bar:
http://127.0.0.1:8000/masterdata/owner/0/contact/details
Because of the "0", this leads to a 404 error. In the DB, the value is set - for example to 10.
Again, the data saves to the DB JUST FINE- there is no problem with
this part. The problem lies with what happens AFTER the data is saved
to the DB.
Below are some entries from the urls.py file
from the urls.py file
url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(),
name='owner-contact-details'),
url(r'^owner/(?P<tenantid>[0-9]+)/contacts/add/$', views.MstrstoreheadcontactCreateView.as_view(),
name='owner-contact-add'),
from the views.py file
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
contact = form.save(commit=False)
contact.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
return super(MstrstoreheadcontactCreateView, self).form_valid(form)
It seems like the code is not getting the data back from the DB properly (after the data has been saved). What can I do to fix the problem?
TIA
Well, thank goodness for debuggers. The following changes resolved all the problems for me :-)
views.py
class MstrstoreheadcontactCreateView( CreateView ):
model = Mstrstoreheadcontact
fields = [ 'firstname', 'lastname', 'genderid', 'officephoneno', 'cellphoneno']
def form_valid(self, form):
form.instance.tenantid = Mstrauthowner.objects.get(tenantid=self.kwargs['tenantid'])
return super(MstrstoreheadcontactCreateView, self).form_valid(form)
models.py
class Mstrstoreheadcontact(models.Model):
tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True)
contactid = models.BigIntegerField(primary_key=True, default=0)
[... snip ..]
def get_absolute_url(self):
[... snip ...]
return reverse('masterdata:owner-contact-details', kwargs={'pk': self.tenantid.pk})

django model inheritance & casting to subtype in a view

It's a sort of cms type application
I have an article model and some specializations in models.py
class Article(models.Model):
foo = models.CharField(max_length=50)
bar = models.CharField(max_length=100,blank=True)
DISPLAY_CHOICES = (
('N', 'None'),
('C','Carousel'),
('M','Marketing'),
('F','Featurette')
)
display = models.CharField(max_length=1, choices = DISPLAY_CHOICES)
def __unicode__(self):
return self.title
class Artist(Article):
website = models.URLField(max_length=200,blank=True)
class Venue(Article):
location = models.CharField(max_length=150)
map_link = models.URLField(max_length=200,blank=True)
class Event(Article):
time = models.DateTimeField()
venue = models.ForeignKey(Venue)
performers = models.ManyToManyField(Artist)
I want to render these in different ways depending on the value of article.display but when I call
articles.objects.all()
I still need the extra attributes form the subclasses so I wrote
#views.py
def castToSubClass(article):
try:
return Artist.objects.get(article_ptr_id = article.id)
except:
try:
return Event.objects.get(article_ptr_id = article.id)
except:
try:
return Venue.objects.get(article_ptr_id = article.id)
except:
return article
def index(request):
carousel = [castToSubClass(article) for article in Article.objects.filter(display='C']
marketing = [castToSubClass(article) for article in Article.objects.filter(display='M'[:3]]
featurettes = [castToSubClass(article) for article in Article.objects.filter(display='F']
return render_to_response('frontpage.html',
{
'carousel': carousel,
'marketing':marketing,
'featurettes': featurettes
})
to turn them all in the appropriate subclass object, this apart from seeming clunky seems to mean I'm hitting the database twice for every (or nearly every) item in the queryset.
Is there a way to do this in the initial calls to the manager instead?
Thanks.
Use one model to store everything, and add a field to distinguish the article type, so that you can render different look for every type combine with display in the template(Like tumblr do).
class Article(models.Model):
foo = models.CharField(max_length=50)
bar = models.CharField(max_length=100,blank=True)
DISPLAY_CHOICES = (
('N', 'None'),
('C','Carousel'),
('M','Marketing'),
('F','Featurette')
)
display = models.CharField(max_length=1, choices = DISPLAY_CHOICES)
ARTICLE_TYPE_CHOICES = (
('artist', 'Artist'),
('venue', 'Venue'),
('event', 'Event'),
)
type = models.CharField(max_length=32, choices = ARTICLE_TYPE_CHOICES)
website = models.URLField(max_length=200,blank=True, null=True)
location = models.CharField(max_length=150, blank=True, null=True)
map_link = models.URLField(max_length=200,blank=True, null=True)
time = models.DateTimeField(null=True)
venue = models.ForeignKey('self', null=True)
performers = models.ManyToManyField('self', null=True)
def __unicode__(self):
return self.title
#views.py
def index(request):
carousel = Article.objects.filter(display='C')
marketing = Article.objects.filter(display='M')
featurettes = Article.objects.filter(display='F')
return render_to_response('frontpage.html',{'carousel': carousel, 'marketing':marketing, 'featurettes': featurettes})

Categories

Resources