Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix a url submit_function not working?
trying to make a rating system but i get this errorerror, here are my urls and views urls views i want it to send ratings into the database when rating is sent -
Cannot autopopulate date field in django template with widget_tweaks
I’m building a django app that basically is a service for legal guardians to automatically create invoices. For the necessary information about their patients that need to be printed on the invoice, I have a model Patient: class Patient(models.Model): address_as = models.ForeignKey('AddressAs', on_delete=models.PROTECT) first_name = models.CharField('First Name', max_length=120) last_name = models.CharField('Last Name', max_length=120) birthday = models.DateField('Birthday') guardian = models.ForeignKey('Guardian', on_delete=models.CASCADE) court = models.ForeignKey(Court, related_name='patients', on_delete=models.PROTECT) record_number = models.CharField('Record Number', max_length=50) first_billing_date = models.DateField('Start of Legal Care', null=True, blank=True) billing_start = models.DateField('Start of Billing', null=True, blank=True) billing_end = models.DateField('End of Billing', null=True, blank=True) last_billing = models.DateField('Last Billing Date', null=True, blank=True) dutyscope_financial = models.BooleanField('Dutyscope Financial Care') is_wealthy = models.BooleanField('Patient is wealthy', default=False) taken_from_volunteer = models.BooleanField('Taken from Volunteer', default=False) given_to_volunteer = models.BooleanField('Given to Volunteer', default=False) def __str__(self): return f'{self.last_name}, {self.first_name}, geb. {self.birthday}' and a very simple form class: class PatientForm(forms.ModelForm): class Meta: model = Patient fields ='__all__' and of course a view to create patients and a template. So far, so good. Everything works. But now I want to add the possibility to edit the patient’s data. I created a new view for that: def edit_patient(request, patient_id): patient = Patient.objects.get(id=patient_id) if request.method =='POST': form = PatientForm(request.POST or None, instance=patient) if form.is_valid(): updated_patient = … -
pandas read_sql using Django.db.connection
Is there a recommended way to utilize pandas read_sql from within a Django app? I was using a much older version of pandas and this worked: import django.db.connection import pandas as pd df = pd.read_sql("select employee.name from employee;", con=connection) Now, I'm getting this error from read_sql: UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy. The query seems to work even with the warning but I don't want to take chances that it might break. I was using the Django.db.connection so that pandas makes use of the db connection pooling within Django. I can successfully use a connection string with the read_sql method but I don't want pandas opening up a bunch of connections in a multi-user system. Same with SQLAlchemy - I don't want to add another connection pool into the app. Any advice or workarounds? I haven't found anything in the pandas or Django documentation covering this. Django==3.2 pandas==2.2.1 mysqlclient==2.2.4 MySQL version 8 -
Is there a way to have SSO using Atlassian for our external Django application?
We created a Forge app and we have an existing Django/Python application. Our forge app app has a connect button and when the user clicks it we want the user to automatically login with the credentials from Jira. Is there a way of possibly doing that? We followed Django-OAuth-Toolkit documentation to build an OAuth 2.0 provider. We managed to get our access token using bash. We followed the documentation on the Atlassian website for External OAuth 2.0 for Forge apps. But we could not get that working. We were expecting some type of response using the Google provider but kept getting errors. We aren't sure exactly what to do after this. The documentation vague. -
Django makemigrations not detecting changes in models
I’m working on a Django project with an app called ‘spider’. I’ve made some changes to my models in models.py, but when I run python manage.py makemigrations spider, it doesn’t create a migration. Here’s the error message I’m getting: No installed app with label 'spider'. Code: Here’s what my INSTALLED_APPS looks like in settings.py: I'm having trouble with Django migrations. Here's what my INSTALLED_APPS looks like in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'spider', ] -
mysql issue with Xampp
I am getting this error on my windows vscode terminal after adjusting the database settings on my settings.py to Xampp settings in django : File "C:\Users\Admin\Desktop\ExPro\venexp\lib\site-packages\django\db\backends\mysql\base.py", line 17, in raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I get the error immediately I tried to runserver which is supposed to run smoothly and prime me to migrate unapplied migrations.. but instead I keep getting the above error no matter what I do.. -
Domain does not work without dot in the en
Why my domain works only when I type this: example.com. with a "dot" and without "www" and in any other condition I get 400 error: http://example.com./ - it works http://www.example.com/ - it doesn't work http://www.example.com./ - it doesn't work Error I get: GET http://www.example.com./ 400 (Bad Request) I use: django, aws, route53, ec2, ubuntu, nginx, gunicorn I followed this tutorial 1:1: I set up: elastic IP for my instance and connnect to my instance. In hosted zone I did like in tutorial: Record name: example.com Record type: A Value: my IP Alias: No TTL (seconds): 300 Routing policy: Simple and > Record name: > www.example.com > Record type: > A > Value: > example.com. > Alias: > No > TTL (seconds): > 900 > Routing policy: > Simple 3)Nginx conf: ``` server { listen 80 default_server; server_name example.com www.example.com myIP;} ``` then restart: ``` sudo systemctl restart nginx sudo service gunicorn restart sudo service nginx restart ``` Settings.py: ALLOWED_HOSTS = [ 'example.com','myIP', ] Thanks in advance! -
Estilos de panel de administracion django no carga
Subi mi proyecto a un servidor gratuito de pythonanywhere la version python es 3.10 y la version django es 5.0. Los estilos de mis templates cargan de manera correcta, pero los estilos de mi panel de administración que trae por deaful django se muestran sin estilos enter image description here Esta es mi configuracion en settings.py obviamnete tengo importada la libreria os STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = 'static/' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' ¿Alguien sabe como poder solucionar esto? -
transaction.atomic() rolls back if another query is executed
I am having issues with Django's transaction.atomic. I have this app that users can update their information, but I will be giving an example here. So I want to prevent update to this field if more than one requests is received, so I want to lock the row which is why I am using transaction.atomic and select_for_update. So I have a UserProfile model that I want to update some information, the method which i use to update is is below Class Profile(models.Model): def get_queryset(self): return self.__class__.objects.filter(id=self.id) @transaction.atomic() def update_age( self, age: int, ) -> None: obj = self.get_queryset().select_for_update().get() obj.age = age obj.save() Below is the view class UserProfileView(APIView): def put(self, request): profile = rquest.user.profile profile.update_age(request.data["age"]) UpdateHistory.objects.create(user=request.user, updated_field="age") The issue is UpdateHistory object is created but the age update is rolled back, but when I remove the creation of the UpdateHistory, the age is actually updated successfully. So the above code only creates UpdateHistory, but doesnt update the UserProfile's age. But if I remove the line UpdateHistory.objects.create(user=request.user, updated_field="age"), the age is updated successfully. No exception is being raised at all, this has been confusing me for days. Hopefully I can get some help. Thanks in advance -
Django-Allauth Function Working Locally But Not When Deployed To Azure
I built a function using Django-allauth that after a user tries logging in with incorrect credentials three times, the program times them out for an hour. The code works locally, but when I deploy to an Azure Instance, the function has to impact at all. Any insights would be greatly appreciated :). -Tried verifying if it was a timezone issue in calculating the logout time -
running django tests --parallel and splitting log files per test-runner worker
I'm using manage.py test --parallel to run my tests and want to create a separate log file for each test runner. Currently, all the test runner worker write to the same log file, so I get a single log file with contents "striped" like this: [ForkPoolWorker-2] ... [ForkPoolWorker-1] ... [ForkPoolWorker-1] ... [ForkPoolWorker-3] ... [ForkPoolWorker-2] ... [ForkPoolWorker-4] ... [ForkPoolWorker-1] ... I create a custom configure_logging() method like this: import logging.config import os def configure_logging() -> None: """Custom logging configuration with process-id named files""" process_id = os.getpid() log_file_path = f"runner-{process_id}.log" LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "file": { "level": "DEBUG", "class": "logging.FileHandler", "filename": log_file_path, }, }, "loggers": { "django.log": { "handlers": ["file"], "level": "DEBUG", "propagate": True, }, }, } logging.config.dictConfig(LOGGING) I'm using a custom test-runner to wire things up: from django.test.runner import DiscoverRunner from myapp.tests.logging_config import configure_logging class ParallelTestRunner(DiscoverRunner): """Parallel test runner with separate log files for each worker""" def setup_test_environment(self, **kwargs): """Configure the test environment with our custom log setup""" super().setup_test_environment(**kwargs) # Configure logging with a unique file per test process configure_logging() I wire that up in settings.py like this: TEST_RUNNER = "myapp.tests.runners.ParallelTestRunner" However, when I look for the log files, it appears it's only creating a single … -
i need help regarding django in vs code?
I want to work on a Django project , but when i try to create a .html file inside templates , it doesn't recognize it as a django template even though i have installed all the django extensions. i also tried to change the file template by default method i.e (ctrl+k M) i also tried to change the file template by default method i.e (ctrl+k M) . -
Error response from daemon: invalid volume specification docker error
I'm using Docker Desktop for Windows on Windows 10. I wanted to run a very simple project from django on Docker locally. after the command "docker build ." everything was OK, but after the command "docker-compose up" I got an error: "Error response from daemon: invalid volume specification : 'C:\Users\elahe\postgre2:/code:rw" I've tried this project on two different windows 10. on one of them, I had no problem, but on the second one I got the mentioned error so I guess my problem is because of the windows or docker setting, is it right? #dockerfile: FROM python:3.9 ENV PYTHONDONTWRITECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ # docker-compose: version: '3.9' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 -
How to build a form in django based on 3 models with Many-To-Many relationship
This is my first experience with django and I'm stuck on creating the form. The models that must be involved in the form are the following: models.py class Ingredient(models.Model): name = models.CharField(max_length=100) id_category = models.ForeignKey(Category, on_delete=models.CASCADE) property = YAMLField() def __str__(self): return self.name class Meta: verbose_name_plural = "Ingredients" class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Meta: verbose_name_plural = "Categories" class Inventory(models.Model): id_user = models.ManyToManyField(User) name = models.CharField(max_length=200) last_update = models.DateTimeField(auto_now=True) creation_date = models.DateTimeField(auto_now_add=True) ingredients = models.ManyToManyField(Ingredient, through='InventoryIngredient') class Meta: verbose_name_plural = 'Inventories' ordering = ['-creation_date'] class InventoryIngredient(models.Model): id_ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) id_inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) quantity = models.DecimalField(decimal_places=2, max_digits=10) measurement_unit = models.CharField(max_length=100) expiry_date = models.DateField() I don't know where to start implementing the form. I tried to look for something similar but I didn't find anything about form management in case of many-to-many relationship with a through table. In practice, in my form there will have to be the attributes of the Ingredient(name, property) model and the attributes of the InventoryIngredient(quantity, measurement_unit, expiry_date) model and also the name for the Category. I ask you if you can please help me with this, at least I would need a basis from which to implement my form. -
Django Template not loading the view inside another template
I am trying to include another template inside my home page as follows: {% if user.userorganisation.organisation %} {% include 'organisation_members.html' %} {% else %} {% include 'create_organisation.html' %} {% endif %} The create_organisation template is correctly loading its view so the step of checking the organisation of the user is correct. When I am trying to directly access the organisation_members.html url everything is working fine but when I am inside the home page where the include 'organisation_members.html' exists, only the static contents are being loaded. I have tried adding some prints for debugging and the view is not being called at all. Here is the view: def organisation_members(request): print("aaaaaa") try: print("aaaaaaaa") user_organisation = UserOrganisation.objects.get(user=request.user) print(user_organisation.organisation) organisation_users = UserOrganisation.objects.filter( organisation=user_organisation.organisation).select_related('user') print(organisation_users) context = { 'organisation_users': organisation_users, } return render(request, 'organisation_members.html', context) except UserOrganisation.DoesNotExist: return redirect('some_error_page') And here is the url: path('organisation_members/', views.organisation_members,name='organisation_members'), Why is the view not being called when including the html page? I know that the 'include' only includes the html but why is it that the create_organisation.html being called and the organisation_members not, when I am doing the same exact steps in both of them -
ByPass Django Basic Auth
I am trying to bypass django basic auth as I want to use firebase auth on Frontend and I am only getting the id_token on Backend. The Middleware is as follows: class FireBaseAuth(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): modified_request = self.process_request(request) response = self.get_response(modified_request) response = self.process_response(response) return response def process_request(self, request): middleware = "[FireBase Auth]" logger.info(f"{middleware} Request path: {request.path}") if request.path.rstrip('/').split('/')[-1] in EXCLUDE_AUTH_ENDPOINTS: logger.info( f"{middleware} Skipping auth check for: {request.path}") return request user = User.objects.filter(email='lahiwe@pelagius.net').first() request.user = user return request token = request.META.get("HTTP_FB_ACCESS_TOKEN") if not token: logger.info(f"{middleware} No token found") return HttpResponse("Unauthorized", status=status.HTTP_401_UNAUTHORIZED) # check if token is valid try: fb_user = auth.verify_id_token(token) if not fb_user: logger.info(f"{middleware} No info found against token") return HttpResponse("Unauthorized", status=status.HTTP_401_UNAUTHORIZED) if fb_user: # Fetch user Data fb_user = auth.get_user_by_email(fb_user['email']) if not fb_user.email_verified: logger.info(f"{middleware} User email not verified") return HttpResponse("User email not verified", status=status.HTTP_401_UNAUTHORIZED) logger.info( f"{middleware} Got user[{fb_user.email}] from firebase") # Check if user exists in current region user = User.objects.filter(email=fb_user.email).first() # Create user if not exists if not user: logger.info(f"{middleware} User not Found") return HttpResponse("User email not Found",status=status.HTTP_400_BAD_REQUEST) logger.info(f"{middleware} User Found. {user.id}") request.user = user setattr(request, 'user', user) logger.info(f"{middleware} Updated request user") return request except Exception as e: exec_type, exce_value, … -
How to fix MyPy [return-value] error when type is actually correct
I am using Django-Ninja + MyPy and I get this error that type it received tuple[int, dict[str, str]]" is not correct as it doesn't match one of the tuple[int, None] | tuple[int, DetailType] types but it is exactly as second type. Because in other parts of code it can figure out correctly it has "detail" as key. But as soon as I use Union[...] it somehow cannot look recursively? apps/users/views.py:106: error: Incompatible return value type (got "tuple[int, Message]", expected "tuple[int, None] | tuple[int, DetailType]") [return-value] This is how my types look like: DetailType = TypedDict("DetailType", {"detail": str}) MessageType = tuple[int, DetailType] NoContentType = tuple[int, None] And this is complete code where mypy is returning error: @post("me/password/change/", response={204: None, 401: Message}, url_name="users_me_password_change") def change_password(request: HttpRequest, data: ChangePasswordRequest) -> Union[NoContentType, MessageType]: <<< THIS IS RETURN TYPE user = request.user if not user.check_password(data.password): return 401, {"detail": "Password is incorrect."} <<< IN THIS LINE IS MYPY ERROR user.set_password(data.new_password) user.save() return 204, None -
i worked on the backend django framework. but i faced Django views.py import problem
I work on the django framework but when i open the urls.py file the views import did not work . kindly guide me . enter image description here kindly guide me about my problem so i continue next to it. kindly give a useful suggestion and solution about it. -
I think iam getting something wrong
recently i tried to setup my environment using miniconda so, i download python and django in my environment so, when is started my django project django-admin startproject myproject i got this error Unable to create process using 'C:\Users\Yoga 260.conda\envs\myenv\python.exe “C:\Users\Yoga 260.conda\envs\myenv\Scripts\django-admin-script.py” how i could solve the issue i tried to delete env and create new one but it didnt work also i started from scratch and deleted everything -
How to create alias for first active item in reverse relation in Django models?
I have a model called Item: class Item(models.Model): ... Also I have another model called Content. It has relation to Item and a ChoiceField to select is the content is active or not: class Content(models.Model): item = ForeignKey(Item related_name=) is_active = BooleanField(default=False) content = TextField() def save(self, *args, **kwargs): """There's a logic to make sure every item has only one content""" I have two questions. How to filter out the Items without any content or without any active content. Can I do something like alias to call item.content to return active content of the item without causing db performance issues. -
Translated Fields not Rendering Correctly in Django CMS Plugin
Am encountering an issue with rendering translated fields in a Django CMS plugin using django-modeltranslation. The plugin is supposed to display translated content based on the selected language, but it only renders with the default language. All other non-CMS plugin parts on the page that also make use of django-modeltranslation translate and are displayed correctly. Here's a brief overview of the setup: I'm using django==4.2.10; django-cms==4.1.0; along with django-modeltranslation==0.18.11 for model field translations. The plugin in question (HeaderPlugin) has a single field that is translated using django-modeltranslation. The template (cms_plugins/header/list_items.html) only includes {{ instance }}, but the translated fields are not appearing as expected when switching languages. {{ instance }} only displays the instance when the default language is selected. The plugin is used within {% static_alias 'header' %}. A noteworthy observation is that, when I want to set the plugin for a non-default language page via the menu dropdown Aliases..., it redirects to the default language (since the page does not exist). Hence I am only able to set the plugin from the default language. The plugin and associated model: #cms_plugins.py @plugin_pool.register_plugin class HeaderPlugin(CMSPluginBase): model = HeaderPlugin module = _("Header") name = _("Header Plugin") render_template = "cms_plugins/header/list_items.html" def render(self, … -
Using 'import_export' model in Django....If I export means it shows an badgateway in nginx
`I am using an import-export model in my Django admin panel it works very well...if the records goes more means on that time also i am export means it gives an error like Bad Gateway...if i click export it asks what format it wants like that then it takes too much of timing and gives an Bad Gateway.I don't Know why `class SongListAdmin(ImportExportModelAdmin): list_display = ('article_title','song_views','date_posted','date_updated','listview') search_fields=('article_title','Tags__tag_name') this is my code...In my SongList table having an record 16,000 if i click export from my admin panel means it goes an Bad Gateway....why If i export i need to 16,000 records but it does'nt comes the actual result it goes an an badgateway in nginx why`` -
Fastest way to redirect with refresh button?
I have an issue where after I've selected some products and filtered them I would like to refresh to the home page (in my case - series_list/) where it shows all products and their specifications but without the filters. Basically it should refresh to the home page immediately when I click on the refresh button from the browser. I tried using: if (performance.navigation.type === 1) { window.location.href = '/series_list/'; } However, it takes roughly 2-2.5 seconds for it redirect to the home page which is too slow. Here is the Django code for the products filters and specifications: {% for key, value in specification_list_fields %} <th> <a class="table-headers" href="?{% if order_by == key %}order_by={{ key }}_desc{% else %}order_by={{ key }}{% endif %}&{{ query_atrs_wo_order_by }}"> {{ value }} <i class="fa fa-fw fa-sort{% if order_by == key %}-up{% elif order_by == key|add:'_desc' %}-down{% else %}{% endif %}"></i> </a> </th> {% endfor %} Is it possible to redirect even quicker when pressing the refresh button? -
How to save products on my Django Ecommerce website
I am trying to implement a feature in my Django ecommerce website where a user can save a desired product after clicking on a button on the product detail page of said product - <div class="me-3 text-white" onclick="saveProduct({{ product.id }})"> <i class="bi bi-balloon-heart"></i> </div> This is my models.py - class UserActivity(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) timestamp = models.DateTimeField(default=timezone.now) saved = models.BooleanField(default=False) # a boolean field to track whether the product is saved by the user class Meta: ordering = ['-timestamp'] This is my ecommerce/views.py - @require_POST @login_required def save_product(request): if request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest': product_id = request.POST.get('product_id') product = get_object_or_404(Product, pk=product_id) # Check if the user has already saved the product user_activity, created = UserActivity.objects.get_or_create(user=request.user, product=product) if created: user_activity.saved = True user_activity.save() return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error', 'message': 'Product already saved'}, status=400) else: return JsonResponse({'status': 'error', 'message': 'Invalid request'}, status=400) this is my ecommerce/urls.py - app_name = 'ecommerce' path('save_product/', views.save_product, name='save_product'), This is my accounts/views.py for rendering the saved products - @login_required def saved_items(request): current_path = resolve(request.path_info).url_name saved_products = UserActivity.objects.filter(user=request.user, saved=True).select_related('product') return render(request, 'accounts/saved_items.html', {'current_path': current_path, 'saved_products': saved_products}) This is my saved_items.html for rendering saved products - {% for user_activity in saved_products %} <div class="border … -
What to do with ''attempted relative import with no known parent package'' in VS?
it is PS C:\storefront> & C:/Users/ANJALY/.virtualenvs/storefront-qOrq4PPp/Scripts/python.exe c:/storefront/playground/urls.py Traceback (most recent call last): File "c:\storefront\playground\urls.py", line 3, in from . import views ImportError: attempted relative import with no known parent package PS C:\storefront>. i tried to change it to subpackage.