Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
passing video_url to html template in django
I am trying to dispaly video in my html page by passing url as dict to template in django view named as succes def success(request): url_video="/media/video1.mp4" return render(request,"payment/success.html",{"url_video":url_video}) my template code is all clear it has no errors i am getting this error on command prompt Not Found: /succes/media/video1.mp4 I don't understand why i get success/ in front of url i have passed.The video file is in media/video1.mp4 location but it is not getting displayed.let me know any changes i need to make.thanks -
Django Reversion - How to use With Django Rest
I'm trying to use Django Reversion with my My Django Rest, but i still confuse about it or i just couldn't what i want in Document. Here what i tried `Settings INSTALLED_APPS = [ .... 'reversion' ] MIDDLEWARE = [ 'reversion.middleware.RevisionMiddleware' ] In Model @reversion.register() class History(models.Model): pass In ModelViewset from reversion.views import RevisionMixin class HistoryViewset(RevisionMixin, viewsets.ModelViewSet): queryset = History.objects.all() serializer_class = HistorySerializer filter_backends = (filters.DjangoFilterBackend,) # if pagination page = none, it will return all page def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if 'page' in request.query_params: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Then i try to update My Model and try to GET request from api endpoint, i got null Value. What do i Missing??? I'll appreciate of all ur Help. Thanks... -
Confusion regarding Django and SECRET_KEY
Recently finished my app and I am ready to deploy it but I don't understand how to set the application's SECRET_KEY. I'm trying to change my database from sqlite to postgresql, but I get the following error: raise KeyError(key) from None KeyError: 'SECRET_KEY' development.py from nurs_course.settings.common import * ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] SECRET_KEY = '9t*re^fdqd%-o_&zsu25(!@kcbk*k=6vebh(d*9r)+j8w%7ci1' DEBUG = True production.py from nurs_course.settings.common import * DEBUG = False SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: update this when you have the production host ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] common.py has all the other settings required. I use Windows OS w/ Powershell. I've been stuck on this for a bit and I am just unsure how to set the SECRET_KEY properly. Any help would be appreciated! -
How can I convert this SQL query to Postgresql in Django?
I have this query that I want to write in Postgres in Django. I can phrase the query using SQL command as DELETE FROM NOTIFICATION_MESSAGES.JSONFIELD["notifications"] WHERE POST_ID=POST_ID AND ACTIVITY="LIKE"; My jsonfield looks something like this: user_id : { notifications : { post_id: post_id, activity:[like, comment...] } } } Please let me know if you need any more information. Thanks in advance! EDIT: Till Now I have tried this: notification_messages = NotificationMessages.objects.get(user__id=user) notification_messages.doc["notifications"].pop(post_id) notification_messages.doc["notifications"].pop("activity") -
Django save a new custom id every time I create a new instance
I have Product db model, which should generate a custom_id every time a new Product has been added. class Product(models.Model): # Common code = models.CharField(_("Course Code"), blank=True, max_length=100) #... Other Fields def __str__(self): return self.code def custom_seq(pk, letters=4, digits=3): """ Generates a sequence when letters=4, digits=3 then, 'AAAA000', 'AAAA001', ..., 'ZZZZ999' Generates a sequence when letters=3, digits=4 then, 'AAA0000', 'AAA0001',..., 'ZZZ9999' """ alpha_list = [string.ascii_uppercase]*letters digit_list = [string.digits]*digits for i in itertools.product(*alpha_list): for j in itertools.product(*digit_list): yield "".join(i + j) def save(self, *args, **kwargs): product_code = next(self.custom_seq()) print("Code", product_code) #-- prints `AAAA000` if self.code is None: self.code = f"{product_code}" return super(Product, self).save(*args, **kwargs) The above code has 2 issues: Everytime, I save a new product its generating only first sequence of custom_seq() ie. AAAA000. code is not getting saved but rest of the object is getting saved -
Django - save under determined condition
I want a FeedstockFormula model (it has a ratio and a name field) to save if and only if the ratio value is something different than 0 or null or blank. Ps.: I'm on a inline formset and when django adds the new empty form to it, the fields are empty, so I can't click on the button to save because it leads to an error stating 'NOT NULL constraint failed' -
ModuleNotFoundError: No module named 'AgregarUsuarios'
from AgregarUsuarios.models import admin_text as at la linea anterior me marca el siguiente error ModuleNotFoundError: No module named 'AgregarUsuarios' El scrip desde donde tengo esa linea de codigo esta en el mismo directorio que mi aplicacion, alguien me podria decir porque me da el error y como lo puedo solucionar? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'social_django', 'AgregarUsuarios', #Agregando la app con la que agrego usuarios] La aplicacion ya esta dentro de la configuracion -
Django update InMemoryUploadedFile with Piexif
I am trying to strip out exif data on an uploaded image before continuing to do some other processing to it before saving to the server. I am using piexif as in this answer to strip out the exif metadata. However, piexif.insert() documentation requires the path to the image being modified. Can piexif be used to write to a file in memory? An InMemoryUploadedFile has a name attribute which seems to provide the path to the file, however it is not working as expected. def modifyAndSaveImage(): # Get the uploaded image as an InMemoryUploadedFile i = form.cleaned_data['image'] # Use piexif to generate an empty exif byte dump exif_bytes = piexif.dump({}) piexif.insert(exif_bytes, i._name) # What should the second parameter be? # continue using i... -
Why does my websocket keep disconnecting in Django Channels App?
I have been on this for a month now without a working solution. Everything works fine in production but I have been trying to deploy my django-channels application using nginx as reverse proxy, supervisor to keep servers running, gunicorn to serve http requests and I am stuck at the weboscket request part using daphne to process http requests. I am bindig with unix sockets: gunicorn.sock and daphne.sock The Console returns: WebSocket connection to 'ws://theminglemarket.com/ws/chat/undefined/' failed: Error during WebSocket handshake: Unexpected response code: 500 My supervisor config: directory=/home/path/to/src command=/home/path/to/venv/bin/gunicorn_start user=root autostart=true autorestart=true redirect_stderr=true stdout_logfile=/path/to/log/gunicorn/gunicorn-error.log [program:serverinterface] directory=/home/path/to/src command=/home/path/to/venv/bin/daphne -u /var/run/daphne.sock chat.asgi:application autostart=true autorestart=true stopasgroup=true user=root stdout_logfile = /path/to/log/gunicorn/daphne-error.log Redis server is up and Running, Sure of that, using redis-server my nginx configurations: upstream channels-backend { # server 0.0.0.0:8001; server unix:/var/run/daphne.sock fail_timeout=0; } upstream app_server { server unix:/var/run/gunicorn.sock fail_timeout=0; } server { listen 80; listen [::]:80; server_name theminglemarket.com www.theminglemarket.com; keepalive_timeout 5; client_max_body_size 4G; access_log /home/path/to/logs/nginx-access.log; error_log /home/path/to/logs/nginx-error.log; location /static/ { alias /home/path/to/src/static/; # try_files $uri $uri/ =404; } location / { try_files $uri @proxy_to_app; } location /ws/ { try_files $uri @proxy_to_ws; } location @proxy_to_ws { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; … -
How to get html from page in Django
I was trying to implement some testing in Django, and I needed to check the data on the web page with a string, but I couldn't retrieve data from the web page. so, how can I get data(html) from web page? my tests.py from rest_framework.test import APITestCase class TicketTestCase(APITestCase): def test_user_details_on_ticket_id(self): response = self.client.get(f"/api/ticket/1") print(response.content) # this returns empty data in bytes # I want to check this #self.assertEquals(response.data "helloworld") -
Cannot Filter ChoiceField in Django with Multiple Keys and One Value
I am trying to filter a choicefield in Django by attempting to display one value with multiple keys. I understand choicefields are normally one key per value, but I have some values (names) which are the same with different id's in my database. I do not want to display the names more than once in the choicefield, so I wrote code to display items of a dictionary as a tuple with several id's and one value. I would like to filter these objects (animals) by "species" and "gender," so I created two modelchoicefields in my form. I am able to filter singular names by "species" and "gender" but not the duplicate names. The only error messages I get are Not Found: /filter_species/(1, 4)/ and "GET /filter_gender/(1,%204)/ HTTP/1.1" 404 4306. The "1" and "4" are respectively id's 1 and 4 for two animals with the same name. I have included my code from my forms, views, URLs, and animals template. Any help would be much appreciated as I am fairly new to Django and am still learning. Note: I am wondering if my URLs may be an issue with not showing regex for the parenthesis (tuple)? If so, I've been researching … -
Django, python3, on install I get: "Parent module 'setuptools' not loaded"
I see lots of errors and suggestions about Parent module '' not loaded, ... I don't see any about specifically "out of the box" django 3.5. $ mkvirtualenv foobar -p /usr/bin/python3 Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /home/isaac/.virtualenvs/foobar/bin/python3 Also creating executable in /home/isaac/.virtualenvs/foobar/bin/python Installing setuptools, pkg_resources, pip, wheel...done. [foobar] $ pip install django Collecting django Using cached Django-2.2.15-py3-none-any.whl (7.5 MB) Collecting pytz Using cached pytz-2020.1-py2.py3-none-any.whl (510 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.3.1-py2.py3-none-any.whl (40 kB) Installing collected packages: pytz, sqlparse, django Successfully installed django-2.2.15 pytz-2020.1 sqlparse-0.3.1 [foobar] $ python Python 3.5.3 (default, Jul 9 2020, 13:00:10) [GCC 6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 666, in _load_unlocked File "<frozen importlib._bootstrap>", line 577, in module_from_spec File "/home/isaac/.virtualenvs/foobar/lib/python3.5/site-packages/_distutils_hack/__init__.py", line 82, in create_module return importlib.import_module('._distutils', 'setuptools') File "/home/isaac/.virtualenvs/foobar/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line … -
I am having a problem linking my HTML pages in Python Django web framework could you help me with that?
I am getting an error when I run my django application and I saw that I have a problem in my url configuration and templates linking app/views.py from django.shortcuts import render from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'blog/index.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' def home(request): return render(request, 'blog/home.html') def about(request): return render(request, 'blog/about.html') def contact(request): return render(request, 'blog/contact1.html') models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title project/urls.py from django.contrib import admin from django.conf.urls import url, include from blog import views urlpatterns = [ url(r'', views.home, name='home'), url(r'^admin/', admin.site.urls), url(r'^blog/', include('blog.urls')), ] app/urls.py from django.conf.urls import url from blog import views #Template tagging app_name = 'blog' urlpatterns = [ url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'', views.PostList.as_view(), name='index'), url(r'<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] templates/home.html --one of my html files <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta … -
Django collectsatic keeps collecting old files
When I run my localserver I noticed that Django is loading a background image I changed a while ago. I checked the folder where my static files are and my new background image was there. Both images had the same name. I changed the name and did collectstatic again and in my STATIC_ROOT the old image appeared. Later I tried python manage.py collectstatic --clear, I also cleared my cache, restarted my server. I tried deleting the file and changing the name and the path and Django keeps collecting old static. Here's my settings.py import os from .passwords import * BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = SECRET_KEY DEBUG = True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'contact', 'home', 'crispy_forms', 'mathfilters', 'ckeditor', 'ckeditor_uploader' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'spanish.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'spanish.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': NAME, 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': '5432' } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
Django static file image into template 404 error
I am trying to load a picture into a a Django 3.1 Template. I followed the documentation on the https://docs.djangoproject.com/en/3.0/howto/static-files/ and looked elsewhere for an answer but was not able to solve the issue. Here is all the code that I think is relevant: from settings.py INSTALLED_APPS = [ 'memberships.apps.MembershipsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] from url.py urlpatterns = [ path('', views.index, name='index'), path('memberships/', include('memberships.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and from the template file: {% load static %} ... <img src="{% static 'static/dribblz/images/multicolored-soccer-ball-on-green-field-47730.png' %}" alt="Football on the pitch"> My files are structured such as: dribblz/ -> dribblz/ --> settings.py --> url.py --> views.py ->static/dribblz/images/image.png ->templates/home.html I don't know what other information I can give that may be useful. Thanks in advance. -
How to solve problem with Django & Mongo on azure appservice
I managed to develop django app with vs code but I couldnt publish it. I think I couldnt set up virtual env properly. But then I made it with normal visual studio and that created me virtual environment which azure accepted well. It was working well but with sqlite. I needed mongoDB. I found instructions for dns and djongo and settings.py, so on terminal: 'python manage.py runserver' (locally, but with atlas mongo) it works well. But now, azure isn´t accepting my app. It says only SQL this and that XXXX are accepted... Could someone help me? Heres all the code: https://github.com/Point-SimoSiren/django-suppliers It is now again with sqlite but setting.py: DATABASES mongo stuff I used are on comments right below that. Only virtual env code is in github repo. -
check variable is numerical django template
Hi I want to check if my variable is numeric in Django template and I tried this code {% if isnumeric(item) %} <h1>{{item}}</h1> {% endif %} but this throws me this error Could not parse the remainder: '(item)' from 'isnumeric(item)' I tried to find a builtin template tag or filter in this page https://docs.djangoproject.com/en/3.1/ref/templates/builtins/ of Django document and I searched for this question in StackOverflow too but I did not found my answer -
wordpress + nginx + django: error too many redirect
I have just included wordpress into a project to replace django for the landing page of the website. Up to that point everything server related is working just fine. I am a bit wary to make modification to nginx configuration because I am far from an expert in the domain. I have tried including wordpress location by disabling what I had before which was from django and it is resulting in ERROR TOO MANY REDIRECT here is the code for /nginx/sites-enabled/conf.d that I have: server { server_name mysite.com www.mysite.com; root /var/www/html; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location ^~ / { alias /home/ubuntu/var/www/html/wordpress; index index.php; if (!-e $request_filename) { rewrite ^ /index.php last; } location ~ /wp-content/uploads/ { expires 30d; } location ~ \.php$ { if (!-f $request_filename) { rewrite ^ /index.php last; } include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; } location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { if (!-f $request_filename) { rewrite ^ /index.php last; } expires 30d; } } } server { if ($host = www.mysite.com) { return 301 https://$host$request_uri; listen 80; server_name mysite.com www.mysite.com; return 404; … -
Django HttpResponse returning object instead of stated string
I am using Django and React. I need to send a string from Django to React. I have tried using both HttpResponse and JsonResponse but both seem to be returning a response object that does not include the data. The response object from React looks like this: Response {type: "cors", url: "http://localhost:8000/post/", redirected: false, status: 200, ok: true, …} body: (...) bodyUsed: false headers: Headers {} ok: true redirected: false status: 200 statusText: "OK" type: "cors" url: "http://localhost:8000/post/" __proto__: Response Here is my Django from django.http import HttpResponse, JsonResponse def index(request): string1 = "" if request.method == 'POST': # ...processing upload... string1 = "Hello World" return HttpResponse(string1) And my react request looks like this: async function handleSubmit(event) { let formData = new FormData(); formData.append(file) fetch("http://localhost:8000/post/", { method: "POST", body: formData, enctype: "multipart/form-data", }).then((res) => { console.log(res); }); How can I get the data I need (string1) included in the response object (or without the response object)? I've looked on StackOverflow and around the web and haven't found a solution. I am also not sure whether this is a problem with Django or React but it seems like a Django problem. (Also, I don't believe it is a CORS Problem as … -
how to user prefetch_related and select_related in django rest framework
Hi I have something like this in Model class Task(model.Models): name=model.CharField(max=100) class attachments(model.Models): file=model.FileField() task=model.Foreginkey(Task) In views class myView(APIView): task=Task.object.get(id=1) task_serilizer=TaskSerilizer(task, many=False) in Serilizer class Myserilizer(aerilizer.Serilizers): class Meta: fields='__all__' Now I want to know how I can user select related and prefetch related , its quite confusing right now (And I wrote this code using mobile so kindly forgive me about this) -
Saving 'views.py': Applying code action 'Sort imports'
currently trying to save some python codes in my django but vscode keep showing this popup Saving 'views.py': Applying code action 'Sort imports'. and i dont know how to go about it. I also launched the vscode from my anaconda navigator -
Django DRF (De-)Serializer not working for me?
I'm stumled upon a case I don't understand. I have two related models: class Course(models.Model): code = models.CharField(max_length=10, default='') semester = models.CharField(max_length=10, default='') class Meta: unique_together = [['code', 'semester']] and: class StudentWork(models.Model): code = models.CharField(max_length=10, default='') course = models.ForeignKey(Course,on_delete=models.CASCADE, related_name='student_works') deadline = models.DateTimeField(blank=True) In the StudentWorkSerializer I'd like to expand a course field into [code, semester]: class CourseNaturalSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ['code', 'semester'] class StudentWorkWithCourseSerializer(serializers.ModelSerializer): course = CourseNaturalSerializer(read_only=True) class Meta: model = StudentWork fields = ['code', 'course', 'deadline'] This works nicely for GET, e.g. I receive this: {'code': 'HW1', 'course': {'code': 'T101', 'semester': 'S20'}, 'deadline': '2020-09-04T23:59:00+03:00'} but this does not work for POST: POST /studentworks json=dict(code='HW2', course={"code": "T101", "semester": "S20"}, deadline="2020-09-04T23:59") says in the stacktrace: django.db.utils.IntegrityError: NOT NULL constraint failed: botdb_studentwork.course_id So this looks to me that {"code": "T101", "semester": "S20"} does not de-serialize into Course object and it's id is not passed to StudentWork's create? What should I do? Thanks in advance! -
Django form not submitting in POST
Been having an issue where I am unable to upload files into my form. From what I can gather on my own, it's because I'm not submitting in POST (since uploaded files aren't saved unless you're in POST) but I don't know why that's the case. Here's my code: Views.py def commission(request): if request.method == "POST": form = CommissionForm(request.POST) if form.is_valid(): subject = str(form.cleaned_data.get("name")) + "'s commission request" message = form.cleaned_data.get("name") + ",\nhas requested a commission, with the following request:\n" + form.cleaned_data.get("request") + "\n Reply to them using their email:\n" + form.cleaned_data['email'] email = form.cleaned_data['email'] print(form.cleaned_data) attach = request.FILES['reference'] try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) if attach != None: mail.attach(attach.name, attach.read(), attach.content_type) mail.send() return redirect("main-commissions-success") except: return render(request, "main/commissions.html", {"form": form}) return render(request, "main/commissions.html", {"form": form}) else: form = CommissionForm() return render(request, "main/commissions.html", {"form": form}) Commissions.html <div class="row"> <div class="content-section card w-50 mx-auto my-5"> <div class="card-body"> <form method="POST" action="" class="border border-light m-10" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 text-center">Request A Painting</legend> {{ form|crispy }} </fieldset> <div class="form-group text-center"> <button class="btn btn-outline-info" type="submit">Send Request</button> </div> </form> </div> </div> </div> And since this has no model relation, I'm not going to bother adding it here. Hopefully someone can … -
Django Extended Group's Permissions not applied to users
So I have extended Django's Group model to add an extra field like so: class MyModel(Group): extra_field = models.TextField(null=True, blank=True) On doing this, each instance of MyModel created, creates a Group instance as well. If I add a user to the resulting group with user.groups.add(group), the group is added as expected. However, the permissions from the MyModel group do not seem to have trickled down to the user i.e Doing user.get_all_permissions(), get_group_permissions() or even testing a user.has_permission(mygroup_permission) returns nothing. Only permissions from pure Group instances(created before extending the model) are shown. Is there anything I need to do for permissions on customised groups to be visible on the users? TIA -
Django Unsupported Look Unsupported lookup 'expiration_date' for AutoField or join on the field not permitted
I am new to django and i am getting this error My Models are: class Client(models.Model): """ A client who holds licenses to packages """ client_name = models.CharField(max_length=120, unique=True) def __str__(self): return self.client_name class License(models.Model): """ Data model for a client license allowing access to a package """ client = models.ForeignKey(Client, on_delete=models.DO_NOTHING, related_name="client_licenses") created_datetime = models.DateTimeField(auto_now=True) expiration_datetime = models.DateTimeField(default=get_default_license_expiration(),editable=False) def __str__(self): return (self.client.client_name +" "+ str(self.package) +" "+ str(self.license_type)) def get_default_license_expiration(): """Get the default expiration datetime""" return datetime.utcnow() + LICENSE_EXPIRATION_DELTA I want to annotate the related expiration date field but i get this error Client.objects.prefetch_related("client_licenses")\ .annotate( expiration = F('client_licenses__expiration_date') )\ Even if i just put this column name in values() Client.objects.prefetch_related("client_licenses")\ .values('client_licenses__expiration_date') I am more concerned about what is the cause of this error as i can't figure it out and thats why i can't find a fix for it Any sort of help would be appreciated