Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django migrations making no changes to my admin site after altering my model.py
from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=255) title_tag = models.CharField(max_length=255, default='awesome') author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) -
Go to the appropriate tab when JavaScript True False
I would like to write JavaScript as follows and move it to Tab4 when it is true, and to display the modal when it is false. Even if it's not modal, it's good to just move to Tab4 when True. How can I solve this problem? If you help me, I'll adopt it right away. javascript // run the webcam image through the image model async function predict() { // predict can take in an image, video or canvas html element var image = document.getElementById("face-image") const prediction = await model.predict(image, false); prediction.sort((a,b) => parseFloat(b.probability) - parseFloat(a.probability)); switch (prediction[0].className){ case "True": resultMessege = "success." break; case "False": resultMessege = "fail" break; default: resultMessege = "error" } $('.result-message').html(resultMessege); for (let i = 0; i < maxPredictions; i++) { const classPrediction = prediction[i].className + ": " + prediction[i].probability.toFixed(2); labelContainer.childNodes[i].innerHTML = classPrediction; } } I want to move tab <input id="tab1" type="radio" name="tabs" checked> <label for="tab1"><img src="https://image.flaticon.com/icons/svg/126/126486.svg"><br>STEP 1<br>1</label> <input id="tab3" type="radio" name="tabs"> <label for="tab3"><img src="https://image.flaticon.com/icons/svg/839/839860.svg"><br>STEP 2<br>2</label> <input id="tab4" type="radio" name="tabs"> <label for="tab4"><img src="https://image.flaticon.com/icons/svg/3064/3064197.svg"><br>STEP 3<br>4</label> -
Could not load a database from C:\Users\Nenye\Documents\fleetmgt\fleetmgt\geoip
I'm working on a python/django web app that should fetch clients current location and calculate his distance after getting his destination from client's input. here's my code: my view: from django.shortcuts import render from geopy.geocoders import Nominatim from .models import Ride from .forms import BookRideForm from .utils import get_geo def book_a_ride_view(request): form = BookRideForm(request.POST or None) geolocator = Nominatim(user_agent="riders") ip = '72.14.207.99' country, city, lat, lon = get_geo(ip) print('country:', country) print('city:', city) print('lat:', lat) print('lon:', lon) msg = "" if form.is_valid(): new_form = form.save(commit=False) destination_ = form.cleaned_data.get('destination') destination = geolocator.geocode(destination_) print(destination) d_lat = destination.latitude d_lon = destination.longitude new_form.rider_id = request.user.id # new_form.save() form = BookRideForm() msg = 'Your booking is Successful' template = 'riders/book_ride.html' context = {"form":form, "msg":msg} return render(request, template, context) Here's utils.py: from django.contrib.gis.geoip2 import GeoIP2 # HELPER FUNCTIONS def get_geo(ip): g = GeoIP2() country = g.country(ip) city = g.city(ip) lat, lon = g.lat_lon(ip) return country, city, lat, lon i get this error: System check identified no issues (0 silenced). August 26, 2021 - 18:56:09 Django version 3.2.6, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /ridersbook_a_ride Traceback (most recent call last): File "C:\Users\Nenye\Documents\fleetmgt\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = … -
Serving Static Images in AWS - Django - Python
I have all of my static images served locally on my Django website project. I need them to be hosted on AWS for my DEBUG = False to work. I have followed many tutorials on how to do this and have had no luck. I have posted my code below for a last-ditch effort hoping that it is just something I have missed. I have my AWS bucket currently as public because that's what I have seen others doing. Any help is greatly appreciated. Thanks! setings.py AWS_ACCESS_KEY_ID = 'AKIAVADFUL4TVW3IKZLA' AWS_SECRET_ACCESS_KEY = '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' AWS_STORAGE_BUCKET_NAME = 'hidden for privacy' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Caracas' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) #STATIC_ROOT = os.path.join(BASE_DIR, 'static') #MEDIA_URL = '/images/' #MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '..','www','media') HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="shortcut icon" type="image/x-icon" href="{% static 'tab_icon.ico' %}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static "css/side.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" %}"> <link rel="stylesheet" href="{% … -
Pass user to model manager
I have a custom model manager: class DBSearch(models.Manager): def search(self, query, user): qs = self.get_queryset() qs = db_search(qs, query) return qs My custom user object has a sting property db_name which I want to pass to using argument of db_manager or to self._db. What is the right way to do that? -
How to make seperate comment section for each item
I am making django app I have a problem I dont have idea how to make seperate comment section to each Item. I do not want to have same comments for every Item on a page. models.py class Comment(models.Model): comment_user = models.OneToOneField(User, on_delete=CASCADE) item = models.OneToOneField(Item, on_delete=CASCADE) content = models.TextField(default='') views.py class ShopDetailView(DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.all() return context -
"The file cannot be reopened." error from django-imagekit after moving a file
I'm using django-imagekit to generate a thumbnail on a Django model: class Book(models.Model): title = models.CharField(null=False, blank=False, max_length=255) thumbnail = models.ImageField( upload_to=upload_path, null=False, blank=True, default="" ) list_thumbnail = ImageSpecField(processors=[ResizeToFit(80, 160)], source="thumbnail", format="JPEG") That works fine. However I'm trying to move the original thumbnail file after upload. Here's a simplified version of my save() method, that just moves the file into a "new" directory and re-saves the object (it's more complicated than that really): def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.thumbnail and "/new/" not in self.thumbnail.path: # Move the thumbnail to correct location. initial_name = self.thumbnail.name initial_path = self.thumbnail.path new_name = os.path.join(os.path.dirname(initial_name), "new", os.path.basename(initial_name)) new_path = os.path.join(settings.MEDIA_ROOT, new_name) if not os.path.exists(os.path.dirname(new_path)): os.makedirs(os.path.dirname(new_path)) os.rename(initial_path, new_path) self.thumbnail.name = new_name kwargs["force_insert"] = False super().save(*args, **kwargs) This works fine by default. But if I have this in settings.py: IMAGEKIT_DEFAULT_CACHEFILE_STRATEGY = "imagekit.cachefiles.strategies.Optimistic" then I get errors resulting from imagekit signals, presumably confused that the file has moved while trying to generate the list_thumbnail. Here's some of the traceback: ... File "/venv-path/python3.8/site-packages/imagekit/specs/sourcegroups.py", line 33, in receiver fn(self, sender=sender, **kwargs) File "/venv-path/python3.8/site-packages/imagekit/specs/sourcegroups.py", line 101, in post_save_receiver self.dispatch_signal(source_saved, file, sender, instance, File "/venv-path/python3.8/site-packages/imagekit/specs/sourcegroups.py", line 124, in dispatch_signal signal.send(sender=source_group, source=file) File "/venv-path/python3.8/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File … -
Django drf-spectacular - Can you exclude specific paths?
We have a bunch of api's with different versions in urls.py, eg api/v1 api/v2 api/v3 . We want to implement swagger with drf-spectacular, but we only want to expose api/v3 endpoints. Is there a way to do this? I cannot make sense of the documentation. Thanks -
FOREIGN KEY constraint failed. Django allauth error in EmailAddress
I use allauth in my Django app. I have custom User Model and custom Signup Form. At first, Model and Form were in the app called "main", then I created a new app called "user" and moved them to new app. And now I get FOREIGN KEY constraint failed error when I signup new user. I have this in my settings.py: AUTH_USER_MODEL = "user.Account" ACCOUNT_FORMS = { "signup": "user.forms.CustomSignUpForm", } My custom SignUp Form: class CustomSignUpForm(SignupForm): full_name = forms.CharField(max_length=350, label="Full Name", required=True) def save(self, request): user = super(CustomSignUpForm, self).save(request) user.full_name = self.cleaned_data['full_name'] user.save() return user My models.py: class AccountManager(BaseUserManager): def create_user(self, email, full_name, password=None): if not email: raise ValueError("Users must have email address") if not full_name: raise ValueError("Users must have name") user = self.model( email=self.normalize_email(email), full_name=full_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, full_name, password): user = self.create_user( email=self.normalize_email(email), password=password, full_name=full_name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): GENDERS = ( ("M", "Male"), ("FM", "Female"), ("O", "Other") ) SPECIALIZATIONS = ( ("DV", "Developer"), ("DS", "Designer"), ) email = models.EmailField(verbose_name="email", max_length=60, unique=True) full_name = models.CharField(max_length=350) gender = models.CharField(max_length=50, choices=GENDERS) birth_date = models.DateField(null=True, blank=True) specialization = models.CharField(max_length=250, choices=SPECIALIZATIONS) extra_info = models.BooleanField(default=False) contacts = … -
Unable to make multiple requests in a row using the google drive API
I have a problem with my google drive API. I use this code to connect to my google account and get service : from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build def getService(): # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive'] """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'code_secret_client_632139208221-9tetq1fkkbud9ucmcq0bl3k4e3centem.apps.googleusercontent.com.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) service = build('drive', 'v3', credentials=creds) return service It works perfectly, but when I call 2 times for example : result1 = GoogleDrive.service.files().list( pageSize=1000, fields="nextPageToken, files(id, name)").execute() result2 = GoogleDrive.service.about().get( fields="storageQuota").execute() I have this error : ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong … -
how to revoke access token in django_simple_jwt?
I'm using simple JWT in Django and I blacklist the refresh token when user want to log out. but I don't know why access token is still working. how can I revoke it? thank u. -
Django Rest Framework - general approach on handling guest users
I'm trying to implement handling of guest (anonymous) users in my Django/React app using DRF, but I'm not sure exactly how to proceed. What I want eventually is, when a non-registered user comes to my homepage, he can perform limited CRUD operations eg. creating a maximum of 10 tasks, and when he chooses to register, these limitations are then lifted. A while ago, I did the same app but only with Django, and the way I had it set up, was when an anonymous user visited the page, a new user was created without a password. I was using this function to achieve this: def getUser(self): if not self.request.user.is_authenticated: ip = get_client_ip(self.request) if UserAccount.objects.filter(ip_address=ip).exists(): return UserAccount.objects.get(ip_address=ip) random_username = f"{randomString(10)}_guest" random_email = f"{randomString(5)}_guest@example.com" guest_user = UserAccount.objects.create( username=random_username, email=random_email, ip_address=ip, is_active=False, ) return guest_user else: return request.user And later, when this user submitted the registration form, I used the same function to retrieve this "guest" user and updated the rest of the model fields (email...) and set his password. Now, to return to the original question, how would I go about doing the same thing with the rest framework? I was also looking at the DRF documentation, and for authentication, you need … -
Как добавить форму в django, для добавления пользователем разного товара? [closed]
models - тут несколько моделей и хочу, чтобы пользователь смогу выбрать категорию товара и выложить на сайт товар class Product(models.Model): class Meta: abstract = True category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.CASCADE) title = models.CharField(max_length=255,verbose_name='Наименование') slug = models.SlugField(unique=True) image = models.ImageField(verbose_name='Изображение') description = models.TextField(verbose_name='Описание', null=True) price = models.DecimalField(max_digits = 9, decimal_places=2,verbose_name='Цена') class Notebook(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') Processor_freq = models.CharField(max_length=255, verbose_name='Частота ЦП') class SmartPhones(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') sd = models.BooleanField(default=True) -
Good resources to learn Django
I am beginner on my road to backend. I have already learnt python basics, html basics and a bit of algorithms and data structure. The problem arose when I tried to learn Django. I mean all the resources that I have found so far are like “do this, write that and it will work”. Before I use something I would like to know why it works and how it works so that in theory I’d be able to do all the stuff even without Django or any other framework. Any good books or other online resources on Django you could suggest? I’d really appreciate. Thank you. -
Djano 3.2 is not generating permissions for model with pre-existing table
Under django 3.2, py3.7, followed pretty much standard steps to add a new model to the application but it does not appear in the permissions list under django-admin->groups. I had a pre-existing table in the DB called 'feedback'. Created a model for it under model.py. Under admin.py, created a ModelAdmin for it and registered it: admin.site.register(Feedback, FeedbackModelAdmin) Then executed python manage.py makemigration that created a migrations file with the respective migrations.CreateModel block for feedback model. Finally executed python manage.py migrate which ran the migration. Did not report with messages like, table already exists etc. The new model is visible in admin, data can be viewed and edited but no permissions were created for it ie When I go to the groups (as superuser), the available permissions list doesnt have this model. Have I missed a step? Is there another way to create permissions for this model other than running python manage.py migrate? -
Django admin screen won't let me see the list of entries under each mondel
I'm currently using Django and I just ran into this problem. When I click on a model in admin, it takes me back to the same screen. For example, if I click on news under NFL on this screen: It takes me to this screen instead of the list of entries: Why would this be happening? I haven't changed in the models since this occurred. -
How do you add an object to a many-to-many relationship through a form on Django?
I have the following models: class Exercise(models.Model): exercise = models.CharField(max_length=166) series = models.CharField(max_length=2) reps = models.CharField(max_length=2) station = models.ForeignKey(Station) class Workout(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) day = models.CharField(max_length=1) exercises = models.ManyToManyField(Exercise) I want to be able to have a page where each Workout is displayed and the user can add Exercises when clicking a + button. So, this would take the Workout ID from the URL, and when creating an Exercise would automatically associate it to that workout. I was trying something along this line, but I don't think works: if request.method == 'POST': np_form = NewWorkout(request.POST) ne_form = NovoExercise(request.POST) if ne_form.is_valid() and np_form.is_valid(): nesave = ne_form.save() npsave = np_form.save(commit = False) npsave.exercises = nesave npsave.save() -
Field Boolean is not updating with time
I am building a Blog App And I am trying to hide blog posts which are older than seven days so, I am showing blog posts which are newer than 7 days. Then i think i can update the boolean if post is older then 7 days. I made a function in models to update the field after seven days. BUT The field is not updating. models.py import datetime from django.utils import timezone from datetime import timedelta class BlogPosts(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) is_older = models.BooleanField(default=False) title = models.CharField(max_length=30) date_added = models.DateTimeField(auto_now_add=True) def active(self): now = timezone.now() # changed 15 seconds for testing if date_added > timezone.now() - timedelta(seconds=15): is_older = False When someone posts a blogposts then boolean is saving to true and I am trying to set to False after 7 days. Any help would be much Appreciated. Thank You in Advance. -
Django: Pass context into a template using Ajax
I know this questionhas been asked here. But the anwser didnt quite fit my need. In my Django project I want to give context data as a dictionary to my templates. like in the normal: return render(request, 'the.html', context) I first build my entire Website without any ajax, so it would be quite a lot of work to entirely rewrite with the ajax HTML on succes like: $("#div_to_update").html( -- completely rewrite already written html code to fit the new ajax -- ) Is there a way to more easily pass context to django template like? $("#div_to_update").set_context(context_the_server_passed_to_ajax) -
How to authenticate a django app with docker from another django app with docker that takes care of users?
I have a django (Docker) container to login, register, etc. with django-simplejwt and another django container that I want to authenticate with the first one. I am using redis to cache the access and refresh token, but I don't know how to authenticate the second with the credentials of the first. Can anyone help? -
Django cache_page - prepopulate/pre-cache
I have one DB query that takes a couple of seconds in production. I have also a DRF ViewSet action that returns this query. I'm already caching this action using cache_page. @method_decorator(cache_page(settings.DEFAULT_CACHE_TIMEOUT)) @action(detail=False) def home(self, request) -> Response: articles = Article.objects.home() return Response(serializers.ArticleListSerializer(articles, many=True).data, headers={'Access-Control-Allow-Origin': '*'}) The problem is that after 15 minutes, at least one user needs to wait 15 seconds for the response. I want to pre-cache this every 5 minutes in background so that no user will need to wait. I use the default caching mechanism. My idea is to create a management command that will be executed using crontab. Every 5 minutes it will call the Article.objects.home() or the ViewSet.action and change it's value in the cache. As this is only one entry, I don't hesitate to use database caching. How would you do that? EDIT: as the default LocMemCache is single-threaded, I'll go with the database caching. I just don't know how to manually cache the view or QuerySet. -
OneToOne field in django default
Please help. I have a model: class Book(core.BaseModel): book_link = models.OneToOneField('self', default = "", on_delete=models.CASCADE) book_name = models.CharField('Name', max_length=250) I want to set 'self' in field book_link that will return in this field - book_name or Book Model object. But when I create new Book object - Django shows me in column "book_link" all book names which I can choose and save new object. I want that when I created new object it will authomatically save for this object this name! -
Count how many posts a user liked in Django
I would like to create a variable that I can pass through as context which will count how many posts a user liked. Here is my models.py class post(models.Model): title = models.CharField(max_length = 255) title_tag=models.CharField(max_length=255) author = models.ForeignKey(User, on_delete = models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length=255, default = "coding") likes = models.ManyToManyField(User, related_name='blog_posts') def __str__(self): return self.title + ' | ' + str(self.author) + ' | ' + str(self.category) def get_absolute_url(self): from django.urls import reverse return reverse('article-detail',args=[self.id] ) def total_likes(self): return self.likes.count() Here is my views.py class ArticleDetailView(DetailView): model = post template_name = 'article_details.html' def get_context_data(self,*args,**kwargs): cat_menu = Category.objects.all() #amount_of_user_likes = ???? context = super(ArticleDetailView,self).get_context_data(*args,**kwargs) '''context allows us to access these values on our page''' stuff=get_object_or_404(post,id=self.kwargs['pk']) total_likes= stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context['cat_menu'] = cat_menu context['total_likes']=total_likes context['liked'] = liked context['amount_of_user_likes']=amount_of_user_likes return context I am not sure how to query the Database in order to get the amount of posts that a user liked since the liked column is on the post table and not on the user table. However, since it is a many to many relationship then we can access the user somehow but I am unsure. -
psql not found in script for trying to control startup and shutdown order in Docker Compose
I'm trying to make sure my Django app waits for my Postgres db to start so I don't get this error django.db.utils.OperationalError: FATAL: the database system is starting up, I've read this https://docs.docker.com/compose/startup-order/, and here is what I have so far docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres"] interval: 5s timeout: 5s retries: 5 environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} backend: build: ./backend command: python3 manage.py runserver volumes: - ./backend:/code ports: - "8000:8000" command: ["./wait-for-it.sh", "db", "bash", "entrypoint.sh"] depends_on: - db wait-for-it.sh #!/bin/sh # wait-for-it.sh set -e host="$1" shift cmd="$@" # postgres until PGPASSWORD=$DB_PASSWORD psql -h "$host" -U "postgres" -c '\q'; do >&2 echo "Postgres is unavailable - sleeping" sleep 1 done >&2 echo "Postgres is up - executing command" exec $cmd Dockerfile # syntax=docker/dockerfile:1 FROM python:3.9.6-alpine3.14 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps COPY . /code/ RUN chmod u+x ./wait-for-it.sh -
How to upload images to django REST api?
I'm creating a backend with DRF to upload json data that I later consume with a REACT frontend. By now it's pretty standard and simple. My django model has an ImageField that is serialized as a string in the form of "http://127.0.0.1:8000/media/example-randomcharacters.png". (I define the media folder in the settings.py in django). As expected, there is now a new file in the media folder with the name shown in the API, but when I try to get the image from the url it returns this: Of course it can't be used by react or any other external tool since the url doesn't provide the image. What am I doing wrong? Here is the django code: models.py: from django.db import models class Project(models.Model): """Programming related project to show on my website. """ title = models.CharField(max_length=100) description = models.TextField() cover = models.ImageField() link = models.URLField() date_started = models.DateField(auto_now_add=True) last_edited = models.DateField(auto_now=True) def _str_(self): return self.title serializers.py: from rest_framework import serializers from .models import Project class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__'