Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a static dead code analyser for Django?
Is there a static dead code analyzer for Django, which excludes such unused variable like 'template_name' or 'form_class' or class 'Meta'. I am looking for a dead code analyzer that reports me only the relevant codes as far as possible. I tried the vulture package, but I want to avoid this: asistar/tests/factories.py:32: unused class 'Meta' (60% confidence) asistar/tests/factories.py:33: unused variable 'model' (60% confidence) asistar/tests/factories.py:47: unused class 'Meta' (60% confidence) asistar/tests/factories.py:48: unused variable 'model' (60% confidence) asistar/tests/factories.py:60: unused class 'Meta' (60% confidence) asistar/tests/factories.py:61: unused variable 'model' (60% confidence) -
How to check if the fields already exist.?
I need to check if the fields already exist. If that field doesn't exist, then I need to create a new one. Like the availability check on a booking system My Model # Choices time = [ ('1', 'Morning'), ('2', 'Afternoon'), ('3', 'Evening'), ('4', 'Night'), ] # Model class Calender(models.Model): user = models.ForeignKey(AUTH_USER_MODEL,on_delete=models.SET_NULL) date = models.DateField() time = models.CharField(max_length=10, choices=time) location = models.CharField(max_length=32) My View class CheckAvailabilityAPIView(APIView): def post(self, request): date = request.data.get('date') time = request.data.get('time') location = request.data.get('location') calender = Calender.objects.all() for obj in calender: if obj.booked_date == date and obj.section_timing == time and obj.location == location: return Response({'response': 'Already exist'}) else: user_id = request.user.id user = User.objects.get(id=user_id) serializer = VendorsCalenderSerializer(data=request.data) if serializer.is_valid(): serializer.save( user=user, date=date, time=time, location=location ) return Response({'response': 'Success', 'result': serializer.data}) else: return Response({'response': 'Failed', 'error': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) Can someone help me with this.? -
Django Rest Framework, create method is no working properly
There is a trial end field in subscription model, i want to initialize the field with trial_end_date , problem I'm facing now trial_end in subscription model showing null value, How can I extract out the field of trial end field and initialize it? I have attached the def create method looked at that. I will appreciate your help . def create method [Model][2] my aim is when in membership model plan contain trial period days , it will add in trial end field of subscription model -
I want to filter by Today Day and Count ids on that day
I am New To Django Plz help me out But in this Case I want Result as {weekday: todayweek_number, count: total_ids_count_number } Currently I am Using this Django Query as follows Booking.objects.filter(created_at__day=today.day).annotate(count=Count('id')).values('weekday', 'count') The Point here is 'Weekday' I want Today Week Day Number as a key, which I am Using in filter -
How to add 2 models in a registration form in Django?
I want to create a Registration form which includes two models. One model is my custom model (Profile) and the other is the default User model in Django. I created two separate forms within the same template but the data is not successfully stored. This is what I had done so far: models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) company = models.CharField(max_length=100, blank=True, null=True) address = models.TextField() views.py: def register(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('login') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'register_page.html', {'user_form': user_form, 'profile_form': profile_form}) forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['company', 'address'] However, when I tried to register a new user, the data gets saved in the User model (username, email, password) but not in the Profile model (company, address). I am getting this error instead: RelatedObjectDoesNotExist at / Profile has no user. What should I … -
Override Save Model in Django
What I wanted to do is to override the save button in the model to run my script. My script contains Tensorflow code. So, what I am trying to do is to get the uploaded image to run in my script then the result image will save in the media. My script contains total count value so I would like to save it in the model. Please help. Model.py from django.db import models # Import packages import os import cv2 import numpy as np import tensorflow as tf import sys # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util from api import object_counting_api from django.conf import settings from django.shortcuts import render class District_1_2018(models.Model): barangay = models.CharField(max_length=255) totalarea = models.CharField(max_length=10) image = models.ImageField(upload_to='result/2018/district1') totalcount = models.CharField(max_length=10) def __str__(self): return self.barangay Forms.py class District_1_2018Form(forms.ModelForm): class Meta: model = District_1_2018 fields = ['barangay', 'totalarea', 'image', 'totalcount'] My script # Name of the directory containing the object detection module we're using MODEL_NAME = 'inference_graph' IMAGE_NAME = 'Burol.png' # Grab path to current working directory CWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which … -
how to create a zoom meeting using a token in django?
i am new to this can someone help? i took help on google and you tube but i cannot able to find any solution. I have been told this to do- Try writing a si.ole python script where - 1. You can obtain oauth token from API. 2. Using the token programmatically create a meeting. -
it is possible to add a keyword to python?
There are many keywords in other languages that miss includes in Python. For example: 'delegate' or 'sealed', 'interface' or 'event' can make the tasks much easier and readable, because you won't have to remember the functionality of the method, but instead use it as a keyword ... If there is no possible way to add a keyword and warn the interpreter from it, then ** please support this message ** so Python Foundation might see it, and consider this feature. 1. class Animals(abc.ABC): @abstractmethod def walk(...): pass 2. interface Animals: def walk(...): pass -
ImportError: No parent package available
This is my line: from . import views This is the error: ImportError: attempted relative import with no known parent package -
Django InconsistentMigrationHistory
I'm trying to setup a Django project and am faced with the following error: WARNINGS: ?: (rest_framework.W001) You have specified a default PAGE_SIZE pagination rest_framework setting,without specifying also a DEFAULT_PAGINATION_CLASS. HINT: The default for DEFAULT_PAGINATION_CLASS is None. In previous versions this was PageNumberPagination. If you wish to define PAGE_SIZE globally whilst defining pagination_class on a per-view basis you may silence this check. Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 82, in handle executor.loader.check_consistent_history(connection) File "/Users/george/.virtualenvs/mixapi/lib/python3.7/site-packages/django/db/migrations/loader.py", line 291, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration events.0001_initial is applied before its dependency commons.0001_initial on database 'default'. make: *** [migrate] Error 1 I am running this from within a virtual environment, and have a docker-compose container for a postgres db running. Not sure how to start debugging this or why its happening. Any help would be appreciated -
Why is python manage.py runserver not working?
Using this code use to work C:\Users\HP>project2_env\scripts\activate (project2_env) C:\Users\HP>cd C:\Users\HP\django_project3 (project2_env) C:\Users\HP\django_project3>python manage.py runserver Today when I tried to run python manage.py runserver the computer just hung. I could not run any SQL queries on my websites database (using CMD). Although I could load the website within Google Chrome. The computer simply got this far. System check identified no issues (0 silenced). December 02, 2019 - 12:36:39 Django version 2.2.6, using settings 'django_project3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [02/Dec/2019 12:37:19] "GET / HTTP/1.1" 200 3667 When I ran the python command I got this error message (project2_env) C:\Users\HP\django_project3>python Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32 Warning: This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.io/activation In Anaconda Prompt I ran this code but the problem still persisted. (base) C:\Users\HP>C:\Users\HP\Anaconda3\Scripts\activate base Can someone give me tips on solving the problem or does anyone have any idea what settings I need to check? -
Why do Django-admin commands recommend using self.stdout() vs print()?
The documentation on writing custon django-admin commands includes the following: When you are using management commands and wish to provide console output, you should write to self.stdout and self.stderr, instead of printing to stdout and stderr directly. By using these proxies, it becomes much easier to test your custom command. Note also that you don’t need to end messages with a newline character, it will be added automatically, unless you specify the ending parameter: self.stdout.write("Unterminated line", ending='') I'm not quite satisfied with this explanation as it doesn't really explain why it's "much easier to test your custom command." Does anyone have a good example or can expand further on what they're getting at? I wrote a custom command using print() statements and had no issues testing, but it feels like I may be missing out on some features. -
Postgres Materialized Path - What are the benefits of using ltree?
Materialized Path is a method for representing hierarchy in SQL. Each node contains the path itself and all its ancestors (grandparent/parent/self). The django-treebeard implementation of MP (docs): Each step of the path is a fixed length for consistent performance. Each node contains depth and num_child fields (fast reads at minimal cost to writes). The path field is indexed (with a standard b-tree index): The materialized path approach makes heavy use of LIKE in your database, with clauses like WHERE path LIKE '002003%'. If you think that LIKE is too slow, you’re right, but in this case the path field is indexed in the database, and all LIKE clauses that don’t start with a % character will use the index. This is what makes the materialized path approach so fast. Implementation of get_ancestors (link): Match nodes with a path that contains a subset of the current path (steplen is the fixed length of a step). paths = [ self.path[0:pos] for pos in range(0, len(self.path), self.steplen)[1:] ] return get_result_class(self.__class__).objects.filter( path__in=paths).order_by('depth') Implementation of get_descendants (link): Match nodes with a depth greater than self and a path which starts with current path. return cls.objects.filter( path__startswith=parent.path, depth__gte=parent.depth ).order_by( 'path' ) Potential downsides to this approach: … -
How to store the user input in dynamic web pages to local storage in django using javascript?
I am learning django through the videos. I am trying a web application like this given link https://www.modsy.com/project/room, so I dynamically got the html pages data from the database And my html code is ><div class="row"> {% for i in room %} <div class="col-4"> <div class="card6 mt-3" style="width: 12rem;"> <img src="{{i.image.url}}" alt="..." width="185" height="100"> <div class="card-body"> <p class="card-text"><b>{{i.content}}</b></p> </div> </div> </div> {% endfor %} </div> So on click of any card by the user and click the next button the imagepath,content and id should store in the local storage in console. Can you please help me how can i achieve this with an example.Thanks in advance -
How to get a http long connection by django and requests?
Some articles said if the http server and http client both use Connection: keep-alive in there header, then the tcp connection will be a long connection. So I did my test below. Client code: import requests import time url = 'http://server url' def session_req(url): s = requests.Session() r = s.get(url, headers={'Connection':'keep-alive'}) print(r.headers) print(r.status_code) while True: time.sleep(10) if __name__ == '__main__': session_req(url=url) From the client print we can see the server add Connection: keep-alive too But the tcp connection still not a long connection. # ss -tan FIN-WAIT-2 0 0 server ip:8004 client ip:40238 As you can see the tcp is not established So anything wrong about my code? How to make a long http connection? -
Django adding multiple m2m related model records using .set works fine, but how to also add additional model fields other than ids?
I have photos model and tags model with m2m relationship through phototags model. class Photo(models.Model): tags = models.ManyToManyField(Tag, through = 'PhotoTag', related_name="tags") In a view I create a list of tag ids that I use in photo.tags.set(form_tags_ids) to create the new phototag relationships. This works fine and successfully populates both photo_id and tag_id fields in phototags model. However, I also have other additional fields in phototags model, other than the related models' ids, that I want to populate at same time eg created date, user_id to record who made relationship and when it was created. What would be best way to populate these other columns? The only thing I can think of is to not use .set and loop through the list of tag ids and manually create the phototag records but then I lose benefit of m2m in avoiding duplicate assignment of tag to photo, etc. -
How to pass data from one view another view using sessions in django?
HTML <div class="content-section"> <form method="GET" action="{% url 'doctor:search' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> I want to save {{request.GET.q}} from this html into session variable and use it in all the views ORIGINAL VIEWS.PY class SearchResultsView(ListView): model = Search template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): query = self.request.GET.get('q') form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) [query = self.request.GET.get('q')] in 'SearchResultsView' and in 'PostCreateView' needs same value. I want to use input value from html and use it in both these classes using session variable VIEWS.PY Trying to implement session variable class SearchResultsView(ListView): model = Search template_name = 'all_users/doctor/search.html' def get_queryset(self): # new **request.session['query'] = self.request.GET.get('q')** **query = request.session['query']** object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): **query = request.session['query']** form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) When i use this code i get "name 'request' is not defined" error. -
Django - Multiple user types (ability to switch between them)
I am doing some pre-planning on a project I am working on and my approach to it. A part of the app is the ability to have multiple user types. For example, a Company and a Contractor account type. Though it's important to note that a company can also be a contractor. So the approach I was going to attempt to implement is similar to Upwork where there is one account, but they can switch between being a client and a freelancer if they wish. It would be ideal if the user didn't need to log out while switching between the two. I'm newer to the django framework and was hoping someone could shed light on the best possible approach to accomplish this while also taking into account scale-ability. -
Django Changing Content Based on Menu Selection
I have a todo website that allows users to put reminders in a certain list. I have a dropdown menu with all lists the user has created. I want content in a div to be changed based on what the user selects, and found a solution with javascript here. I have a custom template tags that returns unique ids and reminders: <div class="col-md-6 inline mb-5"> <div style="display: flex;"> <h3 class="ml-2">Reminders:</h3> <div class="ml-2" style="margin-bottom: -5px;"> <select class="dropdown" placeholder="Sort By:" id="remind_sort"> {% get_dropdown_ids user.username as dropdown_ids %} {% for option_id, list_item in dropdown_ids.items %} <option value="{{ option_id }}">{{ list_item.title }}</option> {% endfor %} </select> </div> </div> {% get_list_items_ids_regular user as list_ids %} {% for div_id, reminder_list in list_ids.items %} <div class="group events-content-section ml-2" id="{{ div_id }}"> {% for reminder in reminder_list %} <div class="mb-2" style="display: flex; align-items: center;"> <ul class="reminderUl"> <li> <span class="reminderSpan"> <button type="button" class="update-reminder btn btn-info" data-id="{% url 'update-reminder' reminder.pk %}"> <i class="fas fa-pencil-alt"></i> </button> </span> <span class="reminderSpan"> <button type="button" class="delete-reminder btn btn-danger" data-id="{% url 'delete-reminder' reminder.pk %}"> <i class="fas fa-trash-alt"></i> </button> </span> <button class="view-reminder btn btn-light" data-id="{% url 'view-reminder' reminder.pk %}"> <h4>{{ reminder.title }}</h4> </button> </li> </ul> </div> {% endfor %} </div> {% endfor %} </div> <script type="text/javascript"> $(document).ready(function … -
Django, cloudflare for media files
I've setup cloudflare with one of my s3 bucket. using AWS_S3_CUSTOM_DOMAIN It works fine for reading the contents, but it has problem with uploading images to the bucket. How do I upload images to the s3 bucket directly, and use cloudflare cdn for read? -
Django - forms.ChoiceField without using model
I want to create a form to select an option without using a model for it. For some reason form is not showing up on the template. I tried below code, could someone help me with this? form.py class selectPostType(forms.Form): STATUS_CHOICES = (('1', 'Text Post'),('2', 'Image Post'),('3', 'Video Post'),) post_type = forms.ChoiceField(choices=STATUS_CHOICES) views.py def selectPostType(request): form = selectPostType return render(request,'selectPostType.html',{'form':form}) html <form action='.' method="post"> {% csrf_token %} {{ form }} <button class='btn btn-default' type='submit'>Select</button> </form> -
How do I get audio duration for the FileField in Django?
Consider having this model: class MusicTrack(models.Model): """ Represents a music track """ title = models.CharField("Track title", max_length=300) audio_file = models.FileField("Audio file", upload_to='audio/%Y-%m-%d/') duration_seconds = models.PositiveIntegerField("Track duration ins seconds", blank=True, null=True) def __str__(self): return f"Music track \"{self.title}\"" How do I get the audio duration in seconds and save it in the database? -
Django Looping Through Objects to Place Object Markers on Google Maps
I cannot figure out how to get checkmark pins to show up on google maps I have tried to loop this several different ways. When I take the function out the map shows back up. I am wondering if it is possible to do on Django in this manner. Thank you for any help. {% extends 'maps/base.html' %} {% block body %} <head> <style> #map { height: 50%; width:50% } html, body { height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { zoom: 2, center: new google.maps.LatLng(2.8,-187.3), mapTypeId: 'terrain' }); // Loop through the results array and place a marker for each // set of coordinates. function loadMarkers(){ {% for object in object_list %} var point = new google.maps.LatLng({{object.latitude}},{{object.longitude}}); var marker = new google.maps.Marker({ position: point, map: map }); {% endfor %} </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap"> </script> </body>''' -
Resolving sub-domains for Django multi-tenancy sites
A site I just got up is resolving the normal pages at the server IP address (eg. XXX.XXX.XXX.XXX) but when I create a new tenant the sub-domains are not resolving (eg. tenant.XXX.XXX.XXX.XXX). I tried adding the sub-domain URL to the host file /etc/hosts but this did not work. I am looking into DNS servers but this looks like every sub-domain would redirect to the main URL which is not what I want since every tenant has their own schema accessed through the sub-domain. Is this true? Or do DNS servers just handle pointing everybody to the correct server? How do I handle sub-domains for multi-tenancy apps on a server? -
How to periodically repeat a function until success in background in Django?
I'm working on a Django project. I want to do a http request to an external server. But sometimes the external server returns 5xx. I want to retry request on the background until it returns 200. How can I do this? This is a pseudo code of what I want to do: response = requests.post(url, json=param) if response.status_code == 200: # do something elif response.status_code >= 500: # schedule task to retry every 30 seconds until success