Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF nested serializer has validation over fields instead of ID
I have a PermissionSerializer and GroupSerializer, when I request to get data it works fine, but when I want to add a new group, it expects to receive all fields of PermissionSerializer while for the model it only needs ID. class PermissionSerializer(serializers.HyperlinkedModelSerializer): """Permission serializer.""" url = serializers.HyperlinkedIdentityField(view_name="account:permission-detail") content_type = ContentTypeSerializer(many=False, read_only=True) class Meta: model = Permission read_only_fields = ( "url", "id", "name", "content_type", "codename", ) fields = ( "url", "id", "name", "content_type", "codename", ) class GroupSerializer(serializers.HyperlinkedModelSerializer): """Group serializer.""" url = serializers.HyperlinkedIdentityField(view_name="account:group-detail") permissions = PermissionSerializer(many=True) class Meta: model = Group fields = ( "url", "name", "permissions", ) When I enable the read_only=True, it completely ignores the permissions field validation while I really need it to be validated as well. Sample request which I expected to work fine: { "name": "editors", "permissions": [ {"id": 8} ] } or { "name": "editors", "permissions": [8] } But I really have no clue how to fix it. If I change the PermissionSerializer, then my output will be changed which it shouldn't, and if I want to keep it as what it is now, then I have to feed it by all permissions fields: { "name": "editors", "permissions": [{ "name": "something", "url": "something", "content_type": "something", "codename": … -
setattr doesn't save the values of my class in Python script
I´ve working on a project that must save in a database the values provided by a json. The setattr function is not working when i try to save the values of each json concept in the database. I think that i have provided the function attributes correctly. This is my models.py: class Balance_sheet(models.Model): company_name = models.CharField(max_length=140) year = models.CharField(max_length=140) quarter = models.CharField(max_length=140) CashAndCashEquivalentsAtCarryingValue = models.IntegerField(null=True, blank=True) ... #Extra fields class Meta: ordering = ['year'] verbose_name = "Balance Sheet" verbose_name_plural = "Balance Sheets" def get_attribute_by_name(self, field): if hasattr(self,field): return getattr(self,field) else: return '' def set_attribute_by_name(self, field, value): if hasattr(self, field): return setattr(self, field, value) else: return '' def __str__(self): return "%s %s" % (self.company_name, self.year) This is my script.py: from types import SimpleNamespace from typing import AsyncGenerator from django.core.management.base import BaseCommand, CommandError from database.models import Balance_sheet class Command(BaseCommand): def handle(self, *args, **options): data = open('database/static/data/data-q1.json') jsonObjectQ1 = json.load(data) json_prettyQ1 = json.dumps(jsonObjectQ1, sort_keys=True, indent=4) data.close() x = json.loads(json_prettyQ1, object_hook=lambda d: SimpleNamespace(**d)) print(x.startDate, x.companyName, x.companyCIK) print(x.year) # Creating Objects balance_sheet = Balance_sheet.objects.create(company_name=x.companyName, year=x.year, quarter=x.quarter) for data in x.data.bs: concept = data.concept value = data.value fields = Balance_sheet._meta.get_fields() for field in fields: if concept == field.name: model_name = field.name setattr(balance_sheet, model_name, value) balance_sheet.save I … -
expand model in backend
I have the following serializer class OrdenTrabajoserializer(BaseSerializer): class Meta: model = Orden_trabajo fields = '__all__' expandable_fields = { 'vehiculo': (Vehiculoserializer, { 'many': False }), 'asesor': (Tecnicoserializer, { 'many': False }), 'servicio_orden_registro': (Orden_registroserializer2, { 'many': True }) } when I make a request from the frontend and I want an expanded field I execute the endpoint and it correctly brings me the expanded object unexpanded {{url...}}/ response: { orden: 1, . . . vehiculo: 32 } expanded {{url...}}/?expand=vehiculo/ response: { orden: 1, . . . vehiculo: { id: 32, color: 'blue', ...data } } the problem is that I want to do the same but directly in the backend this is the viewset, according to the information I have searched it tells me that I should put 'permit_list_expands' but I don't know what to do to be able to use that and expand it ... class facturarOrdenV2viewSet(generics.ListAPIView): queryset = Orden_trabajo.objects.all() serializer_class = OrdenTrabajoserializer permit_list_expands = ['vehiculo', 'asesor', 'servicio_orden_registro'] def post(self, request, *args, **kwargs): orden = self.kwargs.get('orden', None) ordenTrabajo = self.queryset.get(pk = orden) dict_obj = model_to_dict(ordenTrabajo) print(dict_obj) return Response({'OK'}) -
Django webpage giving 404 error when I write the code to give video forward option
I am using django to make a website that shows some movies for me to watch when I am not at home. The code was working well, with the website showing the movie, letting me play it and everything that I wanted, except that i can't go forward and back in the movie. I spent a lot of time trying to solve that problem and I found some videos that explained how to make that work. But, when I write the code, django works normally, but if I try to access the website it shows me a 404 error, just saying "404 Not Found", without the usual 404 error page that django have. The code that is making all of this is application = Ranges(Cling(MediaCling(get_wsgi_application()))) in the wsgi.py file. Everything works fine until I add the MediaCling part. I have installed the libraries and writed the code equal to the videos that I watch. What I am doing wrong? import os from django.core.wsgi import get_wsgi_application from dj_static import Cling, MediaCling from static_ranges import Ranges os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Movies_site.settings') application = Ranges(Cling(MediaCling(get_wsgi_application()))) -
Using Django Allauth credentials instead of Google's flow
I'm trying to start a video stream on Youtube using Django but it seems my credentials are not working properly. To create the stream I use just the resource__owner_secret as a credential when starting the stream. Here is the view.py from django.shortcuts import render #import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors from allauth.socialaccount.models import SocialAccount, SocialApp scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"] api_service_name = "youtube" api_version = "v3" #client_secrets_file = "app/client_secret.json" def index(request): if request.method == 'PUT': google_app = SocialApp.objects.get(provider='google') user_account = SocialAccount.objects.get(user=request.user) client_key = google_app.client_id user_token = user_account.socialtoken_set.first() resource_owner_key = user_token.token resource_owner_secret = user_token.token_secret #flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes) # credentials = flow.run_console() credentials = resource_owner_secret print(credentials) youtube = googleapiclient.discovery.build( api_service_name, api_version, credentials=credentials) request = youtube.liveStreams().insert( part="snippet,cdn,contentDetails,status", body={ "cdn": { "frameRate": "60fps", "ingestionType": "rtmp", "resolution": "1080p" }, "contentDetails": { "isReusable": True }, "snippet": { "title": "Your new video stream's name", "description": "A description of your video stream. This field is optional." } }, onBehalfOfContentOwnerChannel="<MY_CHANNEL_ID>" ) request.execute() return render(request, 'index.html') Any idea why starting the live stream isn't working? -
How Do I Pervent Django Default Ordering
I have two models, Exercise and Workout. When I add my list of exercise to the workout table, they are added in alphabetical order. I do not want that. I use ajax to send a list of exercise_id, in the order I want, then in my views.py, I get the exercise by id, and add it to my workout. I want to keep the order I add the exercises. How do I do that? below are my code snippets. BODYPART_CHOICES = ( ('Abs', 'Abs'), ('Ankle', 'Ankle'), ('Back', 'Back'), ('Biceps', 'Biceps'), ('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'), ('Forearms', 'Forearms'), ('Full Body', 'Full Body'), ('Hip', 'Hip'), ('Knee', 'Knee'), ('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'), ('Neck', 'Neck'), ('Shoulders', 'Shoulders'), ('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'), ('Wrist', 'Wrist'), ) CATEGORY_CHOICES = ( ('Cardio', 'Cardio'), ('Stability', 'Stability'), ('Flexibility', 'Flexibility'), ('Hotel', 'Hotel'), ('Pilates', 'Pilates'), ('Power', 'Power'), ('Strength', 'Strength'), ('Yoga', 'Yoga'), ('Goals & More', 'Goals & More'), ('Activities', 'Activities'), ('Rehabilitation', 'Rehabilitation'), ('Myofascial', 'Myofascial') ) EQUIPMENT_CHOICES = ( ('Airex', 'Airex'), ('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'BattleRope'), ('Bodyweight', 'Bodyweight'),('Bands', 'Bands'), ('Cables', 'Cables'), ('Cones', 'Cones'), ('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'), ('Foam Roller', 'Foam Roller'), ('Kettlebells', 'Kettlebells'), ('Leg Weights', 'Leg Weights'), ('Machine', 'Machine'), ('Medicine Ball', 'Medicine Ball'), ('Plate', 'Plate'), … -
Don’t forget to enter notes” - If they have not enter note by today and enter note the prior day
I have two tables Member table and Daily_Notes table. class Member(models.Model): name = models.Charfield() Daily_notes table class DailyNotes(models.Model): member= models.Foreignkey('Member') note=models.Charfield() date=models.Datetimefield(default="") Daily note table contains daily entries I need to filter datas, If user have not enter note by today and entered the prior day. -
Django-Compressor not working with CDN due to location of cache
I am trying to use django-compressor in my system, but I cannot seem to get it to work by compressing the files locally from a remote CDN. How can I accomplish this? I use a digital ocean CDN for my static files and I would like to have compressor complete the 'compression' in the request cycle using simple code like I have below: {% compress css %} <link rel="stylesheet" href="{% static 'css/root_variables.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/forms.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/animations.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/animate.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/button.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/datepicker.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/strikeout.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/main.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/scrollbar.css' %}?v={{ version }}"/> <link rel="stylesheet" href="{% static 'css/navigation.css' %}?v={{ version }}"/> {% endcompress %} The problem is that my STATIC_URL in production would be through a CDN and I cannot seem to set COMPRESS_URL for django-compressor to a local location, how can I do this? For example my static url: STATIC_URL = f'https://{AWS_DEFAULT_BUCKET}.{AWS_S3_REGION_NAME}.digitaloceanspaces.com/static/' When I attempt to add these settings it fails because it … -
Django Djoser user activation by an admin
It is there a way to override typical djoser account activation flow? After creating an account, I would like to send activation link with uid and token to the admin and email to user eg.: "Your account will be accepted by admin withinn 48hrs or sth like that. I would create a view with admin permissions for auth/request_activation/{uid}/{token} to handle all those requests. -
Django 'time__contains' is not working in particular case
I'm trying to compare time pasted to form with time saved in DB for deleting this record. I don't understand why it's not working when in DB is stored 8:15:00 and the user pasted 08:15. The field in DB is TimeField and for comparing I'm using .filter(time__contains=t) where t is string pasted from form. Only difference is in zero before 8. When in DB is it stored like 08:15:00, all is working. class WateringSchedule(models.Model): time = models.TimeField() t = '08:15' print(WateringSchedule.objects.filter(time__contains=t).count()) Thanks. -
Django - Verify uploaded file size before uploading
In Django I have a view for uploading a file. I want to limit the possible file size to 0.5MB. This is how I do it today: class FileUploadView(BaseViewSet): parser_classes = (MultiPartParser, FormParser) serializer_class = FileUploadSerializer def create(self, request, *args, **kwargs): file_serializer = self.get_serializer(data=request.data) file_serializer.is_valid(raise_exception=True) file_ = file_serializer.validated_data['file'] class FileUploadSerializer(serializers.ModelSerializer): file = MyFileField() MAX_UPLOAD_SIZE = 500000 # max upload size in bytes. 500000 = 0.5MB def validate_file(self, received_file): if received_file.file.size > self.MAX_UPLOAD_SIZE: raise BadRequestException( message='File size is bigger than 0.5MB', error_type=ExceptionTypeEnum.IMPORT_FILE_SIZE_TOO_BIG ) It works. My problem is that the file must first be uploaded to the server before evaluating the size. I checked for other possible options. I can use DATA_UPLOAD_MAX_MEMORY_SIZE (which currently has the default value of 2.5MB) but I don't want to change it to 0.5MB for all the requests. I guess that I may use the 'content-length' header, but seems like it's only after uploading as well. I was wondering if there's a way to reject large files before actually uploading them (In Backend). -
Django return item and list of all matches in second table
I am writing a Django application that uses Angular for the front end. I am responsible for the backend. I have all the basic crud operations functioning. To give some context to my question I have a league model and a league seasons model. League | league_id | league_name | league_admin | |:--------- |:----------- |:------------ | |1|A|Sam| |2|B|Matt| League_Season | league_season_id | league | year | current_season | |:---------------- |:------ |:---- |:-------------- | |1|1|2019|False| |2|1|2020|False| |3|1|2021|True| |4|2|2019|False| |5|2|2020|False| |6|2|2021|True| What I am trying to do is create an API that will return the leagues as well as a list of their seasons. For example but this would return all the leagues. I will figure out how to modify to only do it for a specific league supplied by the user later. { "league_id":1, "league_name":"A", "league_admin":"Sam", "seasons": [{"league_season_id":1, "league":1, "year":2019,"current_season":false}, {"league_season_id":2, "league":1, "year":2020,"current_season":false}, {"league_season_id":3, "league":1, "year":2021,"current_season":true} ] } -
How to keep a consistent display of images in django gridview when user upload more pictures, than the condition passed to forloop
Okay i have been trying to find way to have a consistent display of images in a three column gridview in django, the issue is when ever a user upload 6 pictures in to the grid html view, it display normal, but when the picture are less than 6 or more than 6 the display becomes messy in the grid and the images looks disorganized in the grid display. How best can i write my forloop so that it would always have a consistent display regardless of the number of images posted to the html grid. Here is what i have done so far ,which when i upload 6 picture the gridview looks normal but when i add more pictures or less , it mess-up the appearance of the grid. <div class="grid grid-cols-2 gap-2 p-2"> {% for p in photos %} {% if forloop.counter == 1 %} <a href="{{ p.pic.url }}" class="col-span-2"> <img src=" {{ p.pic.url }} " alt="" class="rounded-md w-full lg:h-44 object-cover" > </a> {% endif %} {% if forloop.counter == 5 %} <a href="{{ p.pic.url }}"> <img src="{{ p.pic.url }} " alt="" class="rounded-md w-full h-full"> </a> {% endif %} {% if forloop.counter == 6 %} <a href="" class="relative"> … -
If possible, what is the best way to migrate CharField to PositiveIntegerField for a table with >150m rows. I am using django + postgres
We have a table with >150m rows, in that 1 field had to be PositiveIntegerField. I assigned it CharFeild and saw it too late. Is it possible to convert those values to integer values? I know we could typecast them when needed, but for our usecase we would like to have the values available as integers in the database itself. -
How best integrate mkdocs-material static built docs page in a Django 3.0+ project?
I know I could have all my mkdocs-material static docs page outside my Django project by just referencing in whatever templates I have. However, If I want a nicely packed Django project WITH nicely built documentation in it using mkdocs-material, what is the best way to approach this integration? So far all I could think about it is to build my docs page first, bring it into my Django project and then tag it according to DTL, wherever necessary, but that seem rather laborious. Since jinja2 is already in both Django e MkDocs, I've got the feeling there must be a better way (a pythonic way) to integrate both. Have anyone else worked on this matter before? How did you go about it? -
Nginx, django, docker, refuses connection over localhost
Following best practices, boiler plates and SO posts, after several days, I'd like to find out what is haunting my dockerized Django, Postgres, Gunicorn, Nginx project. After having chopping up the components, testing it for bit, I can see introduction of Nginx is the problem but seems to lack enough understanding to see the problem. It's probably something very simple, so please be kind as I genuinely have tried to solve it. I will present details in that regards below. Why cannot I get anything in my browser, except logs that says: /etc/nginx/html/index.html" is not found nginx | 2021/10/27 14:03:18 [error] 22#22: *1 "/etc/nginx/html/index.html" is not found (2: No such file or directory), client: 172.21.0.1, server: localhost, request: "GET / HTTP/1.1", host: "0.0.0.0:8000" nginx | 172.21.0.1 - - [27/Oct/2021:14:03:18 +0000] "GET / HTTP/1.1" 404 555 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36" "-" docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ea9da69663eb nn_nginx "/docker-entrypoint.…" 4 minutes ago Up 4 minutes 0.0.0.0:8000->80/tcp, :::8000->80/tcp nginx fcc396bd0e56 nn_django_app "/usr/src/app/entryp…" 7 minutes ago Up 4 minutes 8000/tcp django_app 2653621d29ff postgres:14.0-alpine "docker-entrypoint.s…" 7 minutes ago Up 4 minutes 5432/tcp db1 docker-compose version: "3.8" services: # Database containers db1: container_name: … -
uWSGI thread has existing running event loop which causes Django's SynchronousOnlyOperation exception
I have two Django views, def view_that_accesses_orm(request): # say end point /useorm user = User.objects.first() ... and def view_that_creates_event_loop(request): # say endpoint /createloop client = AsycProvider() ... # do stuff with client and AsyncProvider is something like class AsyncProvider: def __init__(self): self.__loop = asyncio.get_event_loop() self.__session = aiohttp.ClientSession(loop=self.__loop) ... # other operations with asyncio.run_until_complete, asyncio.gather, and self.__session Now the issue is that say if I have 1 process in uWSGI and 2 threads. Then they will be in a round robin fashion serving requests. So scenario is: User hits /createloop (given thread 1) User hits /useorm (given thread 2) User again hits /useorm (given thread 1) Now in third scenario, sometimes the event loop is running and since Django 3.x detects a running event loop and disallows us to access ORM, I get the django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. exception. I am not sure how the event loop doesn't stop and persist in the thread. Please explain what exactly could be the cause of this and what should be the fix? -
Issue outputting HTML to Django admin
I have these models: class Academic(models.Model): surname = models.CharField(max_length=100, blank=True) forename = models.CharField(max_length=100, blank=True) def __str__(self): return '{}, {}'.format(self.surname, self.forename) class Partner(models.Model): name = models.CharField(max_length=200, verbose_name="Organisation name") class ResearchActivity(models.Model): title = models.CharField(max_length=200) academic = models.ManyToManyField(Academic, blank=True) partner = models.ManyToManyField(Partner, blank=True) I want to output the academics linked to a partner via the ResearchActivity model. I have this decorator in my admin.py: @admin.register(Partner) class PartnerAdmin(admin.ModelAdmin): readonly_fields = ('get_academic_links',) @admin.display(description='Academic link(s)') def get_academic_links(self, obj): for ac in ResearchActivity.objects.filter(partner=obj.id).values_list('academic', flat=True).distinct(): return mark_safe('<a href={}>' + ac.surname + '</a>', ac) It sort of works. If I return only ac then I get the ID of that academic. I would expect to get the 'name, surname', as per def __str__(self): decorator. More importantly, if I try to construct an hyperlink (see code above) the admin outputs a '-' and nothing else. What am I missing? -
How to resize django ckeditor according to the window size?
I am going to add a Django CKEditor to my form but it is not resized when I resize my window size. Please help me to fix it. models.py from ckeditor.fields import RichTextField Body = RichTextField() forms.py widgets = { 'created_date': forms.DateTimeInput(attrs={ 'class':'form-control', 'readonly':'True', }) , 'Title' : forms.TextInput(attrs={ 'class':'form-control' }), 'Body': forms.Textarea(attrs={ 'class':'form-control django-ckeditor-widget ckeditor', 'id':'form-control', 'spellcheck':'False'}), } settings.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': [ ['Undo', 'Redo', '-', 'Bold', 'Italic', 'Underline', '-', 'Link', 'Unlink', 'Anchor', '-', 'Format', '-', 'Maximize', ], ], 'toolbarCanCollapse': True, }, } template.html {{ form.media }} {{form.as_p}} -
How to get unique values in quereyset?
I have following record in messages table and I want to get all the receiver where the sender is 15 and all the sender where the reciever is 15. so I used the querey class ContactListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): return Messages.objects.filter(Q(sender=15) | Q(receiver=15)) serializer_class = ContactsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) but it returns duplicates results also as following. How can I get only the distinct/unique records. For example {sender: 15, receiver: 11} should never repeats I also tried Messages.objects.filter(sender=15).values_list('receiver', flat=True).union( Messages.objects.filter(receiver=15).values_list('sender', flat=True) ) but this is returning empty array -
Django broken pipe with CORS_ORIGIN_ALLOW_ALL
Hi I am making flutter app with Django API Because of CORS, I am changing django settings. settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)4%#q5&d3^5=0!bauz62wxmc9csk*_c09k!jl2g1a-0rxsa--j' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crawling_data', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'crawler.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'crawler.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, … -
prablem django install and cmd?
I entered the following code in cmd and line 5 has an error I also tried these codes but did not get the desired result (py -m venv env) please help me!!! C:\Users\baran>python C:\Users\baran>pip C:\Users\baran>pip install virtualenv C:\Users\baran>pip install virtualenvwrapper E:\learning\project\django pro\toplrean>virtualenv -p python env 'virtualenv' is not recognized as an internal or external command, operable program or batch file. -
form.cleaned_data in django is empty
How can I debug the form.cleaned_data giving me None as a return? I am not sure which part of code should I share, but here is a snippet where I am validating the form and checking for cleaned data: if form.is_valid(): form.save() print(form.cleaned_data) Output: {'City': None, 'Country': None, 'Zip Code': None, 'ID': '43434'} -
What is the difference between "boards" and "boards.apps.BoardsConfig" in Django?
What is the difference between "boards" and "boards.apps.BoardsConfig" in Django ? -
django multiple databases django.db.utils.OperationalError: no such table: django_content_type
I'm trying to store my celery tasks tables in tasks database witch has nothing related with any other tables but i keep getting this error. sqlite3.OperationalError: no such table: django_content_type i'd rather to not having extra tables which i don't use in celery tasks like users or my other models so i made two abstract models for my databases: class TaskModel(models.Model): class Meta: abstract = True _db = 'tasks' class CeleryTasks(TaskModel): ... class DefaultModel(models.Model): class Meta: abstract = True _db = 'default' class MyDefaultDatabaseModel(DefaultModel): ... and my database router looks like : class DatabaseRouter: tasks_models = ['CeleryTasks'] def db_for_read(self, model, **hints): """ reading model based on params """ if not hasattr(model, 'Meta'): return None return getattr(model.Meta, '_db', None) def db_for_write(self, model, **hints): """ writing model based on params """ if not hasattr(model, 'Meta'): return None return getattr(model.Meta, '_db', None) def allow_relation(self, obj1, obj2, **hints): if hasattr(obj1._meta, '_db') and hasattr(obj2._meta, '_db'): return obj1._meta._db == obj2._meta._db return None def allow_migrate(self, db, app_label, model_name=None, **hints): print( f'allow migration database router invoked with args db={db},app_label={app_label},model_name={model_name},hints={hints}') if db == 'tasks': if model_name in self.tasks_models: print('returning True') return True print('returning False') return False print('returning None') return None and my full error logs may help: allow migration …