Django DetailView pk error: can't match the last one - python

My new to django. I am creating a simple model for my to do app in django. Here, I have used DetailView to get the details and using the int "pk". When I'm running my server the /task/1/ is working fine but when I'm running task/2/ to check the other task it is shwoing error.
My views.py:
views.py
My app urls.py:
urls.py
template of detailview
See, when I'm running task/1/ there's no error.

This means the query of PK 2 doesn't not exists maybe you have deleted it.
Try number 3 or 4 to check.
Try going to your admin page to find Pk of each row.

So, I found the solution. As mentioned in the above comment that I might have deleted my task. Yes, that was deleted and even if we delete our task, the new task will not get the pk number that was assigned to the previous one. So, instead, if we'll use pk as the larger number than the previous number we won't get the error.

Related

Django can't delete user from my database

I have a problem with my Django project. I need to delete 1 or more users from my database but I can't do it because it returns this error:
__str__ returned non-string (type tuple)
I tried deleting it from my views but it didn't work. Than I went and used admin panel to try to delete it but the same problem happened.
If someone could give some advice or suggestion that would be great.
Thank you.
I found out what was the problem. I was returning tuple in my models __str__ function instead of a string which worked while users existed but it for some reason didn't when I tried to delete or as I later found out create a new user.

Group list items by field value in the Django admin

I'm trying to group the items in the Django admin app by a specific field (e.g. date).
So I've added to the queryset in admin.ModelAdmin.getQueryset() the following:
queryset = queryset.values('date').annotate(Sum('amount'))
But this doesn't work because in this case, a dict is returned instead of a queryset.
I started exploring what's inside the django/contrib/admin folder, and I think something need to be done before sending the object to the template change_list.html.
I'm not sure but I think the class in views/main.py (admin folder) might need some change.
Can anybody confirm that what I'm trying to do is achievable at all?
Please find below a representation of what I'm trying to achieve:
Follow the below example in URL. it's has great way to understand with override django admin with custom queryset and groupby data
https://medium.com/#hakibenita/how-to-turn-django-admin-into-a-lightweight-dashboard-a0e0bbf609ad
I found this useful: https://github.com/xacce/django_admin_grouper
You can simply define the group in ClassAdmin
class RecordAdmin(admin.ModelAdmin):
def regroup_by(self):
return 'category'
The repo overrides Django's change_list_results.html. If your RecordAdmin has method reggroup_by than it inserts a row with the name of the category. If reggroup_by is missing it works as usual.

In the Django admin, "Add" and "Change" options are not appearing for a brand new simple model admin. Why?

This is probably something simple, but I'm just not seeing it. So I started a new app called proposals. The following I entered into the app's models.py:
from django.db import models
class Proposal(models.Model):
name = models.CharField(max_length=200)
I then entered the following into admin.py:
from django.contrib import admin
from proposal.models import Proposal
class ProposalAdmin(admin.ModelAdmin):
pass
admin.site.register(Proposal, ProposalAdmin)
This seems incredibly straightforward, right out of the Django docs, but the "Add" and "Change" options for this admin are not appearing. They do appear for everything else, but not this particular admin. Any ideas on what might be causing this?
UPDATE
I'm continuing to check into this, and it's not a permission issue. The permissions are all set to true for add / change / delete. The template that generates the admin page requires a model.add_url for an "Add" link and model.admin_url for a "Change" link. These attributes are missing for some reason. Thus no links. Why they are missing is the big question.
UPDATE
I finally discovered what was going on here. An app which didn't need the add / change links was listed in the installed apps prior to this new one. Whatever it's author did to cause these links not to appear ended up being inherited by all other apps that followed it in this list. When I moved this new app above this one, the links appeared. I didn't even know that it was possible for apps to affect each other like this, but that is something to look for in the future.

Using django filters

I'm new to django so this must be a silly question but i was working my way through the official documentation tutorial(the one about a site with polls and choices) and i wanted to filter out polls with no choices, i managed to do that with a filter in the queryset argument of the ListView:
queryset=Poll.objects.filter(pub_date__lte=timezone.now).filter(id__in=Choice.objects.all).order_by('-pub_date')[:5]
And this indeed filters the query, the problem is that if i add a choice to a poll that didn't have any choices from the admin site, this won't be reflected on the site until i restart the server or i change some code in the project, even though i'm passing a callable object as argument to the filter (which is the same as the previous filter in that same line), i searched in the rest of documentation and i also looked at the definitive guide to django but i found nothing, that could help me, so i don't really know if there's something wrong with the code, or i'm lacking some understanding of django or a particular concept of python itself
Your current query is incorrect because, You are filtering poll ids, if choice objects of the same ids are present in the database, which is not accurate.
To filter out polls with no choice, you need to do
queryset=Poll.objects.filter(choice__isnull=False).order_by('-pub_date').distinct()[:5] #Get only polls with a choice.
Now,every Poll before now can be filtered like this:
queryset = Poll.objects.filter(choice__isnull=False, pub_date__lte=timezone.now()).order_by('-pub_date').distinct()[:5]

URLs stored in database for Django site

I've produced a few Django sites but up until now I have been mapping individual views and URLs in urls.py.
Now I've tried to create a small custom CMS but I'm having trouble with the URLs. I have a database table (SQLite3) which contains code for the pages like a column for header, one for right menu, one for content.... so on, so on. I also have a column for the URL. How do I get Django to call the information in the database table from the URL stored in the column rather than having to code a view and the URL for every page (which obviously defeats the purpose of a CMS)?
If someone can just point me at the right part of the docs or a site which explains this it would help a lot.
Thanks all.
You dont have to to it in the flatpage-way
For models, that should be addressable, I do this:
In urls.py I have a url-mapping like
url(r'(?P<slug>[a-z1-3_]{1,})/$','cms.views.category_view', name="category-view")
in this case the regular expression (?P<slug>[a-z1-3_]{1,}) will return a variable called slug and send it to my view cms.views.category_view. In that view I query like this:
#render_to('category.html')
def category_view(request, slug):
return {'cat':Category.objects.get(slug=slug)}
(Note: I am using the annoying-decorator render_to – it is the same as render_to_response, just shorter)
Edit This should be covered by the tutorial. Here you find the url-configuration and dispatching in every detail. The djangobook also covers it. And check pythons regex module.
Of course you can use this code.
Your question is a little bit twisted, but I think what you're asking for is something similar to how django.contrib.flatpages handles this. Basically it uses middleware to catch the 404 error and then looks to see if any of the flatpages have a URL field that matches.
We did this on one site where all of the URLs were made "search engine friendly". We overrode the save() method, munged the title into this_is_the_title.html (or whatever) and then stored that in a separate table that had a URL => object class/id mapping.ng (this means it is listed before flatpages in the middleware list).

Categories

Resources