Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unit test get_absolut_url django
I'm pretty new to django, and writing tests. I'm currently working on a project that has two models, Project and Technologies. The project models has a many to many relationship with the technologies model. I have a view that overrides the get_queryset method. On my coverage report this method is my only miss. I am looking for guidance on how to write a unit test for this method. Thank you for taking the time to answer my question. models.py from django.db import models from django.template.defaultfilters import slugify from django.urls import reverse class Technologies(models.Model): name = models.CharField(max_length=64, unique=True) slug = models.SlugField() def __str__(self): return self.slug def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Technologies, self).save(*args, **kwargs) class Project(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=128) repo = models.URLField() slug = models.SlugField() image = models.ImageField( upload_to='project_images', default='project_images/default_project.png') technologies = models.ManyToManyField(Technologies) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("projects:detail", kwargs={"slug": self.slug}) views.py from django.views.generic import DetailView, ListView from .models import Project class ProjectsListView(ListView): model = Project class ProjectDetailView(DetailView): model = Project class TechnologiesListView(ListView): model = Project allow_empty = False # If list is empty 404 def get_queryset(self): return Project.objects.filter(technologies__slug=self.kwargs['slug']) urls.py from django.urls import path from … -
URl redirection issue in Django 2
I'm new to Django and trying to build a web app with the following structure. I need your help to understand what Im doing wrong. The flow of the application is shadesProductUploader.urls will forward '' to authSection for login and after a successful login user should be redirected to mainSection 'home/'. Urls.py files are shadesProductUploader.urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('authSection.urls')), ] authSection.urls from django.contrib import admin from django.urls import path, include from . import views app_name = 'authSection' urlpatterns = [ path('', views.login_view, name='login'), ] mainSection.urls from django.contrib import admin from django.urls import path,include from . import views app_name = 'mainSection' urlpatterns = [ path('home/', views.home), ] and the view.py in authSection def login_view(request): next = request.GET.get('next') form = userLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) login(request,user) if next: return redirect(next) context={'user':user} return redirect('home/') return render(request, 'login.html', {'form': form}) after a successful login I get this error. What Am I missing? Not sure why I see a Url of home/ home/ -
Reverse lookup 'QuerySet' object has no attribute
I have the following Models where I define a trucking company and their insurance company. Models.py: class Truckers(models.Model): DOT_Number = models.IntegerField(primary_key=True) Address = models.CharField( max_length=200) CaliIns_FK(models.Model): DOTNmb = models.ForeignKey(Truckers, on_delete=models.CASCADE) CoName = models.CharField(max_length=20) There are many truckers and not as many insurance companies. I am trying to get a list of every Trucker that has insurance. I tried the following as per django: truck = Truckers.objects.all() filtered = truck.caliinsfk_set.filter(truckers__isnull=True) and filtered = truck.caliins_fk_set.filter(truckers__isnull=True) getting error: AttributeError: 'QuerySet' object has no attribute 'caliinsfk_set' -
load 2 folder static in django
in my project,I have 2 folder static. when I go into web game, django can load static js, css in folder game\static but it can't load img. This is my directory structure: go to web game, the chess not show pieces: It load folder js and css but not load folder img in file chessboard.js: b.pieceTheme="static/img/chesspieces/wikipedia/{piece}.png" This is my static configuration in settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] I have a template that renders chess: {% load static %} <script src='{% static "js/chess.min.js" %}'></script> <script src='{% static "js/chessboard-0.3.0.min.js" %}'></script> <script src='{% static "js/main.js" %}'></script> -
Django update user data
Ребят help Как реализовать изменение данных user-профиля в Django Rest Framework? Ребят прям проблема никак не могу сделать серилайзер типа: class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate_new_password(self, value): validate_password(value) return value -
Stuck with django form validation
I'm trying to get validation running on a django form used to retrieve a list of objects in a ListView View. Despite having read django docs and many other questions here, I can't find out what's wrong in this simple test code: form.html <form action="list.html" method="get"> {{ form }} <input type="submit" value="Submit"> </form> list.html <ul> {% for area in object_list %} <li>{{ area.name }}</li> {% endfor %} </ul> forms.py from django import forms class SearchArea(forms.Form): area = forms.CharField(label='Area code', max_length=6) def clean_area(self): area = self.cleaned_data['area'].upper() if '2' in area: raise forms.ValidationError("Error!") return area views.py class HomePageView(FormView): template_name = 'form.html' form_class = SearchArea class AreaListView(ListView): template_name = 'list.html' model = AreaCentral def get_queryset(self): q = self.request.GET.get('area') return AreaCentral.objects.filter(area__istartswith=q) When I try to submit something like "2e" I would expect a validation error, instead the form is submitted. Moreover I can see in the GET parameters that 'area' is not even converted to uppercase ('2E' instead of '2e'). -
ModuleNotFoundError with Django, not recognizing app's name
I'm getting the same exception whenever I try to run a Django command (makemigrations, migrate, shell, runserver). I looked at other posts but nothing has helped. I changed around the naming of the app but that didn't work either. The exception traceback is: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f3c3ff9dc80> Traceback (most recent call last): File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/usr/projects/myproject/env/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/usr/projects/myproject/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'api' My apps.py is: from django.apps import AppConfig class ApiConfig(AppConfig): name = 'api' verbose_name = 'Project API' and in my __init__.py for the main project I have: default_app_config = 'api.apps.ApiConfig' and my INSTALLED_APPS is: INSTALLED_APPS = [ 'api', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Command "python setup.py egg_info" failed with error code 1 when trying to install unirest
I got this error after running the command pip install unirest to use the unirest in my views.py. I am trying to use the api of petrol price in my project in which run this command (geo) ABHISHEKs-MacBook-Air:map abksharma$ pip install unirest Collecting unirest Using cached https://files.pythonhosted.org/packages/92/da/2149cbd7a8c78f8b76b377379c1bda64ec36cc13315d55f6f7de6d094ac5/Unirest-1.1.7.tar.gz Collecting poster>=0.8.1 (from unirest) Using cached https://files.pythonhosted.org/packages/9f/dc/0683a458d21c3d561ab2f71b4fcdd812bf04e55c54e560b0854cea95610e/poster-0.8.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/setup.py", line 2, in <module> import poster File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/poster/__init__.py", line 29, in <module> import poster.streaminghttp File "/private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip-install-vf9ffv_s/poster/poster/streaminghttp.py", line 61 print "send:", repr(value) ^ SyntaxError: invalid syntax ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/84/0bcm7b0s6kx3496xf5ply6wh0000gn/T/pip- install-vf9ffv_s/poster/ views.py from django.shortcuts import render import requests import unirest def petrol(request): response = unirest.post("https://fuelprice.p.mashape.com/", headers={ "X-Mashape-Key": "eqPyWAd3Wrmsh52b6fvG3AQ5T2ygp1KZhDfjsng702Sd7DmWN7", "Content-Type": "application/json", "Accept": "application/json" }, params=("{\"fuel\":\"p\",\"state\":\"dl\"}") ) price = response.json() return render(request, 'petrol/petrol.html', {'price':price}) url.py from django.urls import path from .import views urlpatterns = [ path('', views.petrol, name='petrol') ] -
What is meant by lightweight server in python django
I was reading django basics document from tutorials point , i came across term " lightweight server ". What does lightweight mean? -
Django Migration: Not reflecting changes | creates only id
I´m stuck trying to migrate my new models using django 2.1. For some reason it only creates the id column. Having done that, I get the following strange behaviour: makemigrations ui: No changes detected in app 'ui' migrate ui No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Doing as said by the cli I´m ending up in a loop. Here is my models.py from django.db import models from django.contrib.auth.models import User class Costumer(models.Model): costumer_id: models.AutoField(primary_key=True) costumer_su_object: models.ForeignKey(User, on_delete=models.CASCADE) set_costumer_mails: models.BooleanField(default='1') set_contact_point: models.EmailField(blank=True) set_tracking_link: models.CharField(max_length=100, blank=True) set_primary_color: models.CharField(max_length=100, blank=True) set_warn: models.IntegerField(max_length=2) stat_saved: models.IntegerField(max_length=100, blank=True) stat_active: models.IntegerField(max_length=100, blank=True) stat_warn: models.IntegerField(max_length=100, blank=True) stat_case: models.IntegerField(max_length=100, blank=True) I do not get any error messages. As well I already deleted the table and all migrations and tried to do an initial migration from scratch (with all the above set). It again creates the id column and that is it. My 0001_initial.py looks like this: # Generated by Django 2.1.2 on 2018-11-25 16:55 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = … -
How to use django default permission in class based view
Django has nice built in admin permission setup. Want to use add, change, delete, view permission in class based generic view outside of the admin panel. How to do this? -
Error while creating superuser in Django web-app
In the project I'm working on is a teacher-student exam app. For the login page, the user is an extension of AbstractUser which contains details of both teacher and student. This is models.py in my app named user: from django.db import models from django.contrib.auth.models import AbstractUser class Courses(models.Model): course_id = models.CharField(max_length=200) department = models.CharField(max_length=200) def __str__(self): return self.course_id class User(AbstractUser): is_student = models.BooleanField(default=True) is_instructor = models.BooleanField(default=False) department = models.CharField(max_length=200) course = models.ForeignKey(Courses, on_delete=models.CASCADE, null=True) def __str__(self): return self.username When I try to create a superuser, I get this long error after entering the username, email id, password twice. What's wrong? (venv) praneeth@My-MBA:~/Desktop/New_E/eeeee$ python manage.py createsuperuser Username: superuser Email address: jkl@j.com Password: Password (again): This password is too common. Bypass password validation and create user anyway? [y/N]: n Password: Password (again): Traceback (most recent call last): File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: NOT NULL constraint failed: user_user.course_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/edubillipraneeth/Desktop/New_E/venv/lib/python3.7/site-packages/django/core/management/base.py", line … -
Django - How to set up ModelViewset with Serializer API endpoint to update if object exists else create?
I am quite confused with how to use ModelViews and Serializers in creating an API using Django Rest Framework. What I am trying to do is this: I have a "Rating" and "Product" model, and I want to figure out how to set up my ModelViewSet, Serializer, and React component such that when I call a function in that React component, I want to: (1) Check to see if the Rating for the Product exists for the current User, and if it exists, then update the rating. (2) If the Rating does not exist, create a new rating In my models.py: class Product(models.Model): name = models.CharField(max_length=100) ... def __str__(self): return self.name class Rating(models.Model): rating = models.IntegerField() product = models.ForeignKey('Product', related_name='ratings') def __str__(self): return "{}".format(self.rating) In my views.py: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class RatingViewSet(viewsets.ModelViewSet): queryset = Rating.objects.all() serializer_class = RatingSerializer In my serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('pk', 'name', 'description', ...) class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ('pk', 'rating', 'user', 'product', ...) In my urls.py: from rest_framework import routers router = routers.DefaultRouter() router.register(r'products', views.ProductViewSet) router.register(r'ratings', views.RatingViewSet) In my React component, I have the below function: const createRating = (rating, … -
Django - Displaying model having content type in admin panel
I am new to Django and I am facing a problem. I have multiple model that require address and phone number against address. And only phone number can be associated with some of models. So, I have made polymorphic relation for "Addresses" and "PhoneNumber". Like here: class PhoneNumber(SoftDeleteModel): phone_number = PhoneNumberField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.phone_number.as_e164 class Address(SoftDeleteModel): house_number = models.CharField(max_length=255) street_number = models.CharField(max_length=255) area = models.CharField(max_length=255) city = models.CharField(max_length=255) country = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() phone_number = GenericRelation(PhoneNumber) content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return str(self.house_number)+", "+str(self.street_number)+", "+self.area+", "+self.city+", "+self.country These are the model for Address & PhoneNumber I am using Address model in Vendor like: class Vendor(SoftDeleteModel): vendor_name = models.CharField(max_length=500) vendor_phone = GenericRelation(PhoneNumber) vendor_address_detailed = GenericRelation(Address) vendor_contact_person = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def __str__(self): return self.vendor_name When I am making crud in admin for vendor I am able to get only Addresses not PhoneNumber in Address model like in in this … -
How to insert character varying array into postgresql
I want to insert a json array into postgresql?This is my code: def get(self,request): request_data = ''' { "name":"a", "isbn":"dd", "author":["a","b"], "publisher":["a","b"], "price":"ddd"} ''' data = json.loads(request_data) serializer = BookSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) And this is my field define: class BookSerializer(serializers.Serializer): name = serializers.CharField(required=False, allow_blank=True, max_length=100) isbn = serializers.CharField(required=False, allow_blank=True, max_length=100) author = serializers.ListField(required=False) publisher = serializers.ListField(required=False, max_length=100) price = serializers.CharField(required=False, allow_blank=True, max_length=100) When i am request the function,it throws error: "[" must introduce explicitly-specified array dimensions How to avoid this problem? -
DJANGO:How to perform AND operation for my query?
There are two models .I want to make query to extract only the app exact app related Adspaces . models.py class Appname(models.Model): user=models.ForeignKey(User,related_name='appname', null=True, default=None,on_delete=models.CASCADE) name=models.CharField(max_length=150,blank=False,null=False,help_text='Add your new App') def __str__(self): return self.name def get_absolute_url(self): return reverse("dashapp:space",kwargs={'pk':self.pk}) class Adspace(models.Model): user=models.ForeignKey(User,related_name='adspace', null=True, default=None,on_delete=models.CASCADE) ad_space=models.CharField(max_length=150,blank=False,null=False) app=models.ForeignKey('Appname', related_name='appnames',default=None, on_delete=models.CASCADE) PID_TYPE = ( ('FN','FORMAT_NATIVE'), ('FNB','FORMAT_NATIVE_BANNER'), ('FI','FORMAT_INTERSTITIAL'), ('FB','FORMAT_BANNER'), ('FMR','FORMAT_MEDIUM,RECT'), ('FRV','FORMAT_REWARDED_VIDEO'), ) format_type=models.CharField(max_length=3,choices=PID_TYPE,default='FN',blank=False, null=False) def __str__(self): return self.ad_space def get_absolute_url(self): return reverse("dashapp:create",kwargs={'pk':self.pk}) Views.py SHowing the one where i need to the query class spacelist(LoginRequiredMixin,ListView): model=Adspace template_name='adspace_list.html' def get_queryset(self): query_set=super().get_queryset() return query_set.filter(user=self.request.user) Here I need to perform One more query so that EACH APP show their own adspaces when clicked right now every app show every show adspaces. I have the idea what to do as if i compare app_id then it'll show the exact app related adspaces, but i dont know how to write query for the same as i already have one query present.??? -
unable to locate websocketbridge.js in Django using channels websocket project
I am trying to implement websockets using channels in Django project. I am getting 404 for webscoketbridge.js Below is html template. {% load staticfiles %} {% block title %}Delivery{% endblock %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="{% static 'channels/js/websocketbridge.js' %}" type="text/javascript"></script> Also, I tried to have a look in the virtualenv/lib/python3.5/site-packages/channels path, there is no js folder or any file named websocketbridge.js Has anyone solved this issue? -
Django: Obtaining verbose_name and help_text for fields added through annotate in custom manager
I'm not sure if I am actually approaching this the right way, but what I would like to do is to be able to give a verbose name and a help text to fields I add to to my model through annotate. I use both these fields as I pass them to the webpage, and use the verbose_name as table header and the help_text as tooltip (basically a call which returns a list of dictionaries with the name of the field, the type, the verbose name and the help text). I get these values by calling Student._meta.get_field(field).verbose_name or help_text. Now the model I use is basically something like this: class Student(models.Model): # new first_name = models.CharField(verbose_name='first name', max_length=30, help_text='The first name of the student') last_name = models.CharField(verbose_name = 'last name', max_length=30, help_text='The last name of the student') date_of_birth=models.DateField(verbose_name='Date of Birth 'help_text = "student's date of birth") sex = models.CharField( max_length=1, choices=(('M','Male'), ('F','Female')), help_text=_('Sex of the student: (M)ale or (F)emale'), verbose_name='Sex')) I then have another model which basically maps the age of a student to its "category" (Freshman-Sophomore-Junior-Senior). My custom manager then adds a new field to the QuerySet which determine the category based on the date of birth and adds … -
Django Admin: Hook admin urls from an app with a namespace
project/urls.py: from django.urls import path urlpatterns = ( path('labs/', include('my_app.urls', namespace='my_app')), ) my_app/urls.py: from django.contrib import admin from django.urls import path app_name = 'my_app' urlpatterns = ( path('admin/', admin.site.urls), ) When I visit 127.0.0.1:8000/labs/admin I get: Traceback (most recent call last): File "/home/user/.virtualenvs/venv/lib/python3.5/site-packages/django/urls/base.py", line 75, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'admin' During handling of the above exception, another exception occurred: ... django.urls.exceptions.NoReverseMatch: 'admin' is not a registered namespace It works as expected, if I set: project/urls.py: urlpatterns = ( path('labs/admin', admin.site.urls), ) I guess that app_name = 'my_app' is the trouble maker. How can I make it work? -
mysqlclient fails to install within virtual environment
Outside my VE, mysqlclient is already installed and works fine, but when I try 'pip install mysqlclient' within my VE I get the following error: "fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory" -
How can I view the pdf file in Django?
Note: My model table consists of id field and File field which will be pdf. I am inserting data into the model using django admin.(I have no custom upload form) I am trying to view the pdf in the browser(as it normally opens in chrome). I am trying to find the file by taking the id field(by user) in a custom HTML template using a form(Please look at the codes mentioned below.) I am attaching the urls.py, index.html, views.py, models.py and forms.py codes below. Please patiently go through and let me the know the problem and the solution. I think my code should work but I am getting a Suspicious File Operation Error. urls.py urlpatterns = [ path('',views.index), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def index(request): if request.method == "POST": form = Form(request.POST) if form.is_valid(): id=request.POST.get("id") ans = query.objects.get(id=id) response=ans.repo if ans is None: return redirect("index.html") else: #return render (request,"ans.html",{'ans':response}) return redirect(response) else: form = Form() return render(request,"index.html",{'form':form}) forms.py class Form(forms.Form): id = forms.CharField(label="Report ID", max_length=100) models.py class query(models.Model): id=models.IntegerField(primary_key=True) repo=models.FileField(upload_to='documents/') index.html <!-- Search Form --> <form id="signup-form" method="POST" action=""> {% csrf_token %} {{form}} <input type="submit" value="Check" /> </form> -
How to count blog categories in django and display them in a template
am new in django am developing a blog which has functions post_list,category_detail and post detail am stuck in post_list function which renders a blog.html i want to display the blog category which are python and hardware together with the total number of posts in that category i have tried my ways it shows the wrong way since there should be six posts in python category and one post in hardware category see the picture here please check the codes and help out views.py def post_list(request): object_list=Post.objects.filter(status='Published').order_by("-created") recent_post=object_list[:4] category_list_count=Post.objects.annotate(num_category=Count('Category')) page = request.GET.get('page', 1) paginator = Paginator(object_list, 3) try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context={ 'items':items, 'recent_post':recent_post, 'category_list_count':category_list_count, } return render(request,"blog.html",context) blog.html <div class="widget"> <h3 class="badge">CATEGORIES</h3> {% for obj in category_list_count %} <ul> <li><a href="{% url 'category_detail' slug=obj.Category.slug %}">{{obj.Category}}</a> <span class="badge">{{obj.num_category}}</span> </li> </ul> {% endfor %} -
Django: use @cached_property decorator to cache queryset result
I am trying to use the cached_property decorator in order to cache the result of a queryset using values_list as follows: class Bar(models.Model): foo = models.ForeignKey('Foo', cascade=models.CASCADE) class Foo(models.Model): @cached_property def bars_pk(self): print('Computing cached property') return list( Bar.objects.filter( foo=self, ).values_list( 'pk', flat=True, )) def has_bar(self, bar): return bar.pk in self.bars_pk for foo in Foo.objects.all(): for bar in Bar.objects.filter(pk__in=[1, 3, 10, 100]): print(foo.has_bar(bar)) Unfortunately, the property bars_pk is always computed. Note that Foo.bars_pk uses list to force queryset evaluation as stated here. For the record, the project uses Python 3.4.4 and Django 1.8.18. Thanks!! -
django rest framework url parameters getting combined
I have the following in my urls.py: url(r'^prstatus/(?P<pk>\d+)/(?P<organization>.+)/' + '(?P<repository>.+)/(?P<pr>\d+)/$',PRStatus.get_pr_status, name="one_pr_in_repo"), The url that I enter is: localhost:8000/api/v1/prstatus/1/myrepo/docker-react/1 But if I print(organization, repository, pr). I get myrepo/docker-react 2 None Organization gets assigned myrepo/docker-react instead of myrepo. Can someone help on this? -
Filtered M2M query sets in selection django admin
I have an event that has many block prices where there are sets of blocks and each set has a price, so I created an M2M field that represents blocs and a positive integer for the price, however, I want to make each set unique so no block can be repeated in another set. Here's my model. class BlocPrice(models.Model): event= models.ForeignKey(Event, on_delete=models.CASCADE) bloc_set= models.ManyToManyField(Bloc) prix = models.PositiveIntegerField() Screenshot of DjangoAdmin: In the change list of the block prices, I want the list of blocks to be filtered each time we select a block so B2, B1 won't be shown in the second input since they were selected in first input, Is there a way to do so?