Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query spanning multiple relationships with indirection
My question is about querying objects spanning across multiple relationships, with a twist. I don't know how to translate what seems like a simple SQL query into its equivalent in Django. Here's a cut down version of my models (I removed the noise) : class Project(models.Model): title = models.CharField() assigned_users = models.ManyToManyField(User, through="ProjectAssignment") class CostProfile(models.Model): title = models.CharField() default_daily_rate = models.DecimalField() class CostRate(models.Model): project = models.ForeignKey(Project) profile = models.ForeignKey(CostProfile) daily_rate = models.DecimalField() class ProjectAssignment(models.Model): project = models.ForeignKey(Project) user = models.ForeignKey(User) cost_profile = models.ForeignKey(CostProfile) Users can be assigned to multiple Projects, with a given CostProfile as extra field of the many-to-many relationship. A Project also has multiple CostRates, that can override the default daily rate on a ProjectAssignment's CostProfile. I want to list all ProjectAssignments, with the referenced user, the cost profile, its default daily rate and finally the related cost rate if there is one for this project and cost profile. The difficulty is on the last bit : matching the related CostRate if there is one. The SQL query would be like this (sticky to IDs for project and user to keep it readable): SELECT gp.project_id, gp.user_id , cp.title, cp.default_daily_rate, gc.daily_rate FROM projectassignment gp LEFT OUTER JOIN costprofile cp … -
Django Multi-Tenancy
How can i create a tenant_superuser in the schema which is not public? raise SchemaError(tenants.tenant_users.tenants.models.SchemaError:Schema must be public for UserProfileManager user creation I tried ./manage.py create_tenant_superuser --username=admin --schema=customer1 but got Schemaerror -
Django testing views - getting error - DiscoverRunner.run_tests() takes 2 positional arguments but 3 were given
I use Django framework to create basic web application. I started to write tests for my views. I followed the django documentation and fixed some issues along the way. But now I am stuck - I don't know why I get this error even after 30 minutes of searching for answer. C:\Osobni\realityAuctionClient\venv\Scripts\python.exe "C:/Program Files/JetBrains/PyCharm 2022.3.3/plugins/python/helpers/pycharm/django_test_manage.py" test realityAuctionClientWeb.test_views.TestViews.test_start_view C:\Osobni\realityAuctionClient Testing started at 7:41 ... Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_manage.py", line 168, in <module> utility.execute() File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_manage.py", line 142, in execute _create_command().run_from_argv(self.argv) File "C:\Osobni\realityAuctionClient\venv\Lib\site-packages\django\core\management\commands\test.py", line 24, in run_from_argv super().run_from_argv(argv) File "C:\Osobni\realityAuctionClient\venv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Osobni\realityAuctionClient\venv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_manage.py", line 104, in handle failures = TestRunner(test_labels, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_runner.py", line 254, in run_tests return DjangoTeamcityTestRunner(**options).run_tests(test_labels, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\JetBrains\PyCharm 2022.3.3\plugins\python\helpers\pycharm\django_test_runner.py", line 156, in run_tests return super(DjangoTeamcityTestRunner, self).run_tests(test_labels, extra_tests, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: DiscoverRunner.run_tests() takes 2 positional arguments but 3 were given Process finished with exit code 1 Empty suite My tests.py looks like this: import django from django.test import TestCase from django.urls import reverse class TestViews(TestCase): def test_start_view(self): """ Test that the start view returns a 200 response and uses the … -
Django: how to add creator of model instance (custom user) in FK field by default?
My model, where I wanna add creator of instance in author field by default from django.db import models from users.models import CustomUser from django_ckeditor_5.fields import CKEditor5Field class News(models.Model): TYPE_CHOICES = ( ('N', 'Новость'), ('A', 'Статья'), ('R', 'Обзор'), ) title = models.CharField("Заголовок", max_length=128) text = CKEditor5Field('Текст', config_name='default') image = models.ImageField('Фото', blank=True, null=True) publication_date = models.DateTimeField("Дата публикации", auto_now_add=True) news_type = models.CharField(choices=TYPE_CHOICES, max_length=1) source = models.CharField("Ссылка на первоисточник", max_length=128) author = models.ForeignKey(CustomUser, models.CASCADE, verbose_name="Автор публикации") allowed = models.BooleanField("Разрешено к публикации") Custom user class CustomUser(AbstractUser): email = models.EmailField('адрес эл. почты', unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() tg_username = models.CharField(max_length=64, blank=True, null=True) name = models.CharField('имя пользователя', max_length=64, blank=True, null=True) update = models.DateTimeField(verbose_name='Дата обновления', auto_now=True) create = models.DateField(verbose_name='Дата создания', auto_now_add=True) def __str__(self): return self.email class Meta: ordering = ["create"] verbose_name_plural = 'Профиль пользователей' verbose_name = 'Профиль пользователя' I'm expecting something like that (it's just for example): author = models.ForeignKey(CustomUser, models.CASCADE, default=request.user, verbose_name="Автор публикации") -
Static files not loading using nginx, docker and django
I'm trying to load static files using nginx and gunicorn, it works when i go to http://0.0.0.0/static/css/base.css static hosted via nginx, but doesn't when i add django port http://0.0.0.0:8000/static/css/base.css static not found using django server these are the errors i get in my nginx container nginx_1 | 172.22.0.1 - - [04/Oct/2023:04:59:33 +0000] "GET /static/css/base.css HTTP/1.1" 304 0 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36" "-" nginx_1 | 2023/10/04 04:59:34 [error] 8#8: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 172.22.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "localhost", referrer: "http://localhost/static/css/base.css" nginx_1 | 172.22.0.1 - - [04/Oct/2023:04:59:34 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://localhost/static/css/base.css" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36" "-" This is all what I've tried, in conf.d i put container name as server_name and tried to add types to determine css files, but it didnt work settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' Dockerfile FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONBUFFERED=1 \ POETRY_VERSION=1.4.2 \ POETRY_VIRTUALENVS_CREATE="false" RUN pip install "poetry==$POETRY_VERSION" WORKDIR /education_platform COPY pyproject.toml poetry.lock docker-entrypoint.sh ./ RUN poetry install --no-interaction --no-ansi --no-dev COPY . /education_platform EXPOSE 8000 RUN chmod +x wait-for-it.sh docker-compose.yaml version: '3' services: db: image: … -
While trying to open Django web socket is showing Chat socket closed unexpectedly error
Channel layer is communicating with Redis but when I try to open websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), ] it shows not found and Chat socket closed unexpectedly error views -
Django App Not Reflecting the Changes in Files
I have a droplet on Digitalocean that runs Django. Whenever I make any changes on urls.py or views.py, I need to reboot the server in order to apply those changes in production. Is there any alternative method? Like if I delete the content of pycache directory, will it work? I tried touch commands but that didn't work. -
Can i add debit card details to billibg information details on heroku?
I have not credit card and i want to deploy a django app but requires payment method verification and this can done only done by credit card payment method on heroku so what i can do? I trie to add details of my debit card but not works. I think that this works because so many peoples having no any credit card then what those peoples do? -
Creating a test Django environment from the existing production Django project
I've developed a Django project which is in production and used by a small team daily. Now I want to make some changes in UI, since there is no test environment, I tried creating a similar base and home page with different names for testing in production environment but it is throwing error in ajax url resolving, I don't want to create another set of ajax url for testing. Is there any better way to create a test environment to test the UI changes and copy the html and java script alone? (it is a single developer project I use github only when I push any big change) -
increase the waiting time for response from server before returning the server time error with django and kubernetes
I am using Kubernetes and Google Cloud to host my web application and was looking for a way to increase the time for waiting for the server response before returning the error Internal server error Sorry, there seems to be an error. Please try again soon. I tried to search for the Kubernetes objects but no result thank you -
Django single choice field with choice of programming language category and quantity of possible answers
I would like to create a single choice quiz in Django. The question creator must: the possibility to add as many answers' fields as possible with a plus + or arrows up-down be capable of marking solely one answer as correct. be capable of choosing of predestined programming language category like here in text question. [![Singlequestion][1]][1] Here is my code: models.py # models.py from django.db import models class Category(models.Model): language_name = models.CharField(max_length=100, unique=True, default='') def __str__(self): return self.language_name class SingleChoiceQuestion(models.Model): question_text = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.question_text class SingleChoiceOption(models.Model): question = models.ForeignKey(SingleChoiceQuestion, on_delete=models.CASCADE) option_text = models.CharField(max_length=255) is_correct = models.BooleanField(default=False) def __str__(self): return self.option_text forms.py # forms.py from django import forms from .models import SingleChoiceQuestion, SingleChoiceOption class SingleChoiceQuestionForm(forms.ModelForm): class Meta: model = SingleChoiceQuestion fields = ['question_text', 'category'] options_count = forms.IntegerField(min_value=2, max_value=4, label="Number of Options Anzahl der Optionen") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) options_count = self.initial.get('options_count', 2) for i in range(options_count): self.fields[f'option_{i + 1}'] = forms.CharField(max_length=255, required=True) self.fields['correct_option'] = forms.ChoiceField( choices=[(f'option_{i + 1}', f'Option {i + 1}') for i in range(options_count)], widget=forms.RadioSelect, required=True, label="Correct Option Richtige Option" ) views.py # views.py from django.shortcuts import render, redirect from django.views import View from .forms import SingleChoiceQuestionForm class CreateSingleChoiceQuestionView(View): template_name … -
Dynamically creating models in django to be used in a unit test
I am attempting to create a test model in a unit test so that I can test associated behavior. Django documentation and related questions here on SO, both indicate that I should use the isolate_apps utility function, that in theory should register a temporary app which holds my test model. Note that I'm on django v1.11. My test looks like this: from django.test.utils import isolate_apps from django.db import models from django.test import TestCase class MyTest(TestCase): @isolate_apps("app_label") def test_the_model(self): class TestModel(models.Model): field = models.CharField(max_length=10) I'm not even running any assertions because it fails before. Error stack trace /usr/local/lib/python3.7/site-packages/django/test/utils.py:381: in inner with self as context: /usr/local/lib/python3.7/site-packages/django/test/utils.py:353: in __enter__ return self.enable() /usr/local/lib/python3.7/site-packages/django/test/utils.py:878: in enable apps = Apps(self.installed_apps) /usr/local/lib/python3.7/site-packages/django/apps/registry.py:56: in __init__ self.populate(installed_apps) /usr/local/lib/python3.7/site-packages/django/apps/registry.py:85: in populate app_config = AppConfig.create(entry) /usr/local/lib/python3.7/site-packages/django/apps/config.py:94: in create module = import_module(entry) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
from django.template import Template will this command into conda give me a folder inside my main one?
from django.template import Template in my class we are trying to create a folder inside our main folder, but I have no idea how to it. will from django.template import Template give a new folder inside my main one? btw, we are using VS code and Anaconda as the powershell. I am hoping someone can help me understand how to create a folder using django through conda -
Only default home page is working when deploying in PythonAnywhere
error message I deployed my Django webapp in PythonAnywhere. Despite following every step, my webapp is displaying only 1 page. As soon as i click on a link to go to other pages, the webapp stops working and gives an error message saying something went wrong with no proper details. But everything works fine when using it on localhost. These are the nav and urls.py files: nav.html: <div class="topbar"> <header> <li><a id="TOP_name" href="home"><img src="{%static 'prasant1.png' %}" height="50"></a></li> </header> <ul> <li><a id="right" href="contact">CONTACT</a></li> <li><a id="right" href="resume">RESUME</a></li> <li><a id="right" href="work">WORK</a></li> <li><a id="right" href="experience">EXPERIENCE</a></li> <li><a id="right" href="education">EDUCATION</a></li> </ul> </div> project/urls.py urlpatterns = [ path('', views.home), path('home', views.home), path('work', views.work), path('resume', views.Resume), path('education', views.education), path('contact',views.contact), path('experience',views.experience), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), ] I tried changing the "home" link with "work" link but that makes the condition worse as it doesn't even load 1 page now. So from my point of view the problem might be with other html files. Please help me out on how to solve this is PythonAnywhere. -
Update and save model data from a view function in Django
I am looking to create an automation strategy for data validation via the Django Admin. My Idea is to save transaction data in my Admin panel then later query the database for validation. I am still on my training wheels with Django, and any help will be much appreciated. the initial event will be triggered through to this JS function function save_this_data_to_models(event) { user_name = "user name"; data = "I need this data auto saved to my models in admin via this called view fucntion"; window.fetch(`/save_this_data_to_models?data=${data}&name=${user_name}`); event.preventDefault(); } the JS function calls and passes user data to this Python View function def save_this_data_to_models(request): # the data i need saved to my models data = request.GET.get('data', 'default') user_name = request.GET.get('name', 'default') print('') print('==========') print(user_name) print('==========') print('') print('=================================================================================') print(data) print('=================================================================================') print('') return HttpResponse(request) the prints are for my sanity. this is my modles.py file where i want to save this data automatically in my Admin site from django.db import models class Name(models.Model): # defining the fields i want to be saved to the database User_name = models.CharField(max_length=50) def __str__(self): return self.User_name class Data(models.Model): # defining the fields i want to be saved to the database Data = models.CharField(max_length=400) def __str__(self): return self.Data … -
Django - Unable to get a ClearableInputField to have the "multiple: True" to work
I am trying to allow my users to select multiple files when uploading file(s). I am trying to allow the field on the forms.py file to have this functionality with the "multiple" property. I have seen other examples found online, but it does not work for me. forms.py", line 168, in Meta "image": ClearableFileInput(attrs={"multiple": True}), File "/x/x/x/lib64/python3.6/site-packages/django/forms/widgets.py", line 393, in __init__ % self.__class__.__qualname__ ValueError: ClearableFileInput doesn't support uploading multiple files. pip list Package Version ----------------- ------- asgiref 3.4.1 Django 3.2.21 django-auth-ldap 4.0.0 django-filter 21.1 lxml 4.9.3 mysqlclient 2.1.1 Pillow 8.4.0 pip 21.3.1 pyasn1 0.5.0 pyasn1-modules 0.3.0 python-docx 0.8.11 python-ldap 3.4.3 pytz 2023.3 setuptools 39.2.0 sqlparse 0.4.4 typing_extensions 4.1.1 forms.py from django.forms import ModelForm, Textarea, Select, ClearableFileInput class UploadImageForm(ModelForm): class Meta: model = Images fields = [ "image", "description" ] labels = { "image": ("Image"), "description": ("Description") } widgets = { "image": ClearableFileInput(attrs={"multiple": True}), } models.py class Images(models.Model): id = models.BigAutoField(primary_key=True) image = models.ImageField(upload_to='images/', null=True) test_part_id = models.ForeignKey('TestParts', on_delete=models.PROTECT, blank=True, null=True) description = models.CharField(max_length=512, blank=True) class Meta: db_table = 'images' def __str__(self): return f"{self.image}" views.py def testing(request): if request.method == "POST" and "fileForm" in request.POST: imageForm = UploadImageForm(request.POST, request.FILES) if imageForm.is_valid(): for image in request.FILES.getlist('files'): new_image = Images(image=image) new_image.save() return redirect(fa_details, … -
Django Quiz- multiple question, saving to database failed, failed to convey programming language category field onto the screen
I neither can get the multi question form saved nor can I save the data in the database. The is one field for programming language category lacking. I would like to get the questions assigned to proper category like Python, JS, PHP etc. No Category field and no possibility to save in database. Here you can see the category field - it gets saved in the database Here is my code: #HTML {% extends 'dependencies.html' %} {% block content %} <div class="jumbotron container row"> <div class="col-md-6"> <h1>Add Question</h1> <div class="card card-body"> <form action="" method="POST"> {% csrf_token %} {{ form.question.label_tag }} {{ form.question }} <br> <label for="id_ans_count">Number of Answers Anzahl der Antworten:</label> {{ form.ans_count }} <br> <div id="answers-container"> {% for i in form.visible_fields %} {% if 'answer_' in i.name or 'is_correct_' in i.name %} {{ i.label_tag }} {{ i }} <br> {% endif %} {% endfor %} </div> <input type="submit" name="Submit"> </form> </div> </div> </div> <script> // JavaScript, um dynamisch Antworten hinzuzufügen const ansCountInput = document.getElementById("id_ans_count"); const answersContainer = document.getElementById("answers-container"); ansCountInput.addEventListener("change", function () { const ansCount = parseInt(this.value); answersContainer.innerHTML = ""; // Leeren Sie das Container-Div for (let i = 0; i < ansCount; i++) { const answerField = document.createElement("div"); answerField.innerHTML … -
Django Rest Framework- retrieving listing updating deleting
I have this class for create and update cuorse content How I convert or wite API view form this view class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super().dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({'form': form, 'object': self.obj}) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: # new content Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, 'object': self.obj}) I want wite API code using django restframework I build LMS using Django I backed and react in front-end The problem is how write API if I have hard code like this -
Django backend cannot access Cookies
Hey I'm trying to access my jwt token in my cookies to do authorization in my backend. But when trying to access my cookie from the request I receive an empty dict. The cookie is created like this in my frontend. cookies.set("jwttoken", result.data.token, { path: "/", maxAge: 3600}); this is done using the universal-cookie npm package. In my backend I try to access my cookies like this. jwt = request.COOKIES.get("jwttoken") But receive None when trying to print the token. This is everything CORS related in my settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_USE_SESSIONS = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", "https://********-*******.******.com", "https://www.******.com" ] Thanks for all the help -
Django - How to extend a template from within an app correctly
I am working on a Udemy class to get back into Django development, and this class has me doing the templates folder differently than I am used to. This is the current directory for my file structure showing where my templates are located: VS Code Directory Structure and extended template I can't embed yet, so this is the best I can do. Please ignore the ARCHIVES directory, that is just there while I test things out. I am trying to extend store.html off of base.html, but to test things, I am trying to extend from 'test.html' which you can see in the image. Historically, I have always added the templates directory to the top level, but this class has them on the app level. My problem here is that I can't get the store.html to show up. The test.html (base) is showing up fine, but I can't extend off of it and I have tried messing with the {% extends './test.html' %) as far as using 'store/test.html', 'test.html', and '../test.html'. I know this latter one goes back another directory level, but I just wanted to state that I have been trying to change where it looks. A few things: my … -
Virtual environment not activating in visual studio code windows 11
i am getting this error & : File C:\Users\mudit\vscode\python django projects\dev\venv\Scripts\Activate.ps1 cannot be loaded. The file C:\Users\mudit\vscode\python django projects\dev\venv\Scripts\Activate.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:3 & "c:/Users/mudit/vscode/python django projects/dev/venv/Scripts/Acti ... + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess check out this screenshot for better understanding. -
Is there a way to test if all my `reverse()` calls in Django Views resolve?
I use reverse('route_name') in my views for redirection. If I do any refactoring of the urls, be it renaming the routes, moving some routes to other urls.py file or something similar, I will have to update all the route names in all my views. It is very easy to miss some of the files. It seems trivial to simply grep all the reverse() calls from all the views and simply check if they resolve. The same thing with template files. It seems trivial to grep all the template names and check if they exist, or have they been moved or renamed and not updated in the views. I'm wondering if there is already some kind of package that does this. I've tried googling, but anything I search for focuses on writing specific tests. I'm wondering if there exists something that will help me avoid writing specific tests for each view. For example: Let's say I have a route: path('/payments/cart', CartView.as_view(), name='payments-cart') If I decide to move the url definition into the payments app, the new name will be cart and the reversing of the url in the view will be done as reverse('payments:cart'). If any of my views still reference … -
Accessing images using URL from a server with restrictions in React
I'm working on a web application using React for the front end and Django for the backend, where I need to display images from a server that has access restrictions in place. These restrictions prevent direct access to the images via a URL(tho I still can access it if I just paste the link into a browser), which is causing issues when trying to display them on my website. Here is an example of the image URL: 'https://mangatx.com/wp-content/uploads/2022/01/Level-1-Player-Manga-Online-193x278.jpg' I've tried using the standard <img> HTML tag to display these images, but I'm encountering a 403 error, indicating that I don't have permission to access the images directly. I have also used a Django templating engine to try to display an image, and it worked somehow, but when I switched to react, it didn't work. Is there a recommended approach or workaround for displaying these images in my web application, considering the server restrictions? I do not want to download the images before displaying them as it will go against the purpose of the application. I also don't want to use a proxy server, as my application has a lot of images and it will be too inefficient. Any ideas would … -
Pytest-django unexpected models test behaviour
I have my Django project with pytest and pytest-django package. I have test_models.py file with my test: import pytest from django.contrib.auth import get_user_model # # Get User model User = get_user_model() # Create your tests here. @pytest.mark.django_db def test_create_user(): assert User.objects.create() I use my custom User model with required fields username, email, password, first_name, last_name. But when I try to create User instance without these fields my tests are passing successfully. Why does my User model have such a behaviour? My models.py: from django.db import models from django.contrib.auth.models import AbstractUser from api.managers import CustomUserManager # Create your models here. # Abstract model TimeStampedModel class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: # abstract = True to enable models inherit from TimeStampedModel abstract = True # Custom User model class User(AbstractUser, TimeStampedModel): # Make these fields not to be null email = models.EmailField(unique=True, null=False, blank=False) first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) # Assing base user manager for admin panel objects = CustomUserManager() I expect that test gives me the error that I can't create a User instance. I've tried to import directly User model from api.models. -
Static files are not loading in Django project in replit
I am working on a project using Python-Django in repl.it. When I set DEBUG=True in settings.py, the static files are loading fine but when DEBUG is set to False (DEBUG=False), the static files are not loading and getting 404 error on the console. Please help me in fixing it. I am assuming there should be a place where we need to define static location like we do in nginx config file as follows location /static/ { alias /var/www/example.com/current/static/; gzip_static on; expires max; add_header Cache-Control public; } Here is my settings.py file: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 3.2.13. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os # 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 = os.getenv('SECRET_KEY') if SECRET_KEY is None: print( "Please setup a SECRET_KEY in the Secrets (Environment variables) tab. See README.md for more." ) exit(1) # SECURITY WARNING: don't run with debug turned on in …