Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM calculate all Members of Group
I am trying to annotate all my groups by the number of Users, that apply to a certain condition. In this case I want to get a number of users, that have related Offer model to the Task in the Group. Users can create Offers to the Task. One Task can be related to one Group. So as the result of annotating Groups I want something like this | id | name | runners_num | | -- | ------ | ----------- | | 1 | name1 | 3 | | 2 | name2 | 5 | With a query below I can get this count as a dictionary runners = User.objects.filter( offer__tack__group_id=1 ).distinct( ).values( 'id' ).aggregate( count=Count('id') ) output: {'count': 5} But I can't figure out how to do this with OuterRef clause runners = User.objects.filter( offer__task__group_id=OuterRef('id') ).distinct().values('id') groups = Group.objects.annotate( runners_num=Count(Subquery(runners)) ) It ended up with this wrong query SELECT "groups"."id", "groups"."name", COUNT( ( SELECT DISTINCT U0."id" FROM "users" U0 INNER JOIN "offers" U1 ON (U0."id" = U1."runner_id") INNER JOIN "tasks" U2 ON (U1."task_id" = U2."id") WHERE U2."group_id" = ("groups"."id") ) ) AS "runners_num" FROM "groups" GROUP BY "groups"."id" LIMIT 21 My models class Task(models.Model): tasker = models.ForeignKey( "user.User", … -
Django: In templates using an if statement inside a for loop of _set.all doesn't work. why?
If you have a better way to reformulate my question please let me know. My template is as follows: {% for x in group.groupmember_set.all %} {% if x.user != user.username %} {{ x.user }} {% endif %} {% endfor %} This statement prints all users in the Group, as though the if statement doesn't exist. If I remove the if statement, eventually prints the same and makes sense... I want to filter out user.username with an if statement but doesn't work. What is wrong? Group has a ManytoMany relation with User through GroupMember. My models.py file reads: class Group(models.Model): name = models.CharField(max_length=255, unique=True) members = models.ManyToManyField(User,through="GroupMember") class GroupMember(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) group = models.ForeignKey(Group,on_delete=models.CASCADE,) is_valid = models.BooleanField(default=False) and in views.py I use DetailView, e.g., class SingleGroup(DetailView): model = Group -
How to implement last visited functionality for articles in django rest framework
I have this model of Articles where users can post articles. add comments etc. I want to add a filter where it can filter articles according to user which have visited the last article or commented the last article Please guide me how can i achieve this functionality in django/drf this is my models class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateField(auto_now_add=True, null=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") def get_id(self): return self.headline + ' belongs to ' + 'id ' + str(self.id) class Meta: verbose_name_plural= "Articles" ordering=("id" , "headline", "abstract", "content", "published", "isDraft", "created_by") def __str__(self): return f'{self.headline}' -
How to rename standart django-registration templates' names
I am using django-registration standard urlpatterns, but i want to rename its template name. By default it is "registration/login.html". In source code there is a parameter "template_name" that i want to change: class LoginView(RedirectURLMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None template_name = "registration/login.html" redirect_authenticated_user = False extra_context = None How and where i can do it? (p.s. django.contrib.auth.views.LoginView.template_name = name is not working, or i just write it in incorrect place) -
Creating PeriodicTask in celery django
I need to send notifications with certain interval when Ticket model instance has been created. For that I decided to use celery-beat. I created signals.py where I create PeriodicTask intance. When I create new Ticket instance the PeriodicTask instance is created in DB but the task is not running. What do I do wrong? signals.py from datetime import datetime from django.db.models.signals import post_save from django.dispatch import receiver from .models import Ticket from django_celery_beat.models import PeriodicTask, IntervalSchedule import json @receiver(post_save,sender=Ticket) def notification_handler(sender, instance, created, **kwargs): if created: interval, created = IntervalSchedule.objects.get_or_create(every=10, period='seconds') task = PeriodicTask.objects.create(interval=interval,enabled=True, name='notification_' + str(instance.id), task="create", args=json.dumps((instance.id, ))) tasks.py from celery import shared_task @shared_task(name="create") def create(data): print("Some logic here") celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'helpdesk.settings') app = Celery('helpdesk') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() setting.py CELERY_BROKER_URL = 'redis://redis:6379/0' The commands I use for launching celery and celery-beat: beat: celery -A helpdesk beat celery: celery -A … -
How to create many to many relationships using three tables Django
I have three tables Client, Company, Account and want to create a relation between then so that they can satisfy following conditions. One client can have many accounts. One Account can be associated with many users. One company can have many accounts. One account can be in many companies. One client can have many companies. One Company can be associated with many companies. Tables are as follows: class Company(models.Model): name = models.CharField(max_length=255) website_url = models.CharField(max_length=255, null=True, blank=True, default='') class Account(models.Model): customer_id = models.CharField(max_length=20, null=True, blank=True) name = models.CharField(max_length=255) class Client(models.Model): name = models.CharField(max_length=255) age = models.CharField(max_length=10, null=True, blank=True) I don't know how to define many to many relationships for these tables. -
adding fields from models to function in django
I'm trying to add all parameters from class Room(number, beds, capacity) to show it on room list page. In result I want to to see all other information under the category which is linked with booking form. I've tried in various ways but I can't solve it. def RoomListView(request): room = Room.objects.all()[0] room_categories = dict(room.ROOM_CATEGORIES) room_values = room_categories.values() room_list = [] for room_category in room_categories: room = room_categories.get(room_category) room_url = reverse('hotelbooking:RoomDetailView', kwargs={'category': room_category}) room_list.append((room, room_url)) context = { 'room_list': room_list, } return render(request, 'room_list.html', context) -
django-cors-headers allow any request and i didn't put any origin why?
Here the code i make post request from frontend to this api that didn't raise any problem, look at this code i didn't allow any origin so why accept requests ? CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ ] CORS_ORIGIN_WHITELIST = [ ] CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] -
Is there a way to upload video file with timestamp in Django Rest Framework?
Is there any way in DRF or just python to post mp4 video with set up timestamp? For example i want to post a video that will start at 10 second if user will display it on frontend. -
Add cluster information to table after KMeans
I am building a django application that uses Kmeans to cluster a particular table in the database. I'd like to add the clusters to the table in the database after the clustering process is done. Here is a sample of the code. This code runs every time someone registers This prints the data frame adding an extra column to show which cluster they belong to. How would I go about it if I want to add those clusters to the original data frame, the table in the database. -
I get AnonymusUser in Ajax GET request DJANGO
I am working in a Django application and I need to get some data with a GET request from a template. I have set up a AJAX get request as follows: $.ajax({ type: 'GET', dataType: "json", url: "https://www.url.com/enpd/var1/var2/var3", xhrFields: { withCredentials: true }, success: function(obj) { ... }, error: function(data) { ... } }); And in the views.py I have the following: @login_required(login_url='/login') def getReq(request, var1, var2, var3): user = request.user if user.is_authenticated: ... else: return HttpResponse({user}) And I always get the request user as "AnonymusUser". It's like the AJAX get request is not sending the user details in the request. Why is that happening? I have read through many posts and nothing helped... PD: I created a custom user, don't know if that may cause any issue? -
Django django-filters ipaddress mysql
filter for ip not working properly model.py class Network(models.Model): start_ip_address = models.GenericIPAddressField(protocol='both', blank=True, null=True) end_ip_address = models.GenericIPAddressField(protocol='both', blank=True, null=True) filters.py class NetworkFilter(django_filters.FilterSet): f_by_address = django_filters.CharFilter(method='filter_by_address', label="BY ADDRESS") def filter_by_address(self, queryset, name, value): return queryset.filter(start_ip_address__lt=value, end_ip_address__gt=value) class Meta: model = Network fields = ['id', 'start_ip_address',] filter by address result to SELECT `network_network`.`id`, start_ip_address, `network_network`.`end_ip_address` FROM `network_network` WHERE (`network_network`.`end_ip_address` > 10.172.148.12 AND `network_network`.`start_ip_address` < 10.172.148.12) ORDER BY `network_network`.`id` ASC my table doesn contains so much records, but even now I got into the troubles. mysql> SELECT start_ip_address, end_ip_address from network_network where (end_ip_address > '10.172.148.12' AND start_ip_address < '10.172.148.12'); +------------------+----------------+ | start_ip_address | end_ip_address | +------------------+----------------+ | 10.172.14.1 | 10.172.15.254 | | 10.172.148.1 | 10.172.149.254 | +------------------+----------------+ 2 rows in set (0.01 sec) mysql> SELECT start_ip_address, end_ip_address FROM network_network WHERE (INET_ATON("10.172.148.12") BETWEEN INET_ATON(start_ip_address) AND INET_ATON(end_ip_address)); +------------------+----------------+ | start_ip_address | end_ip_address | +------------------+----------------+ | 10.172.148.1 | 10.172.149.254 | +------------------+----------------+ 1 row in set (0.01 sec) Not sure what to do in order to make this filter working accurate over django ORM. Can't use raw SQL as example is simplified. -
Large JSON data over POST request
I have a system working as a swarm, with a lot of independent devices running Django and a main Queen (running Django as well) gathering data from the swam. Each device from the swarm is sending the new data to the queen using a POST request with the data in a json. Each data recorded in the device is then updated to mark it as sent to the queen and doesn't need to be resent later. the problem is that each dataset is about 10 MB and I am getting a timeout error while processing the post request. The solution I got at the moment is far from optimal: I split the upload in batches of 500 records and send several post requests. After each successful upload, I update each record 1 by 1. This solution has some performance issues. Things I would need to improve: manage to send all data in 1 single request Reduce the data volume to be sent Update the data faster on each device after so the questions are: Is there a way to keep the post request alive for longer? I am thinking of using gzip to send the data. Is it something to … -
how to view the extension file mention below?
I would like to view (.tiff .ecw) extension files, orthoimage [large files] through online with map integration using python JavaScript ...any one can help or suggest some to create the Web Apps -
ImportError: cannot import name 'Profile' from partially initialized module 'profiles.models' (most likely due to a circular import)
I am importing Profile from profiles.models into meta.models, but showing the subject error. Can't find cutom solution, even though there are similar problems with different solutions out there but not working in my case. Here is my profiles.models from django.db import models from django.contrib.auth.models import User from meta.models import Designation class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, help_text = 'Foreign Key From User') avatar = models.ImageField(upload_to='avatars', default='no_picture.png') designation = models.ForeignKey(Designation, on_delete = models.CASCADE, null=True) def __str__(self): return str(self.user) Here is my meta.models, where i am importing from profiles.models from django.db import models from profiles.models import Profile class Designation(models.Model): DesignationName = models.CharField(max_length = 20, blank=True,null= True) DesignationScale = models.PositiveIntegerField() def __str__(self): return str(self.DesignationName) class DutyPlaceSensitivity(models.Model): sensitivity = models.CharField(max_length = 12, blank=True, null = True) def __str__(self): return str(self.sensitivity) class DutyPlaces(models.Model): DutyPlaceName = models.CharField(max_length =20, blank = True, null = True) sensitivity = models.ForeignKey(DutyPlaceSensitivity, on_delete=models.CASCADE) class ActingAs(models.Model): acting_as_title = models.CharField(max_length = 12) def __str__(self): return str(self.acting_as_title) class PlaceOfPosting(models.Model): UserProfile = models.OneToOneField(Profile, on_delete=models.CASCADE) acting_as = models.ForeignKey(ActingAs, on_delete = models.CASCADE) def __str__(self): return f"{self.UserProfile} - {self.acting_as}" class TaskType(models.Model): taskTypeName = models.CharField(max_length=20) taskDescription = models.TextField(null = True, blank=True) def __str__(self): return str(self.taskTypeName) class TaskPriority(models.Model): priority_title = models.CharField(max_length = 12) def __str__(self): return str(self.priority_title) class Tasks(models.Model): task_name … -
Move Settings folder to settings.py
Recently I received a started project with Django and Python, the project is constantly giving us errors, but some of them are probably because the last programmer made a directory of settings instead a settings.py. My question is if there is some way of move all this .py in the settings folder to a new python file called settings.py, to optimize it. Thanks! -
Django - Unable to find object using pk (Matching query DoesNotExist)
Whenever I try to create a "Tour" for a "User" I get this error: "DoesNotExist at /add-tour/FAjK5CryF8/ - User matching query does not exist." Specifically the problems seems to come from this line of code: user = User.objects.get(pk=pk) models.py class Tour(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tour_date = models.DateField(default=date.today) tour_fans = models.ForeignKey(FanAccount, on_delete=models.PROTECT) def __str__(self): return f"{self.user} del {self.tour_date}" views.py def tour_new(request, pk): user = User.objects.get(pk=pk) if request.method == "POST": form = TourForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.tour_fans = request.user form.instance.user = user instance.save() form.save() return render(request, "tour.html", {"form": TourForm(), "success": True}) else: form = TourForm() return render(request, "tour.html", {"form": form}) For "User" I'm using a custom Primary Key (ShortUUID). I'm new to Python and Django so it may be something easily solvable, but after hours of attempts I seem unable to solve it. -
Django best way to stream video to your frontend (php or react.js)
I want to make a website for watching videos like vimeo or youtube but i have no idea how to watch/stream the videos on the frontend from my django backend. So i have the videos in my database how will someone watch them from his browser -
Edit a foreign key's fields in a template
I'm unsure of how I can edit a foreign key's fields from the template of another model - my changes do not update the model on post, see below. models class Projects(models.Model): name = models.CharField(max_length=250) class Current(models.Model): fk_user = models.OneToOneField(User, on_delete=models.CASCADE) fk_project = models.ForeignKey(projects, default='1', on_delete=models.CASCADE) views class current(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Current fields = [ 'fk_project' ] template_name = 'users/current.html' context_object_name = 'current' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() # return super().form_valid(form) return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False current.html <form method="POST">{% csrf_token %} <input type="text" value="{{ current.fk_project.name }}"/> <button type="submit">post</button> -
Django UnicodeEncodeError, can't encode special czech characters
i built application in django that gives the user a table of employees, it works okay to a point when i want to filter this table - basically I'm sending HTTP GET request with a name or part of a name as one of the parameters. Problem is, I'm czech and we use weird characters in our names like Ř/ř or Ě/ě, i cannot filter these people because there's an encoding problem. UnicodeEncodeError: 'latin-1' codec can't encode character '\u0161' in position 324: ordinal not in range(256) My understanding is that django is trying to use latin-1 which doesn't contain those characters, so it cannot handle them. How would i change that? I'm lost, please help me, thank you. This is my view function i use: def track1(request): year = int(request.COOKIES.get('year', str(date.today().year))) month = int(request.COOKIES.get('month', str(date.today().month - 1))) name = request.COOKIES.get('name', '') project = request.COOKIES.get('project', '') if month == 0: month = 12 sql_query = """select p.name project, p.id projectid, i.title issue, i.id issueid, u.id userid, u.name, replace(ROUND(t.time_spent/3600.0, 1)::text, '.', ',') as spent, TO_CHAR(t.spent_at + interval '2h', 'dd.mm.yyyy HH24:MI:SS') date_spent, substring(n.note for 300) note from issues i left join projects p on p.id = i.project_id left join timelogs t on t.issue_id … -
In Python Django , in my views I cannot access my templates outside of the app which my views are in .How do I do that?
I have simplified the code in order to make it easier to replicate the issue. I have tried putting my templates folder in the same app as the views and that works fine. But when I place the templates folder outside off it , it cant seem to reach it. Base urls code : from django.urls import path from .views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] project urls code : from django.contrib import admin from django.urls import path , include urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), ] This is the code for my settings (relevant parts): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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 = 'personal_site.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', ], }, }, ] -
Passing a related field ID to an API endpoint in Django REST
I will try my best to make this easy to understand: [ { "id": 1, "data_sheet": "http://127.0.0.1:8000/static/media/store/data_sheets/EN_DS_MVS6300-LV_Datasheet.pdf", "module": 3 }, { "id": 2, "data_sheet": "http://127.0.0.1:8000/static/media/store/data_sheets/EN_DS_MVS6300-LV_Datasheet_Pck5SQy.pdf", "module": 5 }, { "id": 3, "data_sheet": "http://127.0.0.1:8000/static/media/store/data_sheets/Trina_670Wp_from_Gamechange_abXvA3H.pdf", "module": 5 } ] Basically, if I can go to an endpoint using the id like this: http://127.0.0.1:8000/store/cable_datasheets/1/. Result would be this: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "id": 1, "data_sheet": "http://127.0.0.1:27038/static/media/store/data_sheets/EN_DS_MVS6300-LV_Datasheet.pdf", "module": 3 } But am unable to achieve the same using the module id. say for instance: http://127.0.0.1:8000/store/cable_datasheets/5/ results in this: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } the module happens to be a related field I have no idea how I can use it and pass it as part of the queryset. My models.py: class Cable(models.Model): id = models.BigAutoField(primary_key=True) def __str__(self): return f"Cable ({self.tag}, {self.manufacturer}, {self.model})" def supports_arch(self, arch): return self.architecture[arch] == '1' class CableDataSheet(models.Model): module = models.ForeignKey(Cable, on_delete=models.CASCADE, related_name='data_sheets') data_sheet = models.FileField( upload_to='store/data_sheets', validators=[ validate_file_size, FileExtensionValidator(allowed_extensions=['pdf', 'jpg', 'png']) ] ) my views.py: class CableViewSet(ModelViewSet): http_method_names = ['get', 'head', 'options'] serializer_class = CableSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] permission_classes = [IsApplicationOrAdmin] def get_queryset(self): queryset = Cable.objects.all() arch = … -
Django how can i find_all book by сategory = None
How can i take all books when i pass None, cuz in Ruby if i write something like that Book.where(category = None) => Give all Books I try this Book.objects.filter(category = None) => empty QuerySet In general, there is some method in django that covers this logic -
have an event handler read a value in a html list and display some html on this condition
Apologies my experience with html and javascript is limited so I am trying to figure out the best way to do this. Essentially I am dealing with some html that creates a form for users to send messages. The form allows the selection of the subject and text to be input. <td>Subject</td> <td> <select id="subject"> <option selected="selected" value="none">Please select a subject</option> {% for subject in MESSAGE_SUBJECTS %} <option value="{{subject}}">{{subject}}</option> {% endfor %} </select> <!-- <input type="text" id="subject" size="80" value='No Subject' onfocus="if(this.value==this.defaultValue)this.value='';" name="subject" /> --> </td> </tr> <tr> <td>Message</td> <td><textarea id="newmessage" cols="80" rows="6" onfocus="if(this.value==this.defaultValue)this.value='';" name="newmessage">Please type your message here</textarea></td> </tr> Without going into too much detail the subjects are just a series of strings. For the purposes of this we can just call them 'sub1' and 'sub2'. I want to make it so the textarea only appears when 'sub1' is selected from the dropdown list. I believe a javascript event handler is the way to go here and there is an associated javascript file with some functions but I can't figure out what the syntax would look like. I assume it is something like: function conditionalMessage() { if( subject == "sub2" ) { //some code that defines displaying text to explain … -
python -m django startproject vs django-admin startproject
hi everyone what is difference between python -m django startproject and django-admin startproject if it have any different so which one is better for use ?