Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use of queryset inside Primarykeyfield of ModelSerializer in Django Rest
I am making a simple create api for a model which has almost all fields as foriegn key to other models. I am writing create logic inside the serializer. It is working fine. However if I define all the fields as pkrelated field in serializer, it asks for queryset attribute. Why it is asking that. And if I put queryset and import all the objects(queryset= Example.objects.all()) wouldnt it make the code and api slow since it is importing all the objects from Example model. Also, what its use to be honest? My model: class Example(TimeStampAbstractModel): abc = models.ForeignKey(User,.... xyz_info = models.ForeignKey(XYZ,... mnp = models.ForeignKey(MNP,...... status = models.CharField(....blank=True) My serializer: class AttendanceSerializer(serializers.ModelSerializer): xyz_info = serializers.PrimaryKeyRelatedField(required=True, queryset=XYZ.objects.all()) mnp= serializers.PrimaryKeyRelatedField(required=True, queryset=MNP.objects.all()) #mnp = serializers.IntegerField(required=True) status = serializers.CharField(required=True) class Meta: model = Attendance fields = ['xyz_info','mnp','status'] def create(self, validated_data): ............. In above serializer class, if I hadnt defined all those fileds in the serializer, it works fine. But if I define them as pkfield as above ( I am passing only ids in the body from frontend), it asks for queryset. Why it is asking queryset and what its use there? Also can I defined them as integarfield? When to define as pkfield and … -
How to mix multiple querysets into one and re order them by time created?
I am learning Django and still a beginner. For practising, i am trying to make a demo social media website. In my project, users can create groups, then they can post and comment there. In the home page, i am trying to add a section like 'recent activities' where a user can see recent activities in that website like "John created a group 'Javascript', Tim posted a comment in 'Python', Sarah posted in 'CSS'" Now i have made some queries like: groups = Group.objects.all().order_by('-created')[0:5] posts = Post.objects.all().order_by('-created')[0:5] comments = Comment.objects.all().order_by('-created')[0:5] I want to mix them all in a single queryset. Then order them all by the time they were created. I know it's a silly question and i have been stuck here since morning. Can you help me and show me the process please? -
How to hoste multiple Django websites on single sever using NGINX and uWSGI
i have a linux server running under Ubuntu server 20.04 LTS, i'm using NGINX as a web server and uWSGI as an application server, i have a Django website is already installed and running perfectly, and the exact way i did that is by following the instructions from this video https://www.youtube.com/watch?v=ZpR1W-NWnp4&t=2s, but the thing is that i have several websites that needs to be installed, so i tried to redo all of it for a second website on the same server, but that did not work at all. My question is: once i install a Django project exactly the way shown in the video using Nginx and uWSGI, how to install another Django project in a practical manner, in other words how to install multiple Django projects using Nginx and uWSGI. -
How to create database connection using REST API in Django?
Currently, I'm trying to make a Database Connection with Django REST API. The goal: To create an API for DB connection with any databases by inputting the properties (e.g., host, dbname, username, password, etc). I already tried using GET method to connect and retrieve the output. However, all the DB properties are written in the script. This is my result using GET: Now, I want to modify it into POST method to connect and retrieve the output. (It seems that user gives the input). My expected result is: The problem is: I don't know how to modify it into POST method (request JSON) and retrieve the desired output (response JSON) as I mentioned in the above picture. The MyApp\src\DBConn.py file: import psycopg2 class DbConnection: def __init__(self, host, port, dbname, user, password): self.host = host self.port = port self.dbname = dbname self.user = user self.password = password def create_conn(self): # connection string conn = 'host = {host} port = {port} dbname = {dbname} user = {user} password = {password}'.format( host = self.host, port = self.port, dbname = self.dbname, user = self.user, password = self.password ) # establish the connection self.db = psycopg2.connect(conn) self.cursor = self.db.cursor() def check_conn(self): sql = "SELECT VERSION()" … -
Why is the server not working when using django_prometheus?
There is a django application. It is necessary to collect metrics. I'm using django_prometheus. I added the django_prometheus app to my project. INSTALLED_APPS = [ ... 'django_prometheus', ... ] MIDDLEWARE = [ 'django_prometheus.middleware.PrometheusBeforeMiddleware', ... 'django_prometheus.middleware.PrometheusAfterMiddleware', ] I don't want to add the URL "/ metrics". I need to start the server on a separate port using prometheus_client.start_http_server. I added this code to wsgi.py: from django.conf import settings from django_prometheus.exports import SetupPrometheusEndpointOnPort SetupPrometheusEndpointOnPort(9090) This starts the server and it works. But the correct metrics are not displayed. If you add the url "/metrics": urlpatterns += [ path('', include('django_prometheus.urls')), ] Then localhost:8000/metrics will display the correct metrics. What could be the problem? P.S.: I started the server via start_http_server in parallel with the FastAPI application and everything worked correctly. -
how to get param in permission.py django
I want to work with 'start' param in permissions.py How I can take it ? My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeField(default="2021-10-10") end = models.DateTimeField(default="2021-10-11") description = models.CharField(max_length=250) permissions.py from rest_framework import permissions class IsTimeNotDefined(permissions.BasePermission) : def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return False return False -
p y manage.py run server not working in vscode editor
recently started learning Django and not to run this command "p y manage.py run server" I am using windows 10 and vs code(power shell) as terminal it's showing me again and again that i have no such file in the directory -
Django-filters, q objects & searching "contains" in manytomany & textfields at the same time
does anyone know anything about q objects and searching many to many fields? class tags(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Item(models.Model): item_id = models.CharField(default = random_string,max_length=5) tags = models.ManyToManyField(tags, verbose_name="tags") description = models.TextField() topic = models.TextField() I am using django-filters to create a filter / search area, below if filters.py: class ItemFilter(django_filters.FilterSet): multi_name_fields = django_filters.CharFilter(method='filter_by_all_name_fields') class Meta: model = Item fields = ['description','topic','tags'] def filter_by_all_name_fields(self, queryset, name, value): return queryset.filter( Q(description__contains=value) | Q(topic__contains=value) | Q(tags__contains=value) ) When I render the form field "multi_name_fields" I get an error " Related Field got invalid lookup: contains " The search form functions perfectly without the manytomany field added in but when I add in the "tags" manytomany field it gives me the above error. Does anybody have any ideas where I am going wrong or what I am missing? -
Docker configuration for Django+Vuejs+Gunicorn+Nginx lead to 502 Bad Gateway
Context I'm developing an application that will have to be deployed once per customer (it's not a multi-tenant app that all my customers would use). Ultimately, it will be deployed on AWS with services like RDS (DB), S3 (storage) and ECS (container service). You can see how I imagined it with the image below if it can help to answer me: My application is working well locally without Docker. But I want to use a dockerized version of it locally before trying to deploy it on AWS, because I want to be able to run it locally with Docker before trying to do it on AWS (...). Since all my customers would have their own instance (and customer1 could have a different version than customer2 at some time), I thought about a single container with everything needed, as you can see on the image : the Django application, the Vue built files, gunicorn and nginx. Question 1 : Is it a good idea to do it like this ? Or should I use a docker-compose thing with multiple services (backend (django) & nginx). Would it lead to multiple containers ? To do so, I did the following configuration : Dockerfile: … -
Django switch database user
Assume I got different database users, and each of them have different permissions (already settled in db side). How can I switch between different db users? 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****', 'USER': '****', # i got several users here and want to switch them 'PASSWORD': '****', 'HOST': '*****', 'PORT': '***', -
Video not playing on ios (safari)
Video Link This video is playable on windows as well as android. But not in ios. I am using Django (python framework) for backend. What should i do ? -
Can we use class create view to build multiple forms in django?
class formsView(CreateView): model= dummy fields= "__all__" template_name= "index/page1.html" success_url="page1" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dummy'] = dummy.objects.all() context['tummy']= tummy.objects.all() return context Using this code, I am able to render a form based on the model 'dummy', and am able to get the context from another model 'tummy' to use in my html code. However, I was wondering if there was a way to include more than one form using the create view. -
How to run tests for specific django apps when you have a conftest in a root folder
I work on a Django project and we have dozens of different apps. We a have a global conftest in the root folder and conftests in each app's folders. Sometimes we need to run tests for separate apps and not wait for all tests to complete. How can I run tests for a specific app if they don't work without running the global conftest? So command pytest -v apps/app_one won't work because it loads only a conftest in the app_one folder and does not load a global conftest. -
Problem with getting data from input for django
I have a problem with getting data from the tag on the page with the Django form. templates: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input id="result" type="hidden"> <script type="text/javascript"> const upload = document.querySelector('#inputGroupFile01'); const result = document.querySelector('#result'); upload.addEventListener("change", (e) => { previewFunc(e.target.files[0]); }); function previewFunc(file) { if (!file.type.match(/image.*/)) return false; const reader = new FileReader(); reader.addEventListener("load", (e) => { const label = document.createElement('label'); label.for = 'photo'; const input = document.createElement('input'); result.name = 'photo'; result.value = 'e.target.result'; result.src = e.target.result; result.type = 'image'; result.id = 'result'; {#result.innerHTML = '';#} {#result.append(input);#} }); reader.readAsDataURL(file); } </script> <button type="submit">{% trans 'Apply' %}</button> </form> Views: class LoadPhotoView(BaseMixin, generic.CreateView): model = Photo template_name = 'load_photos/load_photo_page.html' form_class = PhotoUploader def post(self, request, *args, **kwargs): print(request.POST.get('photo')) print(request.FILES.getlist('photo')) print(request.FILES.get('photo')) return render(request, self.template_name, {'form': self.form_class}) After executing javascript code page has next structure at the screen: But I still can't get photo in method post in my view(I get None or empty list) -
Django: Number the integer fields of the filtered queryset in order (efficiently)
It is possible to assign sequential numbers to the integer fields in the filtered queryset I am looking for by doing the following, but the query is issued every time I save(). How is it possible to save it? queryset = Model.objects.filter(user=user) for i, item in enumerate(queryset, start=1): item.order = i item.save() -
Run separate threads along Django web server
I'm fairly new to the Django framework and also far from being an expert Python programmer, so sorry in advance if my request may sound trivial. I set up my web server in Diango, but what I would like to do now, is to have two python threads, one sending messages on a socket to another process (e.g. after some requests are performed on the web server) and the other receiving them from the same process (e.g. it receives a request that have some effect on the web server). So, down to my question, where should I place this code? I need it to be initialized when the web server starts up, and I want it to be accessible anywhere (e.g. when the code of a certain view is processed I want to signal the tx thread to send a message on the socket). I don't know if there is something django-specific to help me with this task or not. Thanks in advance for any help! -
how to filter data from two django class
I have two Django class,I want to filter VCDUnavailAudit by site_key in Django Get method, how could I do enter code here class VCDUnavailAudit(models.Model): user_key = models.IntegerField() user_name = models.CharField(max_length=40) class User(models.Model): user_key = models.AutoField(primary_key=True) site_key = models.IntegerField() @api_view(['GET']) def get_unavail_audit_records_by_site(request, site_key: int): availability_audit_records = VCDUnavailAudit.objects.filter serializer = VCDUnavailAuditSerializer(availability_audit_records, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
Postgres backup database
I'm working on a django project and i'm using postgres for database. I want to backup the database and i tried to use dbbackup library. While in development env works fine in production i got an error of no password. The command i'm running is the same in both environments and also the configuration, the only difference is the database credentials Backing Up Database: database CommandConnectorError: Error running: pg_dump --host=localhost --username=databaseuser --no-password --clean database pg_dump: error: connection to database "database" failed: FATAL: password authentication failed for user "databaseuser" FATAL: password authentication failed for user "databaseuser" Any suggestions? -
How to Force Current User to a Field in Django Rest Framework
Consider I have models, a serializer and a viewset as below: # models.py class Foo(models.Model): owner = models.ForeignKey(User, models.CASCADE, related_name="bars") # serializers.py class FooSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), queryset=User.objects.all(), ) class Meta: fields = ["pk", "owner"] # viewsets.py # registered to /api/foos/ class FooViewSet(viewsets.ModelViewSet): serializer_class = FooSerializer permission_classes = [permissions.IsAuthenticated] queryset = Foo.objects.all() So, when I send a POST request to /api/foos/ with an empty body, it creates a Foo instance with its owner field set to the current logged-in user, which is fine. However, I also want to totally ignore what the currently authenticated user sends as a value to owner. For example, if I do a POST request to /api/foos/ with body user=5 (another user, basically), CurrentUserDefault sets the Foo.owner to that user, which is not the behavior I want to have. I always want to have the current authenticated user as the value of the field owner of a new Foo instance, or, in other words, I want FooSerializer.owner field to be set as currently authenticated user as a value and ignore what is sent on POST request as a value of owner. How do I do that? Thanks in advance. Environment django ^2.2 djangorestframework ^3.12.4 -
Django-python3-ldap problem to connect admin/login - SyntaxError at /admin/login/
I've just tried to connect to my Active Directory LDAP server. I'm sure, that everything in configuration (like IP and DN) is OK. But If I want to go to admin page, it shows me error (it's below). I don't know how to do it. AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LDAP_AUTH_URL = "ldap://srv.ext.cz" LDAP_AUTH_USE_TLS = None LDAP_AUTH_SEARCH_BASE = "OU=Users,OU=Temp,OU=SRC,DC=example,DC=cz" LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "xxx.cz" LDAP_AUTH_CONNECTION_USERNAME = None LDAP_AUTH_CONNECTION_PASSWORD = None LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } Error: > File > "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\core\handlers\exception.py", > line 47, in inner > response = get_response(request) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\core\handlers\base.py", > line 181, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\views\decorators\cache.py", > line 44, in _wrapped_view_func > response = view_func(request, *args, **kwargs) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 398, in login > **self.each_context(request), File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 316, in each_context > 'available_apps': self.get_app_list(request), File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 505, in get_app_list > app_dict = self._build_app_dict(request) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 450, … -
Access Django context data in get_initial
I have an expensive call in my view's get_context_data to calculate a field for the template. I would like to use this result in the view's get_initial_data to set the initial value of my_field but I cannot see how to access the context_data from within get_initial_data or how to pass it as a parameter. def get_context_data( self, *args, **kwargs ): context = super().get_context_data( **kwargs ) context['expensive_result'] = expensive_function() return context def get_initial( self ): initial = super().get_initial( **kwargs ) # Initialise my_field with expensive result calculated in get_context_data initial['my_field'] = context['expensive_result'] # How to do this? return initial -
Failed - network error when downloading a file
I have configured the apache webserver for my Django application for https redirection and its working fine. When i was testing my application I found out that it sometimes shows Failed -Network error when trying to download a xlsx file .Downloading a tarfile does not give any error.. Tried in different browser but got the same result.. Not sure what is wrong Please Help. Thanks -
Posting Dynamic table Form values using Jquery and fetching that post in django view
I know this is not the conventional method but I wanted to try this out and make it successful. Here is a html file that I am rendering using a django view. {% extends 'base.html' %} {% block table_name %}Invoice{% endblock %} {% block table_view %} <form method="POST" action="/submit" id="myForm"> {% csrf_token %} <table border="1" class="center table-responsive table table-striped" width="100%" cellspacing="0" style="padding-left:418px" id="table"> <thead> <tr> <th colspan="6">INVOICE</th> </tr> </thead> <tr> <th COLSPAN="3">INVOICED TO</th> <td colspan="4" class="center"> <input list="show" type="text" class="center" style="width:100%" name="client_name"> <datalist id="show"> {% for client in clients %} <option value="{{ client.first_name }}"></option> {% endfor %} </datalist> <br><br><textarea type="text" name="client_address" placeholder="Address" style="width:100%" rows="3"></textarea></td> </tr> <tr> <th COLSPAN="3">INVOICED FROM</th> <td colspan="4" class="center"><input type="text" name="company_name" style="width:100%" placeholder="Company Name"><br> <br><textarea type="text" name="company_address" placeholder="Address" rows="3" style="width:100%"></textarea></td> </tr> <tr> <th COLSPAN="3">VESSEL NAME</th> <td colspan="4" class="center"><input name="vessel_name" style="width:70%" type="text" placeholder="Vessel Name"></td> </tr> <tr> <th COLSPAN="3">PO NUMBER</th> <td colspan="4" class="center"><input type="text" name="po" style="width:70%" placeholder="PO number"></td> </tr> <tr> <th COLSPAN="3">INVOICE NUMBER</th> <td><input name="invoice_number" type="text" placeholder="#/2021" disabled></td> <th>DATE</th> <td colspan="" class="center"><input type="date" name="date"></td> </tr> <tr CLASS="CENTER"> <th>S. NO.</th> <th COLSPAN="2">PARTICULARS</th> <th COLSPAN="1">GST</th> <th colspan="2">TOTAL AMOUNT</th> </tr> <tr CLASS="CENTER"> <td class="center">1</td> <td COLSPAN="2" class='center'><input type="text" name="product1" placeholder="Name of product"></td> <td><input type="number" name="gst1" placeholder="gst"></td> <td COLSPAN="2"><input name="cost1" type="number" placeholder="cost"></td> </tr> … -
Filter model by datetime in django
I need to filter model with (datetime.now() < end) My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeFieldField(default="2021-10-10") end = models.DateTimeFieldField(default="2021-10-11") My view class GetQuizView(generics.ListAPIView) : def get_queryset(self): now = datetime.now() return Quiz.objects.filter(start = now) serializer_class = QuizListSerializer But I can only filter with equal time, I can't use > or < -
compare objects in views.py of 2 different models objects in Django
I am trying to compare 2 objects (skills of a job posting such as web development, marketing, etc to the same skills of a logged-in user), if matched will display that job posting. The goal is to display multiple job postings that match the user. Currently, jobmatch.html does not display any jobs. Thank you for taking the time!! views.py from apps.job.models import Job from apps.userprofile.models import User_profile def match_jobs(request): match_jobs = {} for job in Job.objects.all(): if job.product_management == User_profile.product_management: match_jobs['product management'] = job elif job.web_development == User_profile.web_development: match_jobs['web development'] = job elif job.user_experience == User_profile.user_experience: match_jobs['user experience'] = job elif job.marketing == User_profile.marketing: match_jobs['marketing'] = job elif job.finance == User_profile.finance: match_jobs['finance'] = job return render(request, 'jobmatch.html', match_jobs) Job.models.py class Job(models.Model): title = models.CharField(max_length=255) location = models.CharField(max_length=255, blank=True, null=True) description = models.TextField() requirements = models.TextField(blank=True, null=True) product_management = models.BooleanField(default=False) web_development = models.BooleanField(default=False) user_experience = models.BooleanField(default=False) marketing = models.BooleanField(default=False) finance = models.BooleanField(default=False) User.models.py class User_profile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) is_employer = models.BooleanField(default=False) resume = models.ImageField(default='default.jpg', upload_to='resume') full_name = models.CharField(max_length=255, default='Enter full name') relevant_background = models.TextField() product_management = models.BooleanField(default=False) web_development = models.BooleanField(default=False) user_experience = models.BooleanField(default=False) marketing = models.BooleanField(default=False) finance = models.BooleanField(default=False) jobmatch.html {% for job in match_jobs %} <div class="colum is-4"> …