Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting 2 unconnected tables but are connected to the same table via many-to-many relations
I have the following setting in a django project A model describing "Person", this model includes 2 many-to-many relation fields a. The first unit field connects to a Unit model (m2m) b. The second tool field connects to a Tools model (m2m) Unit and Tools are not directly connected, but I want to list all the tools used in a given unit. I'm not sure how this can be done, since the two tables are not connected? class Person(models.Model): name = models.CharField(max_length=100) unit = models.ManyToManyField(Unit, blank=True) rtools = models.ManyToManyField(Rtool, blank=True) class Tool(models.Model): tool_name = models.CharField(max_length=100) tool_description = models.TextField( blank= True) class Unit(models.Model): unit_name = models.CharField(max_length=250) -
Django TypeError expecting str or binary, how to satisfy?
here is the traceback Building a simple Django blog application, had it working on virtual dev server at first but after integrating summernote editor into admin side, front end site wont launch and this TypeErorr is displayed. Has anyone encountered this before and is able to point me in the right direction? Django version 3.1.7. -
django objects.filter() issues
My django project contains an application called: app_1 It stores models.py file wich contains a django models called: client I cannot filter my models throw client.objects.filter(nom=something), django search into a wrong relation it just add my app name with my model's name and search into "app_1_client" (it should be in "client") ERREUR: the relation « app_1_client » doesn't exist I can access my data with client.objects.raw(""" query """) from django.db import models # Create your models here. class client(models.Model): nom = models.CharField(max_length = 100, null=False) prenom = models.CharField(max_length=100, null=False) tel = models.CharField(max_length=12, primary_key=True) views.py from .models import client def modify_client(request, client_phone): c = client.objects.filter(pk=client_phone) context = {'clients': c} -
different number of records in django pagination pages
I make a news blog. I want 5 news to be displayed on the first page. In the order below. And on the next ones, 6 were displayed (all squares with areas are the same). .news-container { margin: 0; display: grid; grid-template-columns: 50fr repeat(2, 25fr); grid-auto-rows: 40vh; grid-column-gap: 20px; grid-row-gap: 20px; } .news-element:nth-child(1) { background:red; grid-column: 1 / 2; grid-row: 1 / 3; } .news-element:nth-child(2) { background:red; grid-column: 2 / 3; grid-row: 1 / 2; } .news-element:nth-child(3) { background:red; grid-column: 3 / 4; grid-row: 1 / 2; } .news-element:nth-child(4) { background:red; grid-column: 2 / 3; grid-row: 2 / 3; } .news-element:nth-child(5) { background:red; grid-column: 3 / 4; grid-row: 2 / 3; } <div class="news-container"> <div class="news-element"> 1 </div> <div class="news-element"> 2 </div> <div class="news-element"> 3 </div> <div class="news-element"> 4 </div> <div class="news-element"> 5 </div> </div> How can you make sure that 5 news are displayed on the first page in pagination and 6 news on the rest? pagination is done on django like this class NewsView(ListView): model = News template_name="mysite/news.html" paginate_by = 5 context_object_name = "all_news" queryset = News.objects.all().order_by("-date_news") -
Deployed Dockerized Django app with GitLab CI/CD can't find static files
Deployed django application using Docker and Gitlab CI can't find static files on the server when I am trying to access admin page, swagger or browsable-api. I checked static files for their existence and they do in the location /srv/data/public/static/ . I tried to change nginx location but it didn't help. Here is mine production docker-compose.yaml version: '3.1' services: postgres: container_name: postgres image: postgres:12.0-alpine logging: driver: none volumes: - ./data/postgres:/var/lib/postgresql/data:rw ports: - 5432:5432 environment: POSTGRES_DB: baysai POSTGRES_USER: user POSTGRES_PASSWORD: pass redis: container_name: redis image: redis:6.0-alpine logging: driver: none volumes: - ./data/redis:/data api: image: registry.gitlab.com/example/example-api:master container_name: api hostname: api command: bash -c "python /app/manage.py collectstatic --noinput && python /app/manage.py migrate --noinput && gunicorn -b 0.0.0.0:8000 config.wsgi:application" stdin_open: true tty: true restart: always environment: DJANGO_SETTINGS_MODULE: config.settings volumes: - ./data/public:/public - ./example-api.env:/example-api.env ports: - "8000:8000" depends_on: - redis - postgres celery: image: registry.gitlab.com/example/example-api:master container_name: celery hostname: celery command: bash -c "cd /app && find . -type f -name 'celerybeat.pid' -exec rm -rf {} \; && find . -type f -name 'celerybeat-schedule' -exec rm -rf {} \; && celery -A config worker -l info" stdin_open: true tty: true restart: always environment: DJANGO_SETTINGS_MODULE: config.settings volumes: - ./data/public:/public - ./example-api.env:/example-api.env depends_on: - redis - postgres nginx: … -
Credential error when trying to preserve data
I am developing an api in Django Rest Framework, which at the moment only registers new users, but I have a problem and that is that now I am adding a bit of security, which is being controlled by means of tokens, but at the time of entering the token of an authenticated user for the creation of users generates an error of The authentication credentials were not provided, but I send the token as follows: This is plugin rest client visual studio code My authentication: ### Login user POST http://localhost:8000/auth-token/ Content-Type: application/json { "username": "hamel", "password": "contraseña" } This return a token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4 My register of user: ### Create User POST http://localhost:8000/api/v1/users Authorization: Token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4 Content-Type: application/json { "first_name": "Carlos", "last_name": "Carlos", "username": "carlos", "email": "correo@rgrgr.com", "password": "contraseña", "password2": "contraseña" } My setting.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } -
how can i set two for loop in django template for send and receive chats?
im trying to set receive and send message in django template with to for loop like this : <div class="border px-2 chat-box "> {% for box in message1 %} <div class=" my-4 border bg-light "> <span class=" p-2 my-5">{{ box.msg_content }}</span><br> <span class="date text-muted ">{{ box.whenpublished }}</span> </div> {% endfor %} {% for box2 in message2 %} <div class=" border bg-danger" style="" > <span class=" p-2 my-5" >{{ box2.msg_content }}</span><br> <span class="date text-muted">{{ box2.whenpublished }}</span> </div> {% endfor %} </div> but when i send and receive message Each of them comes separately like this: hello(user1) how are you(user1) hello(user2) im fine thnaks(user2) but i want when i send one message its show after receive message hello(user1) hello(user2) how are you(user1) im fine thnaks(user2) -
could not create unique index, key is duplicated django postgres
I got following user table with same uuid . I want this uuid to be unique . but while changing the uuid from my user model with unique=True and editable=False While executing migrate command , I am getting "psycopg2.errors.UniqueViolation: could not create unique index" error with Key (hnid)=(8c0bc4a2-165a-47d5-8084-8b87600c7fe8) is duplicated. Note: I am using postgres How can I solve this issue -
Saving Serializers with Foreign Key (django rest framework)
I have two models which is Task and Batch that are related to each other by Foreign Key field. When creating a Task Object, I want to check first if a Batch Object is available in database (batch is just the current date, so I can group each task using batch). If not, create a Batch object and then pass the newly created batch object to the Task that is being created. views.py @api_view(['POST']) def taskCreate(request): batch = Batch.objects.filter(batch = datetime.date.today()).first() serializer = TaskSerializer(data=request.data) if serializer.is_valid(): serializer.save(commit=False) if batch is None : batch = Batch.objects.create(batch = datetime.date.today()) serializer.batch = batch serializer.save() return Response(serializer.data) models.py class Batch(models.Model): batch = models.DateField(auto_now_add=True) class Meta: ordering = ['-batch'] verbose_name = 'Batch' verbose_name_plural = 'Batches' def __str__(self): return self.batch.strftime("%B %d, %Y %A") class Task(models.Model): title = models.CharField( max_length = 256, ) completed = models.BooleanField( default = False, ) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) def __str__(self): return self.title serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' depth = 1 this is how I handle my form in frontend: var form = document.getElementById("form") form.addEventListener('submit', function(e){ e.preventDefault() var url = "{% url 'api:task-create' %}" if(activeItem != null ){ url = `http://localhost:8000/api/task-update/${activeItem.id}/` activeItem = null } var … -
Python Django __init__() takes 1 positional argument but 2 were given
Hi i started to make django and started with simple Hi app. But when i want to access on /hi/ i give error called "init() takes 1 positional argument but 2 were given" Here is code #urls.py from django.contrib import admin from django.urls import path from hi.views import hiView urlpatterns = [ path('admin/', admin.site.urls), path('hi/', hiView), ] #views.py from django.shortcuts import render from django.http import HttpRequest def hiView(request): return HttpRequest('Hi.') #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hi', ] im adding my directory list https://imgur.com/N3uJG1f -
Empty QuerySet for Django Multi-Table Inheritance Subclass
I have the following models: APP 1: class User(AbstractBaseUser): # custom fields etc # NOT ABSTRACT APP 2: class SecondaryUser(User): # other custom fields When I do SecondaryUser.objects.create(...) I get an instance as expected: In: SecondaryUser.objects.create(first_name='test', last_name='test', email='test@etest.com') Out: <SecondaryUser> This has an id and populated fields as expected. I can also query the base class and use the django-generated 1-1 field for the inheritance to access the subclass's fields: User.objects.get(email='test@etest.com').secondaryuser.<some_field> However when I do SecondaryUser.objects.all() it returns an empty queryset. And the model admin for the SecondaryUser shows an empty list view (even when I create a new instance of SecondaryUser in the admin create view). I feel like I'm missing something obvious, I need to be able to list the SecondaryUser instances in the admin. The User class cannot be abstract. -
django apache :WSGIPythonHome cannot occur within <VirtualHost> section
i have a server with ubuntu-server that run apache2 and where i have my django project. i'm having trouble deploying the app. this is my /etc/apache2/sites-available/000-default.conf: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName HIVE.localhost ServerAdmin webmaster@localhost DocumentRoot /home/leo/HIVE/src # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for … -
Django & Celery - Domotic Project with Raspberry
I started a new project with Raspberry Pi that controls a series of sensors and activates relays when certain conditions occur. The script runs well stand alone but I need to integrate it into a django app to control certain cases (e.g. temperatures, humidity, manual switches, etc.) So, I have pip installed celery and redis and configured it. What I need to understand is how to make the while scrip start contextually to the app and not block it when the app starts. The script is very simple def startdomo() stuffs = Stuffs.objects.get(pk=1) while True: do some stuffs I try to put it into url.py at the end urlpatterns = [ url(r'', include('FBIsystem.urls')), ] startdomo() In this case startdomo run but django app not run. The goal is to use Celery to run startdomo async respect to the app. Thanks in advance. -
Use elasticsearch on a local folder
So basically I have a Python Django app that get lots of html pages. I store them locally like this (imagine a lot more) : I want to search by key word(s) in all the these index.html I understood that Elasticsearch is a really powerfull tool but I don't know if it can fits my needs. I searched on the internet but didn't find really accurate websites that could help me. -
name 'ValidationError' is not defined in django form
I'm trying to restrict a user if they enter an e-mail that already exists during registration. This is the error i get Exception Value: name 'ValidationError' is not defined User Form from django import forms from django.db import models from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): email = forms.EmailField() def clean(self): email = self.cleaned_data.get('email') if CustomUser.objects.filter(email=email).exists(): raise ValidationError("Email already exists") return self.cleaned_data -
Django - is token/JWT authentication safer if backend and frontend are on the same server?
I'm researching the best security approaches for a webapp that i want to build, where the backend should be separated from the frontend but they will both be on the same server. The frontend is a standalone VueJS application while the backend is a Django app that will communicate with Vue using JSON, but i think this still applies to other frameworks like react or angular. For authentication, i would use djoser and probably token based authentication or JWT. I made some research about this topic and found that there are some concerns on token based authentication, mostly related to token storage on the client side. My question is: when backend and frontend are on the same server, instead of being cross domain, do these security concerns still apply? Or is it a much safer approach? If i deploy the two apps on the same server, can i store the tokens on Vuex or any other local storage safely? What can i do, instead, on the Django side, to make the app as safe as possible? -
Calling two fetch Requests in Django with Javascript displays the result in the same div
I am really new to Javascript therefore be kind! There must be something wrong with the way I am structuring this. I have seen possible solutions, could involve async functions and I tried them but for some reason, I might not get the order straight, or simply I am missing the point. I am using a fetch request to source some data at first from the API that I made on my local server. And that works fine. I am able to source the names of the cryptocurrencies that I have coupled with a username in JSON format. After I have created the styling for the divs to display and inserted the data in, I call another fetch for another API this time external, to further source data and insert it in divs I have created previously, per each piece of data I sourced from my own API. For some reason, it ends up displaying the data that I am fetching from this external API all in the same div, instead of displaying them for each. I have tried a forEach function, I have tried (i=0;i<data.lenght;i++), I have tried to place it differently, I have tried creating global variables and … -
making context variable from one method accessible to other other methods (and views) in Django
i'm working on a dashboard project (django + charts.js) that currently looks like this: currently, all of the charts are based on all the data in the database (approx 1.5 mil lines). however, i'd like these charts to be responsive to the dates indicated in the start date/end date HTML widget - e.g. show payment methods, taxi orders by the hour/day of week according to the start/end dates indicated. my date_input method gets the start and end dates from the frontend, and queries my MySQL database according to the dates selected. these queries are then rendered to the context variable of date_input - however, i'd like the context variable in date_input to be available to all methods (each chart is rendered by a different method, based on the JsonResponse returned to different endpoints). i've tried making context available as a global variable by defining it outside date_input as queryset = date_input(request) - NameError: name 'request' is not defined. i've looked into context processors, but that seems to be an option only if i didn't have a request (e.g. start/end date input from the frontend). i'm rather confused and would appreciate some help. here's my views.py code: def date_input(request): if request.method … -
Set different password for Django admin users than for the public Django app
We have a Django app where we're using the default password/password reset functionality. Lots of our staff also login to Django admin using the same credentials. Is it possible to create separate passwords for these two areas (the public app and Django admin)? The advantage of doing this is I can set & enforce strong passwords for everyone in Django admin, and people aren't tempted to change them to something that's easier to log into the public app with. -
Django - Override save() method of auth_user model
I want store the username of the auth_user table into the first_name, if no first name is provided. Something like this: from django.contrib.auth.models import User class CustomUser(User): class Meta: proxy = True def save(self, *args, **kwargs): if not self.first_name: self.first_name = self.username super(CustomUser, self).save(*args, **kwargs) Thank you -
Requests-oauthlib access token reuse in Django App
I'm able to fetch an OAuth2 access token using Backend Application Flow for Requests-Oauthlib. The API documentation states "Re-use the access token until it expires. Then, get a new token". from oauthlib.oauth2 import BackendApplicationClient client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=client_id, client_secret=client_secret) The Requests-Oauthlib documentation states that you can save the token, but has no further information on how to do this. The token has 'expires_in' and expires_at fields returned in addition to the access token. I'm going to this in a Django App, but I'm not sure where to store the access token as it's for the Application, not User. How can I retain the token to re-use until it expires? -
Django - Cannot combine a unique query with a non-unique query or pub_date field look up not available
Trying to filter queries by name & datetime. The query should fulfill both criteria, i tried using field lookup in single query using pub_date__date field lookup , it threw the error pub_date not available, then i tried using date field, but that didnt work either. dtt here is = datetime.datetime.now() orders = OrderItemss.objects.filter(customer=customer_object, pub_date__date= str(dtt.day)) orders = OrderItemss.objects.filter(customer=customer_object, date= str(dtt.date()) when i tried combining 2 queries using & , it throws the error 'Cannot combine a unique query with a non-unique query' code: orders = OrderItemss.objects.filter(customer=customer_object) & Customer.objects.datetimes('date', 'hour', order='DESC') -
Custom User Model in Django throws SettingsReference error when making migrations
thanks in advance. I'm trying to build a custom user model and profile model for use in a Django app. I'm just subclassing the built-in CustomUser in case I want to add authentication features in the future, and adding all of the non-authentication related user information in CustomUserProfile. Here's the code: from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save class CustomUser(AbstractUser): # ADD AUTH FUNCTIONALITY IN THE FUTURE HERE pass def __str__(self): return self.email class CustomUserProfile(models.Model): # relates profile to user user = models.OneToOneField(CustomUser, related_name="profile", on_delete=models.CASCADE) # the next date the payment is due payment_due_date = models.DateField(null=True) def save(self, *args, **kwargs): # custom save logic will go here super().save(*args, **kwargs) def __str__(self): return f"Profile of user: {self.user.email}" # post save hook that creates a user profile for new users def create_user_profile(sender, instance, created, **kwargs): if created: CustomUserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=BaseUser) And in the settings.py file, I have included the user model and profile with: AUTH_USER_MODEL = 'accounts.CustomUser' AUTH_PROFILE_MODULE = 'accounts.CustomUserProfile' The error I'm getting occurs when I run manage.py makemigrations. Specifically, it's returning AttributeError: 'SettingsReference' object has no attribute '_meta'. Frankly I'm not sure where to begin … -
REDIRECT_FIELD_NAME from django.contrib.auth
In my class-based django view, I am using redirect_field_name = REDIRECT_FIELD_NAME. May I know where I am redirecting to, and also by default, what is the field name and how I can set it? Thank you def zulip_login_required( function: Optional[ViewFuncT]=None, redirect_field_name: str=REDIRECT_FIELD_NAME, login_url: str=settings.HOME_NOT_LOGGED_IN, ) -> Union[Callable[[ViewFuncT], ViewFuncT], ViewFuncT]: actual_decorator = lambda function: user_passes_test( logged_in_and_active, login_url=login_url, redirect_field_name=redirect_field_name, )( zulip_otp_required( redirect_field_name=redirect_field_name, login_url=login_url, )(add_logging_data(function)) ) if function: return actual_decorator(function) return actual_decorator # nocoverage # We don't use this without a function -
How to customise the representation of fields of a nested serializer?
I am having a nested serializer as:- serializers:- class DeviceConfigSerializer(serializers.ModelSerializer): config = serializers.JSONField() context = serializers.JSONField() class Meta: model = Config fields = ['backend', 'status', 'templates', 'context', 'config'] class DeviceDetailSerializer(serializers.ModelSerializer): config = DeviceConfigSerializer() class Meta(BaseMeta): model = Device fields = [ 'id', 'name', 'organization', 'mac_address', 'key', 'last_ip', 'management_ip', 'model', 'os', 'system', 'notes', 'config', ] def update(): ... ... ... Views:- class DeviceDetailView(RetrieveUpdateDestroyAPIView): serializer_class = DeviceDetailSerializer queryset = Device.objects.all() When I try to get the data with a get request, this is what I receive:- but the fields in the HTML Form section of browsable API doesn't represent the context and config field in JSON format, instead, this is what I receive:- What I expect is to have the same representation of the context and config fields for the HTML Form and the JSON response.