Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple .gs code file to multiple sheet on a project
I'm also a newbie on google AppScript. I'm working on two data entry sheets with datasheets for each. I've done coding two .gs code file for them too. Since, two data entry sheets are of same type but for different scope, hence each functions are managed to be unique too. The problem is once in an execution time, only one data entry sheet get executed and produce the result while the next being nothing. I need to run both of them simultaneously just by switching the sheets. Picture includes, a LL_Tool functioning well while HR_Tool is not. Picture includes, a LL_Tool functioning well while HR_Tool is not. -
Django admin site - limit user content on user
admin.py: from django.contrib import admin from .models import Blog admin.site.register(Blog) I have figured out that Django admin serves my needs very well. The only thing I would like to limit is that Users could write/read/edit the Blog applications but for their own entries only. If Alice posts a blog, she can read/write/edit only her posts and not the posts of Bob. Does Django allow anything like this in the admin site or do I need to develop my code? -
Add Redis USER & PASS to Django channel layer
I'm trying to deploy my WebSocket project on the server (for example Heroku). and I have a Redis server that has a USER & PASS. I want to add this to my Django channel layer. I need your help. This is my channel layer: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'USER': 'spadredis-zxs-service', 'PASSWORD': '9zghygpri84f8vl', 'CONFIG': { "hosts": [('188.40.16.3', 32281)], }, }, } This is my error in terminal : await conn.execute('ping') aioredis.errors.AuthError: NOAUTH Authentication required. WebSocket DISCONNECT /ws/chat/lobby_room/ [127.0.0.1:42812] -
Django 404 css file
For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't. Here is my settings.py (showing you only main things) import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.conf import settings from django.views.static import serve urlpatterns = [ path('', include('main.urls')), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] Here is an example of using css files in my templates {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only@1.0.0/dist/bootstrap-grid.min.css"> <link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}"> <link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}"> And this is the error in Chrome Console Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. And also i cant open css files in a new tab. I am getting that error Also, if you remove %20 from the address bar, then I will open … -
Uploading a file in a form group in angular and send it to Django API
I have a form in the front-end having multiple entries, i.e name, email, phone and also a file field entry. A Form group is used to group all these elements in the same form in Angular. There is also a corresponding model in Django, (Using Django Rest Framework). I could not manage to have the file sent to the API, even if the rest of the data is sent correctly and saved on the back-end. First, I am able to upload the file successfully to Front-end, below I log in the console: Second, the object I send is something like this: {"name":"name", "age":49, "email":"email@field.com", "file":File} The File in the JSON is the same file object displayed in the console above. I tested my backend with Postman, I was able to succesfully have the file as well as the other data saved. (I believe the problem to be more on the Front-end side ). Solutions I found for uploading file in Angular used form data (i.e here), these solutions were not convenient as the form consists only of a file, however in my case I have file as well as other data (Form Group). Another thing I tried that did not … -
Django Rest Framework - Filter with logical and
I'm using Django Rest Framework with DjangoFilterBackend to filter through Publications. Every publication can have multiple authors. My api call to filter the api for authors looks like: /api/v1/publication/?author=1&author=2 This gives me every publication that either author 1 or author 2 has been assigned to. Instead I want to only see the publications that both have published. In other words it should be a logic and, not or. My code is the following: models.py class Publication(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=400) author = models.ManyToManyField(Author, blank=False) type = models.ForeignKey( Type, on_delete=models.PROTECT, null=False, default=1) label = models.ManyToManyField(Label, blank=True) date = models.DateField(blank=False, null=False) url = models.URLField(null=True, blank=True) journal = models.CharField(max_length=400, blank=True) bibtex = models.TextField(blank=True) public = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=upload_path, blank=True, null=True) class Meta: ordering = ['-date'] def __str__(self): return self.title views.py class PublicationFilter(django_filters.FilterSet): author = django_filters.ModelMultipleChoiceFilter( queryset=Author.objects.all()) class Meta: model = Publication fields = { 'title': ["exact"], 'author': ["exact"] } class PublicationView(viewsets.ModelViewSet): queryset = Publication.objects.prefetch_related( 'author', 'label').select_related('type') serializer_class = PublicationSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ['title', 'date', 'journal', 'label', 'author'] search_fields = ['title'] ordering_fields = ['date', 'title'] serializers.py class PublicationSerializer(ModelSerializer): type = TypeSerializer(read_only=False, many=False) label = LabelSerializer(read_only=False, many=True) author = AuthorSerializer(read_only=False, many=True) class … -
Django proxy model is visible on admin site but not showing up in permissions section of the production admin site
Locally I can see the proxy model on the admin site and permissions are visible in the permission section and can be assigned to different users. In production I can see the proxy model on the admin site but permissions are not visible in the permission section and therefore cannot be assigned to different users. I'm expecting to see something like : apps|details|can add apps|details|can delete apps|details|can update apps|details|can view in the permissions section. For other models the permissions are visible. Versions: djangorestframework --> 3.12.2 python --> 3.8 Dir: +Apps - profile - models.py - admin.py - details - models.py - admin.py profile/models.py class Profile: # Model Details details/models.py from profile.models import Profile class ProxyProfile(Profile): class Meta: proxy = True app_label = 'details' verbose_name = 'ProxyProfile' verbose_name_plural = 'ProxyProfiles' details/admin.py from models import ProxyProfile class ProxyProfileAdmin(admin.ModelAdmin): # Admin Model Details admin.site.register(ProxyProfile, ProxyProfileAdmin) -
how to understand if the env is activated in a django project
I am just starting to learn django and I am facing the set-up phase. In particular I'd like to ask how to recognize if the virtual environment is activated or not. I know that I can use the command "pip freeze" but in all the tutorial that I am following , when the venv is activated, I can see the vevn name in brackets in the terminal command line. I can correctly activate the venv with the source command and check via the pip freeze command but I have no indication in the command line. I am on a Mac/OS (chip mac) and using python3 thank you -
"Django" filter according to last added related objects
I want to filter according to last added element of related model with foreignkey relationship field. I try a lot but can not achieve, My models like this class Status(models.Model): member= models.ForeignKey(Member, on_delete=models.CASCADE, related_name='member_status') name = models.CharField(max_length=2, choices=("new","old","continue") status_created_at = models.DateTimeField(auto_now_add=True) class Member(models.Model): messageContent= models.TextField(null=True, blank=True) my queryset like this { "id": 1, "member_status": [ { "id": 8, "name": "new", "notes": "", "status_created_at": "2021-01-01T17:55:21.523162Z", "member": 1 }, { "id": 9, "name": "old", "notes": "", "status_created_at": "2022-08-09T17:56:06.995086Z", "order": 1 } ], "messageContent": "example", }, "id": 1, "member_status": [ { "id": 11, "name": "new", "notes": "", "status_created_at": "2021-01-01T17:55:21.523162Z", "member": 1 }, { "id": 12, "name": "continue", "notes": "", "status_created_at": "2022-08-08T17:56:06.995086Z", "order": 1 } ], "messageContent": "example content", } for filtering with FilterSet def filter_queryset(self, queryset): queryset= Member.objects.filter(member_status__name=self.request.query_params.get('memberStatus')) return super().filter_queryset(queryset) I want to filter according to last member status but when filter with "new", all objects get with queryset. I want to get members filtered by last status. Can you help me, please? -
Django HttpResponseRedirect either crashes the site or shows a blank page
I have this issues with Django forms where on each refresh the form would resubmit the last input into the database I tried working with "HttpResponseRedirect" but it would either crash the site or show a blank page. Heres the code of views.py def page(request) : employe = Employe.objects.all() if request.method =='POST' : form = EmployeForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("") else : form = EmployeForm() return render(request,'hello.html',{'employe':employe,'form':form,}) -
How can I display users in the chat list?
In my project, when, for example, user1 asks for help, then user2 finds this request for help and writes to user1 to agree on further actions for help. My chat is registered in such a way that all users who can be written to are displayed on the left, namely, all registered users, and the chat itself is located to the right of this column. I would like the left column to display, for example, user2 (the one who helps) user1 (who is being helped) and those to whom he wrote earlier were displayed. Here is the chat code: html code: {% extends 'chat/base.html' %} {% load static %} {% block header %} <style> #user-list a.bg-dark { background-color: rgb(107, 107, 107) !important; } .list-group-item { cursor: pointer } .chat-bubble { min-width: 40%; max-width: 80%; padding: 5px 15px; } #user-list a:hover * { text-decoration: unset; } .chat-box { overflow: auto; max-width: 100%; } </style> {% endblock %} {% block content %} <div class="container" style="height: 75%;"> <div class="card bg-dark h-100 border-light"> <div class="card-body h-100"> <div class="row h-100"> <div class="col-md-4 border-right h-100"> <div class="list-group bg-dark" id='user-list'> {% for u in users %} {% if not u.id == 1 and not u.id == user.id … -
Django - Filterset without model
I have such http-request route: frontend > proxy (drf) service > data service (sap) The view in proxy service: def get_data_from_remote_api(): # this is mock return [ {'first_name': 'Brad', 'last_name': 'Pitt'}, {'first_name': 'Thomas', 'last_name': 'Cruise'}, {'first_name': 'Robert', 'last_name': 'Downey'}, ] class RemoteUsersView(ViewSet): # TODO: # define filtering class (data from query params) # with multiple fields (`first_name`, `last_name`) # so it is displayed in swagger def list(self, request): users = get_data_from_remote_api() # here need to filter return Response('list') def create(self, request): return Response('create') def retrieve(self, request, pk): return Response('retrieve') def update(self, request, pk): return Response('update') def destroy(self, request, pk): return Response('destroy') As you can see a list of dicts should be filtered. So I cannot use FilterSet because it needs Django model. How can I do that? -
Creating a Html Template with 2 search bars : How to not to loose get method values
I am displaying to different models as list on my Html template. I also want a search bar for both of these tables. If any search post was made on one of the tables I don't want it to overwritten when a new search post is made on the other table. This is what I have : views.py class DocAssignClassification(ListView): model = Documents template_name = 'documentassignation/docassign_classification.html' def get_context_data(self, *args, **kwargs): context = super(DocAssignClassification, self).get_context_data(*args, **kwargs) search_post1 = self.request.GET.get('search1') search_post2 = self.request.GET.get('search2') if search_post1: context['notassigned_list'] = Documents.objects.filter(Q(timestamp__icontains=search_post1) | Q(statut__icontains=search_post1) | Q(filenamebeforeindex__icontains=search_post1) | Q(timestamp__icontains=search_post1)) else: context['notassigned_list'] = Documents.objects.all() if search_post2: context['notassigned_list'] = Entity.objects.filter(Q(timestamp__icontains=search_post1) | Q(statut__icontains=search_post1) | Q(filenamebeforeindex__icontains=search_post1) | Q(timestamp__icontains=search_post1)) else: context['notassigned_list'] = Entity.objects.all() urls.py urlpatterns = [ path('docassignation/classification', DocAssignClassification.as_view(), name="docassign_classification"), ] docassign_classification.html {% comment %} -------------FIRST TABLE---------------------------------- {% endcomment %} <form class="d-flex" action="{% url 'docassign_classification' uuid_contrat uuid_group %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search1"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> <table class="table"> <thead> <tr> <th scope="col"></th> <th scope="col">ID</th> <th scope="col">PdfNameBeforeIndex</th> </tr> </thead> <tbody> <tr > {% for object in notassigned_list %} <td>{{object.id}}</td> <td>{{object.filenamebeforeindex}}</td> </tr> {% endfor %} </tbody> </table> {% comment %} -------------SECOND TABLE---------------------------------- {% endcomment %} <form class="d-flex" action="{% url 'docassign_classification' uuid_contrat uuid_group %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" … -
Django - getting Error Reverse for 'book' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:flight_id/book\\Z']
I am learning the Django framework. Today I was trying to retrieve a URL in HTML template by using <form action="{% url 'book' flight.id %}" method="post"> Also, I've got a function book. Here is the code: def book(request,flight_id): if request.method=="POST": flight=Flight.objects.get(pk=flight_id) passenger=Passenger.objects.get(pk=int(request.POST["passenger"])) passenger.flights.add(flight) return HttpResponseRedirect(reverse("flight",args=(flight.id,))) And this is the urls.py file : urlpatterns = [ path("",views.index,name="index"), path("<int:flight_id>",views.flight,name="flight"), path("<int:flight_id/book",views.book,name="book") ] But I don't know why it is showing an error: NoReverseMatch at /1 Reverse for 'book' with arguments '(1,)' not found. 1 pattern(s) tried: ['<int:flight_id/book\Z'] -
there are no errors in the models, but when I create a migration, this is displayed
(venv) PS C:\django-sites\testsite> python manage.py makemigrations System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace No changes detected (venv) PS C:\django-sites\testsite> my code: from django.db import models class News(models.Model): title = models.CharField(max_length=150) content = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) #id - INT #title - Varchar #content - Text #createrd_at - DateTime #updated_at - DateTime #photo - Image #is_published - Boolean -
How to create a relations between primary key and foreign key in Django models and POST values into DB
I have a Django app which is basically an Online shopping. Right now I have two models: User_details and Extend_user_deatils. In User_details I have(Username, Firstname, lastname, email, etc..). Now after that i need to extend User_details Model with Other Fields so I have Created another Model Extend_user_deatils consisting of (Mobile , Age) columns. Now i need to Link those Two Models, for that I have written an logic with Foreign Key Reference class User_details(models.Model): #Table 1 id = models.AutoField(primary_key=True, db_column='user_id') username = models.CharField(max_length=50) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.CharField(max_length=50) class Extend_user_details(models.Model): #Table 2 user =models.ForeignKey(User_details, on_delete=models.CASCADE,db_column='user_id') mobile = models.BigIntegerField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) When I Open Django admin Page and Post the Data it is Working Fine and Values are posting into DB. When I register as a User from register page . ForeignKey Column(user) from Table2 is showing Null .apart from that all the inputs is posting into DB as shown Screenshot Is there any way to solve this issue Thanks in Advance -
Django indexing the variable
Simple problem, big headache. html: {% for file in files %} {{ file.image }} {% endfor %} output: pdf/filename.jpg What I need: filename.jpg What I tried: {% for file in files %} {{ file.image[XYZ:XYZ] }} {% endfor %} -
How to find Locations inside some range to a particular lat long. python
I am doing a project in flutter and i need to display only the events that are happening in the nearest locations. suppose my location is of latitude 11.2588 and longitude 75.7804. then i need to find events inside latitude 11.2588 +/- 2 and longitude 75.7804 +/-2. I need the backend python service for this. service for finding events occurring inside 2 days is as follows: I want code for finding events in the nearest locations merged inside this. class uview(APIView): def get(self, request): now = dt.now() + timedelta(days=2) d = now.strftime("%Y-%m-%d") ob = Events.objects.filter(date__lte=d) ser = android_serialiser(ob, many=True) return Response(ser.data) def post(self, request): now = dt.now() + timedelta(days=2) d = now.strftime("%Y-%m-%d") ob = Events.objects.filter(e_id=request.data['eid'],user_id=request.data['uid'],date__lte=d) ser = android_serialiser(ob, many=True) return Response(ser.data) any help would be greatly appreciated. Thanks in advance :) -
Django CBV filter corresponding data
I have this view class Dashboard (LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['User'] = User.objects.all() context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() context['BedarfsBerechnung'] = Bedarfs_und_BesetzungsberechnungTabelle.objects.all() context['JahrgangGebunden'] = JahrgangsgebundenTabelle.objects.all() context['JahrgangUebergreifend'] = JahrgangsuebergreifendTabelle.objects.all() context['FoerderBedarf'] = FoerderbedarfschuelerTabelle.objects.all() context['VorbereitungsKlassen'] = VorbereitungsklassenTabelle.objects.all() context['EinzelIntergration'] = EinzelintegrationTabelle.objects.all() context['SonderPaedagogen'] = SonderpaedagogenbedarfTabelle.objects.all() context['Lehrer'] = LehrerTabelle.objects.all() context['GL_Lehrer'] = GL_LehrerTabelle.objects.all() return context I have 2 groups one for Admins and the other for User. And I want as an Admin see all data that a user has made in the template, and also make it editable. The goal is to have User views where User is allowed to edit his data While the Admins can look it up on the Dashboard and also edit it or create something for the User User data reders fine and everything is good Admin does it too if I use objects.all but in that case it shows everything after eacher other like school 1 school 2 school 3 class 1 class 2 class 3 teacher 1 teacher 2 teacher 3 and I want to bundle it like school 1 class 1 teacher 1 and so on -
hi..i'm trying to create website but it gives me this error
from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from . import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('Eshop.urls')) ]+static(settings.MEDIA.URL, document_root=settings.MEDIA_ROOT) this code gives me this ]+static(settings.MEDIA.URL, document_root=settings.MEDIA_ROOT) AttributeError: 'str' object has no attribute 'URL's error: how can i solve it -
How to send socket data from Django website?
I have a simple website with a button on it and I would like to connect that button to a websocket and send arbitrary data to the socket once it is pressed. I need to calculate the time it takes for the signal to be sent and received once the button is pressed. html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Increment</title> </head> <body> {% block content %} Increment Counter <form id="form" method="post" action="#"> {% csrf_token %} <button type="submit", name="increment", value="increment">Increment</button> </form> <script type="text/javascript"> let url = `ws://${window.location.host}/ws/socket-server/` const chatSocket = new WebSocket(url) chatSocket.onmessage = function(e){ let data = JSON.parse(e.data) console.log('Data:', data) } </script> {% endblock %} </body> </html> I am very inexperienced so I am unsure how to do this. Any help would be appreciated. -
adding a user to a group on djngo admin and accessing it via views
if I add a user to a group on Django admin and assign permissions to the group, can I reference that user and its permissions in the views of my project? if yes how do I do it? thanks -
How do I use React with Django?
I have a Django project that currently run with a html template and vanilla js. If I want to shift the frontend to ReactJs. Is it possible to do so with minimal code changes in the backend? How big a change to the backend should I expect? -
no account logout Django Two factor auth
i am trying to implement two factor auth in my Django app. However, the user can bypass it by using the login provided by django.contrib.auth. is there any way i can redirect the user to /account/login when they browse for /login? Things i tried and have not work: removing django.contrib.auth (need this to logout) redundant login urls -
Django, model non-non-persistence field is None
In my model, I have a non-persistence field called 'client_secret'. The client_hash field is used in the custom model save method to calculate the hash. It worked as expected, but when I tried to save a new instance, self.client_secret is still None, why? class Client(models.Model): client_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) active = models.BooleanField(default=False) client_hash = models.BinaryField(editable=False, blank=True, null=True) # non-persistent field used to cal the hash client_secret = None def save(self, *args, **kwargs): if self._state.adding: self.client_hash = make_hash(self.client_secret) Trying to save a new client, client_secret is None in model save: Client.objects.create(active=True, client_secret='test_secret')