Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting problem with scheduling periodic tasks with multitenant(django-tenant-schemas)?
I m getting problem with scheduling periodic task celery beat for a multitenant(django-tenant-schemas) architecture. Whenever I am running celery beat database scheduler command, its pointing to public schema. I want it to pick periodic task from tenant schemas. Any idea how to make it tenant aware call? I found this github, but didnt understand how to use it for multiple schema. https://github.com/maciej-gol/tenant-schemas-celery In above repository, when to call reset_remaining_jobs_in_all_schemas and how will it take multiple periodic task from all schemas? -
psycopg2.errors.UndefinedTable: relation “exercises” does not exist - Django Testing
I started writing my first tests in django. I have problem with testing POST method based on model. My project tree looks: - db.sqlite3 - manage.py - tree.txt - ----api - - admin.py - - apps.py - - models.py - - serializers.py - - urls.py - - views.py - - __init__.py - - - ----migrations - - - 0001_initial.py - - - __init__.py - - - - - - ----tests - - - test_models.py - - - test_urls.py - - - test_views.py - - - __init__.py - - - - - - ----drummingpractice - - asgi.py - - settings.py - - urls.py - - wsgi.py - - __init__.py - - - ----frontend - - admin.py - - apps.py - - models.py - - urls.py - - views.py - - __init__.py - - - ----migrations - - - __init__.py - - - - - - ----templates - - ----frontend - - exercises_catalog.html - - exercise_add.html - - workouts_history.html - - workouts_stats.html - - workout_add.html - - - ----tests - - - test_models.py - - - test_urls.py - - - test_views.py - - - ----static I writing tests for app 'frontend'. I tried test function 'add_exercises' frontend.views.py def add_exercise(request): if request.method == … -
Newbie to Django framework - '"Todo" list not appearing in Django Admin
So I've just started out learning Python and getting my head around the Django Web Application framework. I do apologise if my issue comes across as a rookie error, but I guess we all have to begin somewhere?! I am using the latest version of Django and currently running my Django application on my CentOS 8 server with SQLite. I have been referencing this tutorial to create a basic Todo list application https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react After following all the steps (With regards to setting up to the Todo list within Django Admin) I can't get the Todo list to actually appear within the Admin interface. I've created a new Todo app, added in the relevant code in to both admin.py and models.py, I have made migrations and executed the migrations as per the tutorial. I've also added 'todo' within the installed apps area of my settings.py file. Finally, I've logged in to my Admin interface and have ensured that my account has the correct permissions to access the Todo list (The Todo list permissions are appearing at least) although, the actual application itself isn't appearing on my Django Admin Dashboard. I feel that I'm missing something small here, but any pointers would … -
How to debug a dockerized Django app with PyCharm
I've a Django app and its dependencies running in docker containers (on Windows 10 with WSL2). This is working fine but I'd like to be able to debug it through PyCharm Pro. Here's my web container in the docker-compose # The main container - containing the Django code web: build: ./web ports: - "8000:8000" depends_on: - postgres #wait for postgres to be started, not for ready - redis - npm_watch - migration volumes: - ./web:/usr/src/app - ./web/collectstatic:/usr/src/app/collectstatic env_file: .env environment: DEBUG: 'true' LOCAL: 'true' restart: always command: su myuser -c "/usr/local/bin/python manage.py runserver 0.0.0.0:8000" I configured a Docker Compose interpreter targeting the Django app container and created a Django Server Run/Debug configuration see below (up command option is to have all containers started) When started in debug, the break points are never caught. I noticed that my Django app is not running on port 8000 as described in my Docker-compose (works fine when started with Docker compose). Is PyCharm running another Django server in parallel ? Or is it because the restart: always that PyCharm disconnects from the container (it restarts until everything is in place). I also tried to add a Docker configuration but it seems that you cannot … -
Django: How to have a local Postgresql connection when production postgres database is on heroku?
My production postgresql database is successfully running on Heroku. Before this, I had a local postgres database configured as the default during development. But, now, after I hooked the Heroku postgres with dj-database-url, whenever I run python manage.py runserver to make changes locally, I get this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: server does not support SSL, but SSL was required This is my database setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'DATABASE_URL': os.getenv('DATABASE_URL'), 'NAME': os.getenv('DATABASE_NAME'), 'USER': os.getenv('DATABASE_USER'), 'PASSWORD': os.getenv('DATABASE_PASSWORD'), 'HOST': os.getenv('DATABASE_HOST'), 'PORT': os.getenv('DATABASE_PORT') } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600, ssl_require=True) DATABASES['default'].update(db_from_env) Even though not required, my local DATABASE_URL in env is this: DATABASE_URL=postgres://{user}:{password}@{host}:{port}/{database name}?sslmode=require It only worked i.e. runserver ran successfully when I commented the dj-database-url snippet but that's not a solution. So, how do I run a local Postgres database along with the Heroku postgres? -
My form doesn't save the value that it gets from the template, django
I want to add a car information from the form but it sees the form as invalid. It doesn't add the car into my car inventory. Where do I make the mistake? Here is my views.py def add_car_step_1(request): form = AddCarForm() if request.method == "POST": form = AddCarForm(request.POST) if form.is_valid(): brand = form.cleaned_data['brand'] status_of_car = form.cleaned_data['status_of_car'] (...) fuel_type = form.cleaned_data['fuel_type'] no_of_owners = form.cleaned_data['no_of_owners'] data = { 'brand': brand, 'status_of_car': status_of_car, (...) 'fuel_type': fuel_type, 'no_of_owners': no_of_owners, } form.save() return render(request, 'cars/cars.html', data) return render(request, 'cars/add_car_step_1.html', context={'form': form}) Here is my forms.py class AddCarForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) class Meta: model = Car fields = [ 'car_title', 'city', (...) 'fuel_type', 'no_of_owners', ] Sorry that the details are a bit much. -
Django - Adding index_together when iexact is used in filter
I am creating a index on 2 columns (that can be found in Django-index together index_together = [["name", "value"]] but I also want it to be case insensitive, because one of my filters will use iexact. Any idea how this can be achieved? I am using latest version of Django with DRF. I am basically just looking to add a index on those 2 columns that is case insensitive. Don't mind doing a raw SQL query in migration as well if no other way is possible, so raw SQL is also helpful. Just want to make sure that there isn't a native way of doing this -
Send a client-side generated PDF to a Django Server using JavaScript
I have an HTML web page with Bootstrap styling, and the client can download the webpage in the form of a PDF. For PDF generation, I'm using window.print(). On the backend or the server-side, I've Django. Now, I'm trying to convert that HTML page to a DOC file. I have already figured out a way to do so in the backend. But the input file should be a PDF. So, I need to send a PDF to the server from the client side. Client-side because the PDF generated using window.print() is needed. The PDF should be generated using window.print() only. But, "as far as I know", window.print() can't be automated and hidden on the client-side. The client interacts with the print dialog box. The workflow should be as follows - Client clicks on a button A PDF is automatically generated using window.print(). The generated PDF is sent to the Django server. Please help me with this. Thank you -
How to stop the execution of a long process if something changes in the db?
I have a view that sends a message to a RabbitMQ queue. message = {'origin': 'Bytes CSV', 'data': {'csv_key': str(csv_entry.key), 'csv_fields': csv_fields 'order_by': order_by, 'filters': filters}} ... queue_service.send(message=message, headers={}, exchange_name=EXCHANGE_IN_NAME, routing_key=MESSAGES_ROUTING_KEY.replace('#', 'bytes_counting.create')) On my consumer, I have a long process to generate a CSV. def create(self, data): csv_obj = self._get_object(key=data['csv_key']) if csv_obj.status == CSVRequestStatus.CANCELED: self.logger.info(f'CSV {csv_obj.key} was canceled by the user') return result = self.generate_result_data(filters=data['filters'], order_by=data['order_by'], csv_obj=csv_obj) csv_data = self._generate_csv(result=result, csv_fields=data['csv_fields'], csv_obj=csv_obj) file_key = self._post_csv(csv_data=csv_data, csv_obj=csv_obj) csv_obj.status = CSVRequestStatus.READY csv_obj.status_additional = CSVRequestStatusAdditional.SUCCESS csv_obj.file_key = file_key csv_obj.ready_at = timezone.now() csv_obj.save(update_fields=['status', 'status_additional', 'ready_at', 'file_key']) self.logger.info(f'CSV {csv_obj.name} created') The long proccess happens inside self._generate_csv, because self.generate_result_data returns a queryset, which is lazy. As you can see, if a user changes the status of the csv_request through an endpoint BEFORE the message starts to be consumed the proccess will not be evaluated. My goal is to let this happen during the execution of self._generate_csv. So far I tried to use Threading, but unsuccessfully. How can I achive my goal? Thanks a lot! -
Javascript static file not loading on pythonanywhere django website
Even though css static file loads, js codes in static folder refused to load even after I included the path on the web tab, all solutions I saw on pythonanywhere forum are all css centered. the weird part is after using developer tools i see css codes inside the js file in source instead of the actual js code. -
Django INSTALLED_APPS using hypen in app name ERROR
I'm having trouble with third-party package. The third-party package name uses hypen in its name. Third party package name is django-partial-content so because of usage hypen in naming of the package django giving me error that usage of hypen in installed apps is not allowed. django.core.exceptions.ImproperlyConfigured: The app label 'django-partial-content' is not a valid Python identifier. So basically what I tried to do, I tried to rename package name with dash but after renameing package didn't work at all. -
How could validate User's default field along with other custom field in Django REST API?
class ProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user', 'phone_number', 'date_of_birth','address','pin_code','city','country','region','website'] def create(self, validated_data): # user = validated_data.get('user') phone_number = validated_data.get('phone_number') print(phone_number) date_of_birth = validated_data.get('date_of_birth') address = validated_data.get('address') pin_code = validated_data.get('pin_code') city = validated_data.get('city') country = validated_data.get('country') region = validated_data.get('region') website = validated_data.get('website') user = UserProfile(**validated_data) user.serializable_value('date_of_birth') user.serializable_value('address') user.serializable_value('pin_code') user.serializable_value('city') user.serializable_value('country') user.serializable_value('region') user.serializable_value('website') user.serializable_value('user') user.serializable_value('phone_number') user.save() return user -
Openstack API Update Server Tags
I am using Django Rest API on open stack version 2.1 Unable to update Server Tags it is giving response text:'{"itemNotFound": {"code": 404, "message": "The resource could not be found."}}' the code explanation is there is an array of object contains multiple server objects with updated tags within a loop it will request and append responses in an array for front-end @classmethod def update_tags(self, params): check(self, params) responses = [] try: headers = { "X-Auth-Token": params.headers['x-auth-token'], "Content-type": 'application/json' } for server in params.data['payload']: replace_tags = {"tags": server["tags"]} response=requests.put(os.environ.get('PROTOCOL')+'://'+os.environ.get('OPENSTACK_HOST')+':'+os.environ.get('COMPUTE_PORT')+'/v2.1/servers/' +server['id']+'/tags', data=json.dumps(replace_tags), headers=headers, verify=False) responses.append(response) return responses except Exception as e: raise e -
Field 'id' expected a number but got 'logout_view'
I try to add new path and this happen Field 'id' expected a number but got 'logout_view'. In pycharm terminal i habe other error o.O ValueError: Field 'id' expected a number but got 'favicon.ico'. Files: urls.py -> from django.contrib import admin from django.urls import path from Artykuly.views import * urlpatterns = [ path('admin', admin.site.urls), path('', index, name='index'), path('<category_id>', category, name='category'), path('artykul/<category_id>', article, name='article'), path('login', login_view, name='login_view'), path('register', register_view, name='register_view'), path('logout', logout_view, name='logout_view'), ] views.py from django.contrib.auth import login from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Category, Article from .forms import LoginForm, RegisterForm # Create your views here. def index(request): Categories = Category.objects.all() dane = { 'Categories': Categories } return render(request, 'template.html', dane) def category(request, category_id): category_user = Category.objects.get(pk=category_id) article_data = Article.objects.filter(category_id=category_id).all() Categories = Category.objects.all() dane = { 'category_user': category_user, 'article_data': article_data, 'Categories': Categories, } return render(request, 'category.html', dane) def article(request, category_id): article = Article.objects.get(pk=category_id) article_user = Article.objects.filter(pk=category_id) Categories = Category.objects.all() dane = { 'article': article, 'article_user': article_user, 'Categories': Categories, } return render(request, 'artykul.html', dane) def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password1") password2 = form.cleaned_data.get("password2") try: user = User.objects.create_user(username, … -
Django annotate by foreign key
This is my models.py: class Category(models.Model): category_des = models.CharField(max_length=250) class Type(models.Model): type_des = models.CharField(max_length=250) class Product(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) type_id = models.ForeignKey(Type, on_delete=models.CASCADE) product_name = models.CharField(max_length=250) product_price = models.FloatField() What I want to do is to divide products into menus list and extras list and group them by category like this: Category 1: extra 1.a extra 1.b menu 1.c menu 1.d Category 2: extra 2.e extra 2.f menu 2.g menu 2.h and this is what I did in views.py: class MenuList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=1).annotate("category_id") serializer_class = serializers.ProductSerializer class MenuDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=1).annotate("category_id") serializer_class = serializers.ProductSerializer class ExtraList(generics.ListCreateAPIView): queryset = models.Product.objects.filter(type_id=2).annotate("category_id") serializer_class = serializers.ProductSerializer class ExtraDetail(generics.RetrieveUpdateDestroyAPIView): queryset = models.Product.objects.filter(type_id=2).annotate("category_id") serializer_class = serializers.ProductSerializer I got this error: TypeError: QuerySet.annotate() received non-expression(s): category_id. -
Can't make Codemirror config works
I followed the guidelines from the official website of mirrorcode and for some reason I am able to make only some of the configuration options work. In the example below you can see that the "firstlinenumber" config works fine but the others don't seem to be taken into consideration (value, theme etc). Note that I'm using django framework. Code: <link rel="stylesheet" href="{% static 'polls/codemirror/codemirror.css' %}"> <div> <textarea id="codemirrorTextArea"" cols="80" rows="24"></textarea> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript" src="{% static 'polls/codemirror/codemirror.js' %}"></script> <script type="text/javascript"> $(document).ready(function(){ var codeEditor = CodeMirror.fromTextArea(document.getElementById('codemirrorTextArea'),{ lineNumbers: true, theme:"dracula", tabsize:2, value:"15", mode:"python", firstLineNumber:5, }); }); </script> Output: -
How to display MultiSelectField in Template Django
I have a MultiSelectField in my models. I want to display MultiSelectField forms in my template like checkboxes below and I want the user to be able to check them and save the form. Feature_1 : [ ] Feature_2 : [ ] Feature_3 : [ ] {{ form.feature_1 }} doesn't display anything. The name of the form is AddCarForm models.py feature_1 = MultiSelectField(choices=feature_1_choice, max_length=100, default='', blank=True) feature_2 = MultiSelectField(choices=feature_2_choice, max_length=100, default='', blank=True) feature_3 = MultiSelectField(choices=feature_3_choice, max_length=100, default='', blank=True) feature_4 = MultiSelectField(choices=feature_4_choice, max_length=100, default='', blank=True) feature_5 = MultiSelectField(choices=feature_5_choice, max_length=100, default='', blank=True) feature_6 = MultiSelectField(choices=feature_6_choice, max_length=100, default='', blank=True) -
Unique constraint for many-to-many field
I have the following models from django.db import models class Man(models.Model): class = models.ManyToManyField(Class) class Classifier(models.Model): name = models.CharField() class Class(models.Model): classifier = models.ForeignKey(Classifier, on_delete=models.CASCADE) name = models.CharField() I.e. a man can have multiple classes, but only one per a classifier. How to implement this constraint in Django? There is UniqueConstraint, but it looks that it doesn't support nested fields, and I can't write: constraints = [ models.UniqueConstraint(fields=['class.classifier'], name='unique class per classifier') ] -
AttributeError: module 'django.db.models' has no attribute 'permalink'
@models.permalink AttributeError: module 'django.db.models' has no attribute 'permalink' please help me solve this it's a bit urgent -
Django - Update a value in database on another table
I have two tables class Payment(models.Model): payment_id = models.CharField(max_length=100) status = models.CharField(max_length=100) class Order(models.Model): payment = models.ForeignKey(Payment, on_delete=models.SET_NULL, blank=True, null=True) is_ordered = models.BooleanField(default=False) An incoming value (data) is coming from a webhook payment_confirmation(event.data.object.id) containing the payment_id. I want this value to be matched with Payment.payment_id (Payment table) and then update Order.is_ordered=True (Order table). How i can do that? I tried below with no success: Order.objects.filter(payment__payment_id=data).update(is_ordered=True) I can update Payment.status successfully by running: Payment.objects.filter(payment_id=data).update(status='COMPLETED') Thank you -
'list indices must be integers or slices, not dict' when using loop index
i always get this error. the statement which i commented out works. but i want to make a list of all elements of "categories", so i can choose later in the html which one to display. def home(request): response = requests.get('http://XXX.XX.XX.XXX:XXXX/api/categories/') categories = response.json() #return render(request, 'home.html', # { # 'id': categories[0]['id'], # 'name': categories[0]['name'], # 'colour': categories[0]['colour']} #) liste = [] for i in categories: liste.append({ 'id': categories[i]['id'], 'name': categories[i]['name'], 'colour': categories[i]['colour'] }) return render(request, 'home.html', liste) -
how to get an object after saving it to the database
i am trying to use django allauth to send confirmation emails on sign-up,after successfully sending the email i need top have a way to identify if the user has confirmed his email,dajngo allauth provides somthing for that from allauth.account.signals import email_confirmed @receiver(email_confirmed) def email_confirmed_(request, email_address, **kwargs): user = email_address.user user.email_verified = True user.save() what i can't figure out how to do is access the user.email_verified that i saved @api_view(['GET']) def current_user(request,user): current_user = request.user return Response({ 'id': current_user.id, 'verified': user.email_verified #??????? }) -
div inside another div is not taking 100% of its size. It is letting some equal space on the right and left
I want to make a responsive website and when I used columns and rows in bootstrap, I am having this problem where the inner div will not take the whole space in another div. The div inside div having class profile_left will leave a space on each side. Can you tell me what is wrong please? Here is my code snippet: div .profile_left{ border: 1px solid black; border-top-left-radius: 5px; border-top-right-radius: 5px; } div .profile_picture{ padding:20px; overflow: hidden; } <div class="container"> {% block content %} <div class="row"> <div class="profile_left col-lg-8 col-md-8 col-sm-8 col-xs-12" style="width: 30%;"> <div style="background-color: #01226c; text-align:center; padding:20px;"> <h3 style="color: white;"><strong>PROFILE</strong></h3> </div> <div style="background-color: white;"> <div class="profile_picture"> <figure> <img src="{{ student.profile_picture.url }}"> </figure> {% if student.profile_picture == 'default.png' %} <a href="">Add a picture</a> {% endif %} </div> </div> </div> </div> {% endblock content %} </div> -
Why am I getting this error when I run loaddata?
I am trying to run heroku python manage.py loaddata db.json but I keep getting this error UnicodeDecodeError: 'utf-8' codec can't decode byte 0x97 in position 2446: invalid start byte. What I did: python manage.py makemigrations locally git pushed to repo to update changes heroku python manage.py migrate heroku python manage.py loaddata db.json I keep getting this problem where I make changes to the database locally, the changes will not be reflected when I deploy on heroku. I added new rows locally, these rows do not get added to postgres when I deploy on heroku. No table or data on postgres when I deploy on heroku. I deployed the app through connecting to github. -
Inserting pandas dataframe into django model
I am having an issue writing a dataframe to my django models.py. The file is long, but is quite simple in its methodology: -import modules -create django database -requests.get necessary data -alter data some to fit my goals, save as df -connect to django db and insert df My models.py is the following: from django.db import models import requests import pandas as pd from datetime import timezone from datetime import datetime from datetime import date from datetime import timedelta import time from django.conf import settings from sqlalchemy.engine import create_engine class cryptoData(models.Model): coin = models.CharField(max_length=10) asset_id = models.SmallIntegerField() time = models.DateTimeField() close = models.FloatField() volume = models.BigIntegerField() market_cap = models.FloatField() reddit_posts = models.IntegerField() reddit_comments = models.IntegerField() tweets = models.IntegerField() tweet_favorites = models.IntegerField() social_volume = models.IntegerField() lunarcrush_key = 'fakekey1234' def top_coins(): lc_market = requests.get( url = 'https://api.lunarcrush.com/v2?data=market&', params = { 'key': lunarcrush_key, } ) all_coins = [] for entry in lc_market.json().get('data'): coin = [] coin.append(entry.get('s')) coin.append(entry.get('mc')) all_coins.append(coin) all_coins.sort(key = lambda x : x[1], reverse = True) top_ten_coins = all_coins[:10] return(top_ten_coins) top_coins_lst = top_coins() top_coin_names_lst = [x[0] for x in top_coins_lst] def get_coin_data(key, coin, date_diff, start_date, end_date): lc = requests.get( url = 'https://api.lunarcrush.com/v2?data=assets&', params = { 'key': lunarcrush_key, 'symbol': coin, 'interval': 'day', 'data_points': …