Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access attributes of subclassed User in Django
This seems really simple and I'm probably missing something, but I'm struggling with the following model structure: from django.contrib.auth.models import AbstractUser class User(AbstractUser): @property def is_author(self): return False @property def is_editor(self): return False class Author(User): @property def is_author(self): return True class Editor(Author): @property def is_editor(self): return True Basically I want to have a generic user class and then a subclass called Author and a subclass of that called Editor, each with slightly different properties. This seems to work at the database level, but when I get a User in the context of the app that is also an Author or Editor, I can't get access to the Author or Editor class methods/properties. I tried playing with __init__ to no real effect; have I structured this wrong? How do I call is_author on an Author that's also a User and get True back? -
pagination does not work in Django template page
I was trying to include pagination in template page. but the template syntax error was encountered when executing the project. it says : Could not parse the remainder: '==i' from 'posts.number==i' I am very frustrated about this. views.py def posts(request): posts = Post.objects.filter(active=True) myFilter = PostFilter(request.GET, queryset=posts) posts = myFilter.qs page = request.GET.get('page') paginator = Paginator(posts, 3) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) context = {'posts': posts, 'myFilter': myFilter} return render(request, 'base/posts.html', context) posts.html <div class="row"> {%if posts.has_other_pages%} <ul class="pagination"> {%for i in posts.paginator.page_range%} {%if posts.number==i%} <li class="page-item"><a class="active page-link">{{i}}</a></li> {%else%} <li class="page-item"><a href="?page={{i}}" class="page-link">{{i}}</a></li> {%endif%} {%endfor%} </ul> {%endif%} </div> -
Error when trying to migrate postgresql database Django/Gunicorn/Nginx/Docker
I try to "dockerize" a Django project. I've build my images and access my application via localhost:8002 Now I need to migrate postgresql database but it failed (cf traceback below) when I run the command docker exec -it my_djangoapp_id python manage.py migrate It seems to be a problem of port I am lost with port in my configuration but I configure port 5436 for postgresql docker-compose.yml version: '3.7' services: coverage-africa: restart: always build: context: ./coverage-africa dockerfile: Dockerfile.prod command: gunicorn coverage.wsgi:application --bind 0.0.0.0:8002 volumes: - coverage-africa_static_volume:/home/apps/coverage-africa/static - coverage-africa_media_volume:/home/apps/coverage-africa/mediafiles expose: - 8002 env_file: - ./config/coverage-africa/.env depends_on: - coverage-africa_db coverage-africa_db: restart: always image: postgres:12.0-alpine expose: - 5432 ports: - "5436:5432" volumes: - coverage-africa_postgres_data:/var/lib/postgresql/data/ env_file: - ./config/coverage-africa/.env nginx: build: ./nginx volumes: - coverage-africa_static_volume:/home/apps/coverage-africa/static - coverage-africa_media_volume:/home/apps/coverage-africa/mediafiles ports: - 8002:82 depends_on: - coverage-africa volumes: coverage-africa_postgres_data: coverage-africa_static_volume: coverage-africa_media_volume: ``` ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.8/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect … -
Django: delete a Foreign Key object when empty
I am writing a dictionary app using Django where Expressions have Definitions. When an Expression is deleted, all its Definitions are deleted also (achieved through on_delete=CASCADE in foreign key field). My problem is that when the last Definition of an Expression is deleted, that Expression remains in my database without Definitions. I would like that when you delete the last Definition of an Expression the Expression gets deleted as well. How can I enforce this in my models? Here is my code right now: class Expression(models.Model): expression = models.CharField() class Definition(models.Model): definition = models.CharField() expression = models.ForeignKey(Expression, on_delete=models.CASCADE) -
Django - ForeignKey value same as object from different model
I have two models. One of them have a ForeignKey which should be related to an object in a different model: class Game(models.Model): gameday = models.CharField(max_length=120) hometeam1 = models.ForeignKey(Teams, on_delete=models.CASCADE, related_name="hometeam1", blank=True, null=True) class Tipp(models.Model): hometeam1 = models.ForeignKey(Game, on_delete=models.CASCADE, default=Game.hometeam1) week = models.CharField(max_length=120, null=True, blank=True) The hometeam1 object in the model Tipp should be the same as Game.hometeam1 and Game.hometeam1 gets his value manually. How can I assign that Tipp.hometeam1 has everytime the same value as Game.hometeam1? -
How to have two tag fields i.e. two Taggable Managers in the same model?
I have a model for uploaded files and I now need to have two tag fields in that model. One for user tags and one for admin tags. I've tried several solutions but neither worked. Here is my code now and it doesn't work. Not sure if this is to create two separate tables, one for user tags and for admin tags so any help would be appreciated. Also, if you could maybe explain to me what I'm doing because I'm lost. class UserTags(CommonGenericTaggedItemBase, TaggedItemBase): object_id = models.CharField(max_length=50, db_index=True) objects = models.Manager() class BaseTag(TagBase): pass class AdminTags(CommonGenericTaggedItemBase, TaggableManager): object_id = models.CharField(max_length=50, db_index=True) tag = models.ForeignKey(BaseTag, on_delete=models.CASCADE) objects = models.Manager() # Model for all uploaded files class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") time_uploaded = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50) file = models.FileField(upload_to=MEDIA_ROOT) tag = TaggableManager(blank=True, through=UserTags, related_name='user_tags') tags = TaggableManager(blank=True, through=AdminTags, related_name='admin_tags') additional_description = models.CharField(max_length=50, blank=True) def __str__(self): return f"{self.name} {self.file}" -
Django: Module not found error , on importing a model
I am fairly new to Django, in my project I have created 2 apps, web, and dashboard while trying to import my model from the web to model in the app dashboard using '''from myproject.web import models''' I am getting the following error ModuleNotFoundError: No module named 'myproject.web'. Thanks in advance -
django import export for new field that is foreign key in another model
I have a project where I have a model called User, the important columns for that model are: name = CharField(_("Name of User"), blank=True, max_length=255) national_id = models.CharField(max_length=14, validators=[numerical_regex,MinLengthValidator(14)], null=True, unique=True) company = models.ForeignKey(Company, on_delete=models.SET_NULL, null=True, default='') All these data exist and there are no empty data. My project manager asked me to add a new table called department which will be a foreignkey too at User model. Then he told me that we can't add each department to each user, he needs to add it using Excel sheet from admin panel, the excel sheet is ready and its structure will be like that: company | Department | National ID so actually excel sheet will have many departments that are duplicated and supposed to be added as unique values to department table and be connected to User through national id and company is depending on User too which will not be added, just display it. How to solve a problem like that? -
Django ORM query with IN + LIKE
Lets suppose the following model: class Person(models.Model): name = models.CharField(null=False) ... I know that I can filter Persons with a name that contains the letter a using Person.objects.filter(name__contains='a'). And I know that I can filter Persons with name is in a list using Person.objects.filter(name__in=['John Doe', 'Mary Jane']). Its possible ( or, whats the performative way ) to do the two things using just one filter ? I know that I can do 2 queries (maybe more) and fetch the data. But in my current case, I have a method on my view called get_filters that returns a Q object that will be used in get_queryset method. So I need to implement this inside a Q object and fetching only 1 query. Its possible ? -
Is it possible to use django-parler with static model classes
I am trying to migrate from django-hvad to django-parler for translation in a django app I am working on. After replacing django-hvad with django-parler in the app when I run it I get this error: raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__)) TypeError: Can't create TranslatedFieldsModel for abstract class MyClass I have read the documentation https://django-parler.readthedocs.io/en/latest/api/parler.models.html and have seen how TranslatedField is explained and used in an example there but I don't want to use this approach because it won't work in my case. How can I use django-parler with my abstract class, is it possible? If it's not possible is there an alternative package that works with static model classes I can use in place of django-parler? -
Django queryset return DurationField value in seconds
I have two models: Post, Comment (Comment has FK relation to Post). Now I want to return all posts with theirs "response time". I get this response time in timedelta format. Can I receive it in seconds instead? I tried ExtractSecond but it is not what I'm looking for: base_posts_queryset.annotate( min_commnet_date=Min("comment_set__date_created"), response_time=ExpressionWrapper(F("min_commnet_date") - F("date_created"), output_field=DurationField()), response_time_in_sec=ExtractSecond(F("response_time")) ).filter(response_time__isnull=False).values("response_time", "response_time_in_sec") This code returns following objects: {'response_time': datetime.timedelta(days=11, seconds=74024, microseconds=920107), 'response_time_in_sec': 44} What I want to achieve is basically call .seconds for each item in result queryset. I could do this in python, but mb it could be done on db level? -
What is the best practice / best place for enabling/disabling site-wide admin functionality
Situation: I have a Django project with multiple applications, each of which have one or more models. I have added custom admin actions for some of the models and got the "Delete selected" action for free. I want to disable this for all models in all applications. I'm aware how to disable the "Delete selected" action for the whole project, i.e. by using admin.site.disable_action('delete_selected') but I simply don't know where to put it. I've put it in the admin.py file of one application and that definitely works, but that bugs me as (in my opinion) a site-wide change, also affecting other applications, shouldn't be caused by the admin configuration of a single application. I was hoping to find some way to have a "project-level" admin.py file, but it seems that only fully customizing the AdminSite will do the trick, which I think is a bit overkill if I only want to disable the "delete_selected" action globally. Any thoughts? -
Django ModuleNotFoundError. Everything is fine, but i am unable to run a server
I have started going through "Django for Beginners" book and copied code example from 2nd chapter, but it doesnt work because of the ModuleNotFoundError ModuleNotFoundError: No module named 'pages.apps.PagesConfigdjango'; 'pages.apps' is not a package My app urls seem to be fine from django.urls import path from .views import homePageView urlpatterns = [ path('', homePageView, name = 'home') ] As well as INSTALLED_APPS 'pages.apps.PagesConfig' What is the possible problem? -
Django Formset POST not registering in views.py
I have a View that creates multiple formsets and displays them in a template, from the customers list page I have an Ajax call that passes the Selected Customer ID through to this view for intial data display. Here is the views: views.py def mod_customer(request): print(request.body) try: params = json.loads(request.body) selection = params['cst_id'] obj = AppCustomerCst.objects.get(id_cst=selection) instance = get_object_or_404(AppCustomerCst, id_cst=selection) form = CustomerMaintForm(request.POST or None, instance=instance) ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=( 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt')) formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=selection), prefix='contact') tpList = AppCustomerTpRel.objects.filter(idcst_rel=selection).select_related('idcst_rel', 'idtrp_rel').values( 'idtrp_rel__id_trp', 'idtrp_rel__tpid_trp', 'idtrp_rel__name_trp', 'sender_id_rel', 'category_rel', 'cust_vendor_rel') TPFormSet = formset_factory(TPListForm, can_delete=True) tp_formset = TPFormSet(initial=tpList, prefix='tp') doc_list = DocData.objects.document_list(selection) DocFormSet = formset_factory(DocumentListForm) # print(formset) DocFormSet = formset_factory(DocumentListForm) doc_formset = DocFormSet(initial=doc_list, prefix='doc') context = {'form': form, 'formset': formset, 'tp_formset': tp_formset, 'doc_formset': doc_formset} print(form.errors) # context = {'form': form} return render(request, 'mod_customer.html', context=context) except ValueError: print(request.POST) if '_edit' in request.POST: # This works with Customer Name, but would prefer to use Customer ID -- Need to figure that out. cust_name = request.POST['name_cst'] instance = get_object_or_404(AppCustomerCst, name_cst=cust_name) form = CustomerMaintForm(request.POST, instance=instance) cntct_instance = get_list_or_404(AppContactCnt, idcst_cnt=selection) # print(cntct_instance) contact_form = ContactsForm(request.POST or None, instance=cntct_instance) if form.is_valid(): # print('made it to valid point') form.save() return render(request, 'customers.html') else: context = {'form': form, 'contact_form': … -
How can i use django template based package in jinja2
I'm developing website based on django. In my project, there are some third party package which is based on django templates engine, now is there any to integrate this package with jinja templates -
Error with Docker Compose Django and PostgreSql
I got a problem when i create any object with my on Admin show me this error: LINE 1: SELECT (1) AS "a" FROM "license_portal_client" WHERE I'm new with docker-compose so i appreciate if anyone knows how to solve it. Here is My DockerFile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ Here is my docker-compose.yml: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python license_portal/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db My Database settings.py and i add my app on installed apps: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } And here is my models.py test: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) And the last one admin.py from django.contrib import admin from license_portal.models import Person admin.site.register(Person) -
Specify a Django model field as a query expression
How do I specify that a model field is implemented by a database expression instead of a table column? I have this model: class URLProbe(models.Model): url = models.CharField(max_length=MAX_URL_LENGTH) timestamp = models.DateTimeField(auto_now_add=True) status_code = models.SmallIntegerField(null=True, blank=True) # The HTTP status code error = models.TextField(blank=True) # stores non-HTTP errors, e.g. connection failures def ok(self): return self.status_code == 200 ok.boolean = True ok.admin_order_field = Case( When(status_code__exact=200, then=True), default=False, output_field=BooleanField() ) def errmsg(self): if self.ok(): return '' if self.status_code is not None: return f'Error: HTTP status {self.status_code}' return self.error errmsg.admin_order_field = Case( When(status_code__exact=200, then=Value('')), When(status_code__isnull=False, then=Concat(Value('Error: HTTP status '), 'status_code')), default='error', output_field=CharField() ) The model represents an attempt to retrieve an url, recording whether the HTTP call succeeded or what the error was. The ok and errmsg fields here are implemented as methods, but I want to be able to use them in the Django admin as regular fields (sort/filter on them) and to sort and/or filter on them in queries. That is possible, but I need to define the query expression multiple times: in an admin_order_field, in a Django admin custom filter, and in queries where I want to use them. So that duplicates a lot of code, both for the multiple expressions … -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' error html form
I'm getting this error while trying to run a html django program . File "C:\Users\ankit\project\detri\calc\views.py", line 22, in speedup m1 = int(request.POST.get('mi1')) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' function ```def speedup(request): #line22 m1 = int(request.POST.get('mi1')) m3 = int(request.POST.get('mi3')) #calculation stuff return render(request, 'Speed Result.html', {"days": T})``` html form ```<form action= "{%url 'sp'%}" method="POST" > {% csrf_token %} <label for="mi1"> Enter 1 minute :</label> <br><input type="number" id="mi1" name="mi1" ><br> <label for="mi3"> Enter 3 minute :</label> <br><input type="number" id="mi3" name="mi3" ><br> </html>``` -
SlideShow of Images with title having Different time durations in django
how i can make Slide Show of Images with title having Different time durations in django and set url and images from my database for example : {% for photo in Photos%} <label id="label_main_app"> <a href=" {{ photo.page_url }} " style="color:#033457" > <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{ photo.get_image }}" alt="no image found !" height="160" width="165" > </a> <a href=" {{ photo.page_url }} " style="color:#033457" > {{ photo.name }} </a><br><br> <p id="p_size_first_page"> {{ photo.app_contect}} <br> <br> <a href=" {{ photo.page_url }} " type="button" class="btn btn-dark"><big> See More </big> </a> </p> </label> {% endfor %} -
Heroku has issues in deploying Django Channels app for development purposes
I have been on this issue for some hours now, can someone help please. Thank You for your time, I appreciate it. I have been trying to publish this DRF app that is using Django Channels for websocket support. I want to use this only for further development for now and hence thought of deploying it to Heroku. But Heroku keeps giving me this Push Rejected Error. in settings.py : # Development CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } in routing.py : # imports from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) channel_routing = {} In asgi.py : import django import os from channels.routing import get_default_application from channels.layers import get_channel_layer from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppBackend.settings') # application = get_asgi_application() django.setup() application = get_default_application() channel_layer = get_channel_layer() (Heroku) Procfile : web: gunicorn app_xxx.wsgi --log-file - web2: daphne AppBackend.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 chatworker: python manage.py runworker --settings=AppBackend.settings.production -v2 (Heroku) requirements.txt : django gunicorn django-heroku channels djangorestframework (Heroku) runtime.txt : python-3.7.8 (Heroku) Error Message : (django-env) D:\Code\Projects\social-media-app-backend\AppBackend>git push heroku master Enumerating objects: … -
Using string parameter on django template
I'm having some trouble passing a string parameter to a href from withing a template. I have the following url pattern path('current_observations/<str:mongo_id>', views.specific_observation, name='specific_observation') At current_observations I have several objects which have the mongo ID as an attribute. The idea is to send this id to the new url. I tried doing the following withoud success <a href="{% url 'VM_OrchestratorApp:specific_observation' resource.id|stringformat:s %}"> {{ resource.TITLE }} </a> Which returns Failed to lookup for key [s] Tried doing the following also <a href="{% url 'VM_OrchestratorApp:specific_observation' resource.id|stringformat:'s' %}"> {{ resource.TITLE }} </a> But in this case the argument is not being recognized at all. NOTE: By doing <a href="{% url 'VM_OrchestratorApp:specific_observation' 'hello' %}"> {{ resource.TITLE }} </a> I get redirected to current_observations/hello which is the expected behaviour. Any idea on what could be going wrong with the string formatting? -
How to change list of foreign keys for a formset generated by django inlineformset_factory?
I have the following models: class Organization(models.Model): name = models.CharField(max_length=255) owner = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class Category(models.Model): name = models.CharField(max_length=255) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='categories') class Meta: verbose_name = "category" verbose_name_plural = "categories" order_with_respect_to = 'organization' def __str__(self): return self.name class Product(models.Model): brand = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255) code = models.CharField(max_length=255) sale_price = models.DecimalField(decimal_places=2, max_digits=12) stock = models.DecimalField(decimal_places=2, max_digits=12) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='products') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='producs', null=True, blank=True) class Meta: order_with_respect_to = 'organization' I want an inline formset where the user can add products, but I want to show only the categories that are registered to the current user's organization(accessible by request.user.organization) Right now, this is how the formset is set up: def addProducts(request): ProductFormSet = inlineformset_factory(Organization, Product, exclude=('organization',), extra=5) organization = request.user.organization if request.method == "POST": formset = ProductFormSet(request.POST, instance=organization, queryset=Product.objects.none()) else: formset = ProductFormSet( instance=organization, queryset=Product.objects.none()) context = {"forms": formset} return render(request, "products/product_form.html", context=context) But, as you can probably guess, the select field is showing all categories, not just the one's that have the same organization. How do I pass Category.objects.filter(organization=organization) to the select field? -
How to add/update/remove value in existing values list in redis cache using django
I am storing data in redis as below: key: "fruitList" values: [{"a": "apple", "id": 1}, {"b": "banana", "id": 2}, {"m": "mango", "id": 3}] to add following data, I used conn = cache.client.get_client() conn.lpush(key, *values) Now I want to update/remove some element of a value eg. removing {"b": "banana", "id": 2} from values. I have huge list of values. How would I do that. Please help -
Can't retrieve multiple results sets from a stored procedure using django.db.backends.mysql
I'm using django.db.backends.mysql, NOT mysql.connector.django, and I can't get nextset() to work for retrieving multiple result sets from my stored procedure. I suspect that this is a limitation of my setup (I am using Django 2.2.5 with Python 3.7.6), but I can't find confirmation of that. If this is a limitation, my option might be to switch to using mysql.connector.django, which I know will retrieve the records using stored_results() in that specific case, but won't work for the site in general because I think it only supports Python 2.7. My question is: Does anyone know a solution to this issue using my particular setup and keeping django.db.backends.mysql?? I know that this code works (using mysql.connector.django and stored_results()): import mysql.connector def execute_sql(sql_statement, params): conn = mysql.connector.connect(user=settings.DATABASES['default']['USER'], password=settings.DATABASES['default']['PASSWORD'], host=settings.DATABASES['default']['HOST'], database=settings.DATABASES['default']['NAME']) cursor = conn.cursor() cursor.callproc(sql_statement, params) for result in cursor.stored_results(): print(result.fetchall()) I'd like an alternative using django.db.backends.mysql with Python 3.7.6. -
AttributeError: 'NoneType' object has no attribute 'lower'. for django-comments-dab app
I want to use django-comments-dab but I meet this Error, AttributeError: 'NoneType' object has no attribute 'lower'. Request Method: GET Request URL: http://127.0.0.1:8000/2020/9/6/test4 Django Version: 3.1.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'lower' Exception Location: D:\amirblog\venv\lib\site-packages\comment\utils.py, line 26, in get_model_obj Python Executable: D:\amirblog\venv\Scripts\python.exe utils.py def get_model_obj(app_name, model_name, model_id): content_type = ContentType.objects.get(app_label=app_name, model=model_name.lower()) model_object = content_type.get_object_for_this_type(id=model_id) return model_object