Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SMTP ERROR using Django in Railway Production
I am getting error while trying the same end point locally so it's working properly fine but in production it dosen't work and always throwing this error. The code of my settings.py file is as EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # or False depending on your setup EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') I am using my gmail (codingwithhasnin@gmail.com) and the password which I got from gmail app password which works fine locally and also on AWS EC2 instance but not in railway production. What can be the issue? -
Included App URLs not showing in DRF browsable API
I'm using the Django Rest Framework to provide an API, which works great. All needed URLs for routers and others too are hold in the root urls.py To better handle the growing number of routes I tried to move routes from Apps to their related app folders - as one would do with pure Django. # urls.py from django.contrib import admin from django.urls import include, path from rest_framework.routers import DefaultRouter import core.views router = DefaultRouter() router.register(r'core/settings', core.views.SettingsViewSet, basename='settings') router.register(r'core/organization', core.views.OrgViewSet, basename='org') urlpatterns = [ path('api/', include(router.urls)), path('api/een/', include('een.urls')), path('admin/', admin.site.urls), path('', include('rest_framework.urls', namespace='rest_framework')), path('api/tokenauth/', authviews.obtain_auth_token), ] # een/urls.py from django.urls import path, include from rest_framework import routers from . import views app_name = 'een' router = routers.DefaultRouter() router.register( r'cvs', views.EENSettingsViewSet, basename='een-cvs', ) urlpatterns = [ path('', include(router.urls)), ] Everything shown here is working as expected, but the included URLs are not shown in the browsable API. They are reachable and working, but they are not listed. I do use drf-spectacular, which correctly picks up even the included app urls. I've tried several different combinations, different url order, etc - with no luck. What do I overlook? Or is this a general thing with DRF and I should really keep everything … -
How to architect the external evnets and Django models?
I'm building a django backend app and I have a few different models in my app. One of these models is a Driver and I want to do the following when calling the create-driver endpoint: create the driver in database create a user account for the driver in my B2C directory send an email to the driver on successfull creation send a notification to admins on succesfull creation Operation 1 and 2 should either be succesfull or fail together (an atomic transaction). I was initially handling 1 and 2 in the Driver model's save method like this: Class Driver(models.Model): ... def save(self, *args, **kwargs): if self.pk is None: # Creating a new driver if self.b2c_id is None: graph_client = MicrosoftGraph() try: with transaction.atomic(): user_info = B2CUserInfoSchema( display_name=f"{self.first_name} {self.last_name}", first_name=self.first_name, last_name=self.last_name, email=self.email, phone_number=self.phone, custom_attributes={ "Role": UserRole.DRIVER.value, }, ) res = graph_client.create_user(user_info) # create B2C user self.b2c_id = res.id super().save(*args, **kwargs) # create driver in database except Exception as e: raise e else: # Updating an existing driver super().save(*args, **kwargs)``` This was working perfectly fine but I didn't like mixing responsibilites here and adding the B2C user creation logic to my Driver's save method. I like to keep the save method simple … -
Django with MSSQL Server – GUID Type is maped as char(32) not uniqueidentifier
I would like an app that can easily use different databases. Currently, I’m using SQLite and MSSQL, switching between them via a config file. I noticed that the following field could be quite important from a performance standpoint: user_guid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, null=False, blank=False, db_index=True ) In MSSQL, the field is mapped as char(32), and I have mixed feelings about that. Over time, I might switch to PostgreSQL, but as I mentioned before, I’m not entirely comfortable using char(32) instead of uniqueidentifier. -
Celery chord, execute code after callback
I am working on a Django application that uses celery tasks for complex and time intensive calculations. I have a task in which subtasks are used to process a large number of combinations of values and determine the best combination based on predefined parameters. The subtasks are created like this: combinations = itertools.product(*bm) # setup for multicore processing using celery tasks static_args = (nt, mp, f, levels) chunk_size = 10000 tasks = _chunked(combinations, chunk_size) chunk_tasks = group(evaluate_combination_chunk.s(list(chunk), static_args) for chunk in tasks) final_task = compare_chunk_results.s() best_result = chord(chunk_tasks)(final_task) # do some stuff with this result return best_result the subtask methods like this: def evaluate_combination_chunk(chunk, static_args): # evaluate a chunk of combinations best_result = None highest_power = -1 for comb in chunk: result = evaluate_combination(comb, *static_args) if result[0] and result[1] > highest_power: best_result = result highest_power = result[1] return best_result and def compare_chunk_results(results): best_result = None highest_power = -1 for result in results: if result: if result[1] > highest_power: best_result = result highest_power = result[1] return best_result both marked with @shared_task(). so i am finding the best result in each chunk (that works just fine based on what i see in the console) and then compare those to find the best … -
Django Serializer - `methodViewSet(viewsets.ViewSet)` is not displayed in url list
I am trying to combine multiple serializers into a single API call, and as a result, I am using viewsets.ViewSet. I am aware that viewsets.ModelViewSet automatically generates the routes, but with viewsets.ViewSet, I am not seeing the expected route for my API. When I switch to viewsets.ModelViewSet, the route becomes available. This makes me think my issue is specific to how viewsets.ViewSet handles routing. According to the documentation (https://www.django-rest-framework.org/api-guide/viewsets/), I should be able to register the URL like I would with ModelViewSet. However, the route doesn't appear when using viewsets.ViewSet. Any suggestions on what might be going wrong? views.py class MethodViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] @action(detail=False, methods=['get'], url_path='method-path') def list(self, request): ... urls.py from rest_framework.routers import DefaultRouter from .views import ( MethodViewSet, ) from rest_framework.authtoken.views import obtain_auth_token router = DefaultRouter() ... router.register(r'method-path', MethodViewSet, basename='methodbasename') -
Twilio Return gathering after client press star
I'm trying to create a fallback gathering if the interpreter hangup from the conference while the client is still on the line, I have to return the gathering to the client to ask him if he wants another interpreter or disconnect everything work perfect but, when the client pressed star, the gather said the first part of the word only, and then the call disconnected def handle_incoming_call(self, call_sid, from_number, language_code): try: with transaction.atomic(): next_interpreter = CallSelector.get_next_interpreter(language_code) conference_name = f"conferenceـ{call_sid}" conference = CallSelector.create_conference( language=next_interpreter.language, interpreter=next_interpreter.interpreter, conference_name=conference_name, ) response = VoiceResponse() response.say("Please wait while we connect you with an interpreter") dial = Dial( hangup_on_star=True, action=f"{settings.BASE_URL}/api/calls/webhook/interpreter_leave/{conference.conference_id}/", timeout=30, ) dial.conference( conference_name, start_conference_on_enter=True, end_conference_on_exit=False, # record=True, # recording_status_callback=f"{settings.BASE_URL}/api/calls/webhook/recording/{conference.conference_id}/", status_callback=f"{settings.BASE_URL}/api/calls/webhook/conference-status/{conference.conference_id}/", status_callback_event="start end join leave announcement", status_callback_method="POST", beep=True, participant_label="client", ) response.append(dial) self._add_client_to_conference(conference, from_number, call_sid), self._call_interpreter(conference, next_interpreter.interpreter), return response except Exception as e: logger.error(f"Call handling failed: {str(e)}", exc_info=True) return self._generate_no_interpreter_twiml() And here is the callback interpreter_leave def handel_interpreter_leave(self, conference_id: str): try: print("Interpreter leave handling started") conference = CallSelector.get_conference_by_conference_id(conference_id) response = VoiceResponse() gather = Gather( num_digits=1, action=f"{settings.BASE_URL}/api/calls/webhook/client_choice/{conference_id}/", method="POST", timeout=10, input="dtmf", ) gather.say("Press 1 to connect with a new interpreter, or press 2 to end the call.") response.append(gather) return response except Exception as e: logger.error(f"Interpreter leave handling failed: {str(e)}", exc_info=True) … -
Show Data of Customer and License from database according to the click on dropdown list of financial year
dropdown financial year show data from database as per the financial year in all pages enter image description here dropdown that i created def get_financial_year(date): year = date.year if date.month < 4: # before April, in the previous financial year year -= 1 return f'{year}-{year + 1}' financial_years = {} for license in licenses: financial_year = get_financial_year(license.Subscription_End_Date) if financial_year not in financial_years: financial_years[financial_year] = 0 financial_years[financial_year] += 1 print(financial_years.keys()) financial_years_list = sorted(financial_years) how show data -
SMTP Error in Django on Production using Railway
I am getting error while trying the same end point locally so it's working properly fine but in production it dosen't work and always throwing this error. The code of my settings.py file is as EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True # or False depending on your setup EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') -
Django view is rendering 404 page instead of given html template
I'm working on a wiki project with django. I'm trying to render 'add.html' with the view add, but it sends me to 404 instead. All the other views are working fine. How should I fix add? views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django import forms import re from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def detail(request, entry): #if search based on title returns result if util.get_entry(entry): content = util.get_entry(entry) return render(request, "encyclopedia/details.html", { "title": entry, "content": content }) else: return render(request, "encyclopedia/404.html", { 'entry': entry }) def add(request): return render(request, "encyclopedia/add.html") urls.py: from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:entry>/", views.detail, name="entry"), path("add/", views.add, name="add"), ] -
How fix redirect after registration? Django
today I faced such a problem that after registration the form does not go anywhere. The catch is that the form does not send a request to the database, but I can create a user through the Django admin panel. views.py def registration(request): if request.method == 'POST': form = UserRegistrationForm(data=request.POST) if form.is_valid(): form.save() user = form.instance auth.login(request, user) messages.success( request, f'{user.username}, Successful Registration' ) return HttpResponseRedirect(reverse('user:login')) else: form = UserRegistrationForm() return render(request, 'users/registration.html') forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm, \ UserCreationForm, UserChangeForm from .models import User class UserLoginForm(AuthenticationForm): username = forms.CharField() password = forms.CharField() class Meta: model = User fields = ['username', 'password'] class UserRegistrationForm(UserCreationForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'username', 'email', 'password1', 'password2', ) first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.CharField() password1 = forms.CharField() password2 = forms.CharField() class ProfileForm(UserChangeForm): class Meta: model = User fields = ( 'image', 'first_name', 'last_name', 'username', 'email', ) image = forms.ImageField(required=False) first_name = forms.CharField() last_name = forms.CharField() username = forms.CharField() email = forms.CharField() registration.html {% extends 'main/base.html' %} {% load static %} {% block title %}Registration{% endblock title %} {% block content %} <section class="login-reg d-flex"> <div class="login-title"> <h2>Registration</h2> <form action="{% … -
Django Template Override Works Locally but Not on Azure
I’m working on a Django project where I’m overriding the submit_line.html template. This override works perfectly in my local development environment, but when I deploy the application to Azure, the override doesn’t seem to take effect. Here’s the custom submit_line.html override in my templates directory: {% extends 'admin/submit_line.html' %} {% load i18n admin_urls %} {% block submit-row %} {{ block.super }} {% for obj in transitions %} <input type="submit" value="{{ obj }}" name="{{ obj }}"> {% endfor %} <!--{{ perms.ForecastResponse }}--> {%if perms.ForecastResponse.add_project%} <input type="submit" value="{% translate 'Clone project from source'%}" name="_cloneproject"> {%endif%} {% endblock %} File structure: myproject/ ├── ForecastResponse/ │ ├── migrations/ │ ├── templates/ │ │ └── admin/ForecastResponse/project │ │ | └── submit_line.html # Overridden template │ │ ├── ForecastResponse/ │ │ │ ├── base.html # Global base template │ │ │ ├── other_template.html │ │ ├── static/ │ │ ├── views.py │ │ ├── models.py │ │ └── admin.py │ ├── manage.py │ ├── settings.py │ ├── urls.py │ └── other_project_files/ What I've tried: Verified that the custom submit_line.html file exists in the correct location on Azure by inspecting the deployed files. Updated the settings.py to include the TEMPLATES section: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
Can not get group permissions by custom User and Group
I create my custom user and group as below: models.py (myusers app) ` from django.db import models from django.contrib.auth.models import AbstractUser, GroupManager, Permission class AbstractGroup(models.Model): name = models.CharField(_("name"), max_length=150, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_("permissions"), blank=True, related_name="fk_group_permission", ) objects = GroupManager() def __str__(self): return self.name def natural_key(self): return (self.name,) class Meta: verbose_name = _("group") verbose_name_plural = _("groups") abstract = True class Group(AbstractGroup): is_active = models.BooleanField(_("Is Active"), default=True) class User(AbstractUser): groups = models.ManyToManyField( Group, verbose_name=_("groups"), blank=True, help_text=_( "The groups this user belongs to. A user will get all permissions " "granted to each of their groups." ), related_name="user_set", related_query_name="user", ) ` and point in settings.py: AUTH_USER_MODEL=myusers.User AUTH_GROUP_MODEL=myusers.Group All is ok but when get group permissions (a_user.get_all_permissions() or a_user.get_group_permissions()) raise error: ValueError: Cannot query “a_user”: Must be “Group” instance. (a_user here is the user user instance) what is wrong? The get_group_permissions() return error. -
retrieving media files on render with django
Hopefully a simple issue that I cannot find any answer to online so far. Background : I have an django web app that is hosted on render.com. Everything is working apart from the media files that are hosted on a bought disk (mounted at /var/data) for my project. I have followed the documentation and added the following to settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = '/var/data' media context is set: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.media", ], I have urlpatterns configured for media: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) whitenoise is configured: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' requirements.txt asgiref==3.8.1 click==8.1.8 dj-database-url==2.3.0 Django==5.1.4 django-crispy-forms==2.3 gunicorn==23.0.0 h11==0.14.0 packaging==24.2 pillow==11.0.0 psycopg2-binary==2.9.10 sqlparse==0.5.3 typing_extensions==4.12.2 uvicorn==0.34.0 whitenoise==6.8.2 index.html {% extends "airfryer_app/base.html" %} {% block body %} <div class="product-container flex flex-wrap justify-content-center"> {% for recipe in recipes %} <div class="product shadow-lg w-1/5 rounded-lg m-10"> <div class="product-image"> <img src="{{ recipe.image.url }}" alt=""> </div> <div class="p-5"> <div class="font-bold"> {{ recipe.name }} </div> <div> {{ recipe.description }} </div> <div class="text-orange-700 font-bold text-orange"> {{ recipe.time }} minutes </div> <div class="mt-5"> <a class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded" href="{% url 'recipe' recipe.id %}">View Details</a> </div> </div> </div> {% if forloop.counter|divisibleby:3 %} <div class="w-full"></div> {% endif %} {% endfor %} </div> {% endblock %} Using … -
How to reuse mysql persistant connection in uwsgi + django + multi threading?
My Env: DJANGO 4.1 UWSGI 2.0.26 processes + gevent mode And I Use concurrent.futures.ThreadPoolExecutor as my thread pool I know that django mysql connecition is thread local. If I create thread pool in request thread, then pool thread id is different in each request so mysql connection is not reused.But if I create thread pool in uwsgi processes,the connection cannot be recycled after request finished and it will throw "Mysql server has gone away" afeter a few time. So how to reuse mysql connection correctly in my run env? -
Django REST + API Gateway CORS Issue with Cognito Authentication
I have issues with CORS, most likely due to Frontend (Amplify) being https and backend (ElasticBeanstalk) being http. Tried to fix unsuccessfully with API Gateway. Frontend: React app hosted on AWS Amplify Backend: Django REST framework on Elastic Beanstalk Authentication: AWS Cognito API Gateway as proxy between frontend and backend Issue: Getting CORS error when frontend tries to access backend through API Gateway. With Chrome CORS disabled, the request reaches backend but fails with Django auth error. Frontend (React/TypeScript): const fetchVideos = async () => { const session = await fetchAuthSession(); const token = session.tokens?.idToken?.toString(); // Token looks valid: eyJraWQiOiJxTHpReFZa... const fullUrl = `${BASE_URL}/api/premium-content`; const response = await fetch(fullUrl, { method: 'GET', credentials: 'include', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', } }); } Django Settings (base.py): CORS_ALLOWED_ORIGINS = [ "https://my-frontend.amplifyapp.com", "http://localhost:5173", "http://localhost:3000" ] CORS_ALLOW_CREDENTIALS = True API Gateway Configuration ANY method: HTTP Proxy integration to EB endpoint OPTIONS method: Mock integration with headers: Access-Control-Allow-Origin: 'https://my-frontend.amplifyapp.com' Access-Control-Allow-Methods: 'GET,OPTIONS' Access-Control-Allow-Headers: 'Content-Type,Authorization' Access-Control-Allow-Credentials: 'true' Gateway responses: 4XX and 5XX enabled for CORS Seeing the error message in the console log: Access to fetch at 'https://[api-gateway-url]/prod/api/premium-content' from origin 'https://my-frontend.amplifyapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control … -
font Tag issue in summer note
<font style="background-color: rgb(255, 255, 0);" color="#ff0000">Write something</font> Above tag generated by Summernote; the color property came outside of the style attribute. How can I fix this issue?" anyone found same problem that iam facing if you found let me know it will help me lot -
Why does Auth0 use /login/callback instead of my configured callback URL in the redirect to Azure AD?
I am implementing Okta - Auth0 with Azure Active Directory (Azure AD) as the identity provider (IdP) in my Django project. Here's a breakdown of my setup: Django OAuth Configuration: Callback URL in Django: https://mydomain/api/auth/callback/. My Django app redirects users to the Auth0 /authorize endpoint with the correct redirect_uri. Auth0 Application Settings: Allowed Login URLs: https://mydomain/api/auth/login/. Allowed Callback URLs: https://mydomain/api/auth/callback/. Allowed Logout URLs: https://mydomain/api/auth/logout/. Azure AD Application Settings: Redirect URI: https://mydomain/api/auth/callback/. Problem: When I delete the default callback (https://dev-xxxxx.ca.auth0.com/login/callback) from Azure AD, the login process fails with the following error from Azure AD: AADSTS50011: The redirect URI 'https://xxxxxxca.auth0.com/login/callback' specified in the request does not match the redirect URIs configured for the application. However, I have not included the okta default /login/callback in my Auth0 configuration. I only use /api/auth/callback/. The flow seems to depend on this default callback URL, even though I expect Auth0 to use my configured callback (/api/auth/callback/) throughout the login flow. Questions: Why does Auth0 internally use https://dev-xxxxxx.ca.auth0.com/login/callback instead of the configured callback URL (/api/auth/callback/) when redirecting to Azure AD? How can I eliminate the dependency on the default callback (/login/callback) and ensure the entire flow uses my custom callback (/api/auth/callback/)? Steps I’ve Tried: Ensured https://mydomain/api/auth/callback/ is … -
Switching Django USE_TZ to True
I have a site which is pretty old (started at Django 1.6) but has been upgraded over time and is now at Django 4.2. It has always had USE_TZ=False and TIME_ZONE='America/Chicago'. We have a lot of critical dates (subscriptions, purchase records, etc), many of which are fed from external webhooks from our payment processor. I'm looking at adding another Django app, but it requires USE_TZ=True. Anyone have any insight into what might happen if I turn it on? I've turned it on in my development environment and I don't see any obvious issues, but can't easily replicate the webhooks I receive and daily tasks that extensively use date calculations. Where should I be looking for issues? -
убрать надпись в регистрации This field is required [closed]
Я использую встроенную в джанго форму UserCreationForm для создания формы регистрации, но есть лишние предписания 'This field is required.' о том что эти поля обязательны, я хочу убрать их, помогите пожалуйста, ну или хотя бы перевести на русский что-б надпись была на русском, если так же сможете помочь исправить clean_email в формах так что б он не всегда выкидывал эту надпись после 1 тестового ввода существующего email вот скрин результата enter image description here views.py: class RegisterUser(CreateView): form_class = RegisterUserForm template_name = 'users/register.html' extra_context = {'title': 'Регистрация'} success_url = reverse_lazy('users:login') forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Логин:", widget=forms.TextInput(attrs={'class': "form-input"})) password1 = forms.CharField(label="Пароль:", widget=forms.PasswordInput(attrs={'class': "form-input"})) password2 = forms.CharField(label="Повтор пароля:", widget=forms.PasswordInput(attrs={'class': "form-input"})) class Meta: model = get_user_model() fields = {'username', 'email', 'first_name', 'last_name', 'password1', 'password2'} labels = { 'username': 'Логин', 'email': 'E-mail', 'first_name': 'Имя', 'last_name': 'Фамилия', 'password1': 'Пароль', 'password2': 'Повторить пароль', } widgets = { 'username': forms.TextInput(attrs={'class': "form-input"}), 'first_name': forms.TextInput(attrs={'class': "form-input"}), 'last_name': forms.TextInput(attrs={'class': "form-input"}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.order_fields(['username', 'email', 'first_name', 'last_name', 'password1', 'password2']) def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError("Такой E-mail уже существует") return email users/register.html: {% extends 'users/base.html' %} {% block title %}Регистрация{% endblock %} {% block content %} <h1>Регистрация</h1> <form method="post"> {% csrf_token %} {{ … -
Wagtail - add custom link option
I would like to customize External link type in Wagtail links in admin RichText field - I need to change (or at least disable) the link validation (e.g., to my custom regex) in admin frontend, as my links have different format to https://<something>. Does anybody know how to do that without forking wagtail and making own addition in this and this file? Any help would be appreciated. -
How can I override settings for code ran in urls.py while unit testing django
my django app has a env var DEMO which, among other thing, dictate what endpoints are declared in my urls.py file. I want to unit tests these endpoints, I've tried django.test.override_settings but I've found that urls.py is ran only once and not once per unit test. My code look like this: # settings.py DEMO = os.environ.get("DEMO", "false") == "true" # urls.py print(f"urls.py: DEMO = {settings.DEMO}") if settings.DEMO: urlpatterns += [ # path('my_demo_endpoint/',MyDemoAPIView.as_view(),name="my-demo-view") ] # test.test_my_demo_endpoint.py class MyDemoEndpointTestCase(TestCase): @override_settings(DEMO=True) def test_endpoint_is_reachable_with_demo_equals_true(self): print(f"test_endpoint_is_reachable_with_demo_equals_true: DEMO = {settings.DEMO}") response = self.client.get("/my_demo_endpoint/") # this fails with 404 self.assertEqual(response.status_code, 200) @override_settings(DEMO=False) def test_endpoint_is_not_reachable_with_demo_equals_false(self): print(f"test_endpoint_is_not_reachable_with_demo_equals_false: DEMO = {settings.DEMO}") response = self.client.get("/my_demo_endpoint/") self.assertEqual(response.status_code, 404) when running this I get: urls.py: DEMO = False test_endpoint_is_reachable_with_demo_equals_true: DEMO = True <test fails with 404> test_endpoint_is_not_reachable_with_demo_equals_false: DEMO = False <test succeed> urls.py is ran only once before every test, however I want to test different behavious of urls.py depending on settings Using a different settings file for testing is not a solution because different tests requires different settings. Directly calling my view in the unit test means that the urls.py code stays uncovered and its behaviour untested so this is also not what I want. How can I override settings for code … -
Add buttom from admin panel to ModelForm in Django
In the admin panel of a django app when you are adding a database entry that links data from another table on a foreign key you get a dropdown to select the entry and 3 buttons to edit, add or view an entry like this: However when you create a form for this model to take data from a user, the linked data only shows the dropdown menu and no buttons: Is there any way that I can add the 'add' and 'view' button on the input form so that the user can view an entry in more detail if unsure or add a new entry if the required information is not already in the database? It seems like it should be pretty simple if the functionality is already there for admin panel and would be neater than implementing some custom pages to load the data for viewing or redirecting to another form to add the new data? -
How to properly configure python path in Microsoft Dev Containers?
I have configured Microsoft Dev Containers for a Django project but I'm not able to properly set the python path since vscode is raising an error regarding a package that it is not able to find (i.e. Import "django.contrib.auth.models" could not be resolved from sourcePylancereportMissingModuleSource) and it is installed in the venv within my dev container. My approach has been to declare a variable in devcontainer.json but it has not worked since the warning is still appearing: "customizations": { // Configure properties specific to VS Code. "vscode": { "settings": { "python.pythonPath": "/opt/venv/bin/python3.11" } } } Any suggestion about how to fix this warning? -
After switching to postgresql - connection reset by peer
According to this tutorial I switched to postgresql code. # django_project/settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } } Here is docker-compose.yml # docker-compose.yml version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: Everything worked before editing DATABASES section. When I run $ curl 127.0.0.1:8000 curl: (56) Recv failure: Connection reset by peer