Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filters field forms doesn't show in HTML
I try to use django-filters in my Django app. I am using it with pagination. Page renders properly (it just works), but without filter fields that I created. Only submit button shows. I will be really thankful for any help i don't know what I am doing wrong. I want to use ModelChoiceFilter to filter objects from Image model, by their foreign key Publisher filters.py # filters.py import django_filters from django import forms from .models import Image, Publisher, Author class ImageFilter(django_filters.FilterSet): class Meta: model = Image fields = ['title', 'created'] class ImageForeignFilter(django_filters.FilterSet): wydawca = django_filters.ModelChoiceFilter( queryset=Publisher.objects.all(), empty_label="Wszyscy wydawcy", label="Wydawca", widget=forms.Select(attrs={'class': 'form-control'}), ) class Meta: model = Image fields = ['created', 'wydawca'] models.py # models.py class Publisher(models.Model): name = models.CharField(max_length=200, default='',blank=True, verbose_name="Nazwa wydawcy", help_text="Nazwa wydawcy") urlglowna = models.URLField(max_length=2000, default='', blank=True, verbose_name="Strona główna", help_text="Adres strony") def __str__(self): return '{} {}'.format(self.name,self.urlglowna) class Image(models.Model): url = models.URLField(max_length=2000, verbose_name="Link do znaleziska", help_text="Podaj bezpośredni link") created = models.DateField(auto_now_add=True) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, null = True, blank=True) views.py # views.py def image_list(request): images = ImageForeignFilter( request.GET, queryset=Image.objects.filter(status=Image.Status.PUBLISHED).order_by('created') ).qs paginator = Paginator(images, 15) page = request.GET.get('page') try: page_number = paginator.page(page) except PageNotAnInteger: page_number = paginator.page(1) except EmptyPage: page_number = paginator.page(paginator.num_pages) return render(request, 'images/image/list.html', {'section': 'images','images': images, 'page_number': page_number}) … -
new Media files in django gets 404 not found nginx
My old media files (photos) are loading correctly but when new medias are uploaded I'm getting 404 not found by nginx. I used docker and this is my volume part of docker compose: volumes: - '/root/docker-compose/data/media/MEDIA/:/app/MEDIA' all media files are loading correctly and saved correctly but when new files added I get 404 not found. although all files are uploaded correctly and I can see them not only in docker container but also outside of it. but still getting 404 not found! I tried changing media files and reseting all docker compose details and uwsgi configs. but still not fixed. and also try refactor settings and urls. -
"Column 'group_id' cannot be null". i cant register superuser?
as i said i cant register superuser. this is not my project so I don't know it fully. during the createsperuser, django requires a password and a phone number and that's it. models.py class User(AbstractBaseUser): is_required = models.BooleanField(verbose_name=_('Статус подтверждения'), default=False, blank=True) is_staff = models.BooleanField(verbose_name=_('Статус персонала'), default=False) group = models.ForeignKey('Groups', verbose_name=_('Группа'), on_delete=models.CASCADE, ) center = models.ForeignKey('Centers', verbose_name=_('Центр'), on_delete=models.PROTECT, null=True) disease = models.ForeignKey('Disease', verbose_name=_('Заболевание'), on_delete=models.SET_NULL, null=True) number = models.CharField(verbose_name=_('Номер'), max_length=30, unique=True, null=True) email = models.CharField(verbose_name=_('Электронный адрес'), max_length=100, blank=True, null=True) first_name = models.CharField(verbose_name=_('Имя'), max_length=20, null=True, blank=True) last_name = models.CharField(verbose_name=_('Фамилия'), max_length=30, null=True, blank=True) surname = models.CharField(verbose_name=_('Отчество'), max_length=40, null=True, blank=True) birthday = models.DateField(verbose_name=_('День рождения'), null=True, blank=True) image = models.ImageField(verbose_name=_('Фотография Пользователья'), upload_to='users_photos/', blank=True, default='media/site_photos/AccauntPreview.png') country = models.ForeignKey('Countries', on_delete=models.PROTECT, verbose_name=_('Страна'), null=True) city = models.CharField(verbose_name=_('Город'), max_length=50, null=True) address = models.CharField(verbose_name=_('Адрес'), max_length=100, unique=False, null=True) created_at = models.DateTimeField(verbose_name=_('Дата создания'), auto_now_add=True, blank=True, null=True, ) updated_at = models.DateTimeField(verbose_name=_('Дата изменения'), auto_now=True, blank=True, null=True, ) USERNAME_FIELD = 'number' objects = UserManager() def __str__(self): return self.number def delete(self, using=None, keep_parents=False): group = Groups.objects.get(id=self.group_id) group.number_of_people -= 1 group.save(update_fields=['number_of_people']) super(User, self).delete() def has_perm(self, perm, obj=None): return self.is_staff def has_module_perms(self, app_label): return self.is_staff class Meta: verbose_name_plural = 'Пользователи' verbose_name = 'Пользователья' ordering = ['-created_at'] class Groups(models.Model): name = models.CharField(verbose_name=_('Название Группы'), max_length=100, null=True) number_of_people = models.IntegerField(verbose_name=_('Количество людей'), default=0) def … -
How long does it take to install chromadb on Ubuntu?
I have developed a django project and am trying to deploy to AWS EC2 Instance. My project uses chromadb so I try to install with this command. pip install chromadb Then it installs all the related dependencies but when it starts to install hnswlib, it freezes. Building wheels for collected packages: hnswlib Building wheel for hnswlib (pyproject.toml) ... \ It doesn't give any error but no progress. How to handle this? Should I wait? This was the second time for me to deploy this kind of project but at the first time, I installed chromadb without any issue. But at that time, I used the Instance that my client has provided. Now I created the Instance with myself. Are there any kind of settings about Instance? Thanks -
Django BaseFormSet and formset_factory not working properly
I took reference from https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html to create a formset that creates multiple users from a model named Office365User that has a foreign key field linked to another model named Domain, but the formset is not saving the form. It would be really helpful if the problem can be identified in this or an alternative solution can be suggested. ############models.py########## class CloudFlareAccount(models.Model): username = models.CharField(max_length=200, null=False) password = models.CharField(max_length=200, null=False) api_key = models.CharField(max_length=500, null=False) date_created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CMSUser, null=False, on_delete=models.CASCADE) def __str__(self): return self.username class Domain(models.Model): name = models.CharField(max_length=150, null=False) date_created = models.DateTimeField(auto_now_add=True) is_verified = models.CharField(max_length=10, default='Not Specified') cloud_flare_account = models.ForeignKey(CloudFlareAccount, null=False, on_delete=models.CASCADE) def __str__(self): return self.name class Office365User(models.Model): name = models.CharField(max_length=200, null=False) issuer = models.ForeignKey(Domain, null=False, default='Select Issuer', on_delete=models.CASCADE) mail = models.CharField(max_length=150, null=False, unique=True) password = models.CharField(max_length=100, null=False) date_created = models.DateTimeField(auto_now_add=True) is_licensed = models.CharField(max_length=10, default='True') is_active = models.CharField(max_length=10, default='Not Specified') def __str__(self): return self.name ############forms.py############ class CreateUser(ModelForm): def __init__(self,*args, listt=None, **kwargs): super(CreateUser, self).__init__(*args, **kwargs) if listt is not None: self.fields['issuer'].queryset = listt class Meta: model = Office365User fields = ['name', 'issuer', 'mail', 'password'] class CreateBulkUser(BaseFormSet): def clean(self): """ Adds validation to check that no two links have the same anchor or URL and that all links have both … -
Why isn't CSS loading on my django website?
I have managed to upload my django project to a server(www.sb10-89.co.uk but the css file isn’t working. Even the admin page doesn't look right, again i guess its missing a css page. The code below is from my settings file. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'staticfiles/bands_ratings' See below image for file structure. Connecting css in html <link rel="stylesheet" href="{% static 'Style.css' %}" > Project level urls file code """download_band_rater_v4 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path , include from django.views.generic import RedirectView from django.contrib.auth.views import LogoutView urlpatterns = [ path("admin/", admin.site.urls), path('bands_ratings/', include ('bands_ratings.urls')), path('',RedirectView.as_view(url='bands_ratings/signup/')), path('accounts/', include('django.contrib.auth.urls')) ] #urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How can I get the user's data that is not logged in from a model
I have this model that represents a connection between two users: class Connection(models.Model): userone = models.OneToOneField(User, on_delete=models.CASCADE, related_name="downconnections") usertwo = models.OneToOneField(User, on_delete=models.CASCADE, related_name="upconnections") date_established = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "connection" verbose_name_plural = "connections" ordering = ["date_established"] db_table = "connections" def __str__(self): return f"{self.userone} is connected to {self.usertwo}" I would like to the serialized data of the user that is not logged in but no matter what I get a key error "request" Here is the serializer: class ConnectionSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = Connection fields = [ "id", "user", "date_established" ] def get_user(self, obj): request = self.context.get("request") logged_in_user = getattr(request, "user", None) if logged_in_user: if obj.userone == logged_in_user: return UserSerializer(obj.usertwo).data elif obj.usertwo == logged_in_user: return UserSerializer(obj.userone).data return None def to_representation(self, instance): return self.get_user(instance) Why is this not working? -
Integrating Veracode logging formatter library into Django project
there! I'm currently working on resolving a vulnerability issue reported by Veracode, specifically CWE 117 (Improper Output Neutralization for Logs). To address this issue, I need to implement the Veracode logging formatter library available at logging-formatter-anticrlf in my Django project. In Django, there is a configuration file called settings.py where the logging behavior for the application is defined using formatters, handlers, and loggers. Here's an example of the configuration: # Logging LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {filename}:{lineno} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'file': { 'level': 'DEBUG', 'class': 'concurrent_log_handler.ConcurrentRotatingFileHandler', 'filename': os.path.join(BASE_DIR, '..', '..', 'log-debug.log'), 'maxBytes': 1024 * 1024 * 1024, 'backupCount': 365 * 7, 'formatter': 'verbose', }, }, 'root': { 'handlers': ['console', 'file', 'errorfile'], 'level': 'DEBUG', }, 'loggers': { 'root': { 'handlers': ['console', 'file', 'errorfile'], 'propagate': True, 'level': 'DEBUG', }, 'django.request': { 'handlers': ['console', 'file', 'errorfile'], 'propagate': False, 'level': 'DEBUG', }, 'django.server': { 'handlers': ['console', 'errorfile'], 'propagate': False, 'level': 'DEBUG', }, 'webportal': { 'handlers': ['console', 'file', 'errorfile'], 'propagate': False, 'level': 'DEBUG', }, } } In each module of the Django application, the LOGGER is instantiated … -
Reduce database hit when using django-taggit and mymodel.tags.all in a template
I'm using django-taggit in Django 3.2 and can't figure out how to prevent it from hitting the database for every object in a list view template. Here's how I'm using it: class Quest(TagsModelMixin, models.Manager): # etc. In a ListView html template, I am displaying all Quest objects and their tags like this: {% for obj in quest_queryset %} {{obj.name}}: {{ obj.tags.all }} {% endfor %} At first, this was hitting the DB twice per object. I found that if I prefetch_related I could remove half of them: quest_queryset = quest_queryset.prefetch_related('tags') But I'm still getting one hit per object. How can I eliminate this repetition? Here's the offending query as shown by django-debug-toolbar, when there are 5 Quest objects. -
Django: How to format nested data, including a list of dictionaries, as multipart/form-data for posting?
How can I format nested data, including a list of dictionaries, as multipart/form-data for posting in Django? DATA = { "title": "Test Entry", "subcategory_id": subcategory.pk, "description": "Description for test entry.\n" * 2, "price": 150_000.00, "publisher": publisher.pk, "location": { "town": "Ant Town", "landmark": "Pink Poolside", }, "cover": _simple_image(), "images": [_simple_image(), _simple_image()], "specs": [ {"name": spec_field1.name, "value": "1000", "field_id": spec_field1.id}, {"name": spec_field2.name, "value": "SSD", "field_id": spec_field2.id}, ], "tags_ids": [tag.id for tag in TagFactory.create_batch(2)], } def test_something_doesnt_go_wrong(self): self.client.force_authenticate(user=UserFactory()) url = reverse("entries:entry-list") response = self.client.post(url, data, format="multipart") self.assertEqual(response.status_code, 201) self.assertEqual(len(response.data["images"]), 2) self.assertEqual(len(response.data["tags"]), 2) This is the error I get when I run my test suite. AssertionError: Test data contained a dictionary value for key 'location', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. Is this even legal? Is the API badly designed (I'm wondering). What can I do here? I can't seem to wrap my head around how to achieve this using QueryDict. -
Figma to Django (Python Web Framework) [closed]
Haii! I am new to Python web development, and I am using Python to master it further. I am trying to create a website using Django, and I already have my design in Figma. I am proficient in creating attractive user interfaces in Figma, but I have never used it with Python / exported. I do not know how to easily export Figma to Django. Does anyone know how to import Figma to Django without exporting every single item into an HTML file? Is that the only solution? Or am I doing something wrong? and are there any youtube / sites / plugin that you can recommend for me that I can try? I'm honestly lost for how to make exporting Figma to Django easier for myself. If there's no better solution, I completely understand, but I wanted to see if there was a better way than converting everything myself, which would take a significant amount of time. Thank you so much!! -
Django df add filter to df column
I am new to Django. I have a df and I can display it in the html. I use the pandas.read_sql_query to pull the data from the db. I want to realize the filter for each column in the df. views.py def index(request): dfa_query = "select * from database" dfa = pandas.read_sql_query(dfa_query,connection) dfa_html = dfa.to_html(index=False) return render(request, 'CaseTest.html',{'dfa':dfa_html}) CaseTest.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CaseTest</title> </head> <body> <h2> dfa </h2> <div style="height: 500px; overflow: auto;"> {{dfa | safe}} </div> </body> </html> THe filter function I want to realize is sth like excel filter, for each column there is a drop down menu and you can choose the value you want, then the df will only show the value which matches the requirements. for the display for filter, I am okay with any format (1) the filter in excel (2) the filter on the top of the table, see picture below Any help is really appreciated!! -
Django create picture object based on upload_to and get response
I have this model and there is a ImageField with custom upload_to in it, so i want to create an instance and give the content of the file to my django model but i don't want to give any path or save image and i want django to handle this for me. this is the model: class UploadSorlThumbnailPictureMixin(UploadBasePictureMixin): picture = ImageField( _('picture'), max_length=255, width_field='width_field', height_field='height_field', help_text=_('The picture that is uploaded.'), upload_to=category_dir_path, validators=[validate_file_extension] ) and This is how i want to create instance: response = requests.get(base_url) # this is the image content UploadSorlThumbnailPictureMixin.objects.create( alternate_text=images['name'], picture='WHAT TO DO HERE?' ) How can i get the image from response and put create the instance with it? -
How to get the session of session with `request.session.get()` in Django?
I could get the session of session with request.session['key']['key'] as shown below: # "views.py" from django.http import HttpResponse def my_view(request): request.session['person'] = {'name':'John','age':27} print(request.session['person']['name']) # John print(request.session['person']['age']) # 27 return HttpResponse("Test") But, I couldn't get the session of session with request.session.get('key/key') as shown below: # "views.py" from django.http import HttpResponse def my_view(request): request.session['person'] = {'name':'John','age':27} print(request.session.get('person/name')) # None print(request.session.get('person/age')) # None return HttpResponse("Test") So, how can I get the session of session with request.session.get()? -
Is there a way to configure Django JWT authorisation/confirmation emails without SMTP server?
We are building an app with Django using Djoser and want it to send authorisation/confirmation emails to users. But the client said that there is no SMTP server on the domain he provides. So, is there some third-party api service that can send emails for our app? While testing we used the following code (it worked): /settings.py `DJOSER = { "HIDE_USERS": False, "LOGIN_FIELD": "email", "SERIALIZERS": { "user_create": "users.serializers.CustomUserCreateSerializer", "user": "users.serializers.CustomUserSerializer", "current_user": "users.serializers.CustomUserSerializer", }, "ACTIVATION_URL": "#/activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_RESET_CONFIRM_URL": "#/activate/{uid}/{token}", "USERNAME_CHANGED_EMAIL_CONFIRMATION": True, } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=1), "AUTH_HEADER_TYPES": ("Bearer",), } ... EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_USE_TLS = True EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") EMAIL_SERVER = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER` -
Collecting static of Swagger UI in django project on server
I setup a Swagger configuration on my Django project for a specific endpoint It worked fully completed on my local machine but when I sent it on server it seems that the static files of drf_yasg cannot be collected and show there were a blank page without any 404 Not Found error, but also on the console it wrote the Js and CSS files are 404 not found swagger.py from drf_yasg import openapi from drf_yasg.views import get_schema_view from django.urls import path from requests_app.views import RequestsVS from rest_framework import permissions single_endpoint_schema_view = get_schema_view( openapi.Info( title="/api/", default_version='v1', description="برای احراز هویت نیاز است تا کلید دریافتی در هدر درخواست ها با عنوان زیر ارسال شود", ), public=True, permission_classes=[permissions.AllowAny], patterns=[path('requests/add/outside/', RequestsVS.as_view({'post': 'create_from_outside'}))], ) swagger_urlpatterns = [ path('swagger/', single_endpoint_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', single_endpoint_schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] urlpatterns = swagger_urlpatterns + [ ] settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' AUTH_USER_MODEL = 'users.User' # Swagger settings SWAGGER_SETTINGS = { 'USE_SESSION_AUTH': False, # Set this to True if you're using session authentication 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header', }, }, } urls.py … -
How to select a Django Plotly dash element in JavaScript?
I have a Django Plotly dash app where I have an HTML structure like this: html.Div( id="search-topics", className="search-topics", children=dcc.Input( id="search-topic-input", type="text", placeholder="search...", debounce=True, className="search-topic-input", ), ), I want to select the search-topics element in JavaScript so that I can manipulate its properties dynamically. However, when I try to select the element using document.getElementById("search-topics, it returns null. Is there a way to select this element in JavaScript and modify its properties? any help or guidance would be greatly appreciated. Thank you! -
Getting "Authentication credentials were not provided." error when making a request to another api endpoint with required auth, on behalf of a user
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) username = serializer.validated_data['username'] password = serializer.validated_data['password'] user = authenticate(request, username=username, password=password) login(request, user) session_id = request.session.session_key csrf_token = get_token(request) request_headers = { 'X-CSRFToken': csrf_token, 'Cookie': f"sessionid={session_id}", } # Url to request mail for email confirmation url_path = reverse('send-mail-confirm-email') full_url = request.scheme + '://' + request.get_host() + url_path requests.get( full_url, headers=request_headers, ) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) Getting "Authentication credentials were not provided." error when making a request to another api endpoint with required authentication, on behalf of a user. I have included cookie with sessionid, and csrf_token in the request headers. It doesn't work either way. -
Install requirements from Django project with VS Code
I try to run and open the development server of a Django project in VS Code, that I created with GidPod IDE. When I open the project in GidPod (where I created it), install the requirements, create an env.py, set the 'SECRET_KEY' variable and I can start the server with python3 manage.py runserver. Then I open the exact same project in VS code, I create a virtual environment and install the requirements from requirements.txt as I did in GidPod with pip3 install -r requirements.txt. If I now try to start the development server, I get the following error: (gh-env) PS C:\Users\SkywalkingTiger\Desktop\git-repos\gfeller-herbs-wf> python3 manage.py runserver Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "C:\Users\SkywalkingTiger\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\functional.py", … -
Django: TypeError: XXX() got multiple values for argument 'chat_id'
I'm using Django with Celery and getting this error: TypeError: get_response() got multiple values for argument 'chat_id' I'm calling the function via: i = get_response.delay(chat_id=chat_id, is_first_message=is_first_message,question=question,user_id=user_id) and the function header is: @shared_task(bind=True) def get_response(chat_id: int, is_first_message: bool, question:str,user_id:int) -> str: I tried running a print(chat_id) but this only confirmed the field was a single integer. Edit. Full trace: [03/Jul/2023 13:52:16] ERROR "django.request" Internal Server Error: /chat/chat/1/283/new_message/ project | Traceback (most recent call last): project | File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner project | response = get_response(request) project | ^^^^^^^^^^^^^^^^^^^^^ project | File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response project | response = wrapped_callback(request, *callback_args, **callback_kwargs) project | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ project | File "/code/apps/chat/views.py", line 82, in new_message project | i = get_response.delay(chat_id=chat_id, is_first_message=is_first_message,question=question,user_id=user_id) project | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ project | File "/usr/local/lib/python3.11/site-packages/celery/app/task.py", line 425, in delay project | return self.apply_async(args, kwargs) project | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ project | File "/usr/local/lib/python3.11/site-packages/celery/app/task.py", line 540, in apply_async project | check_arguments(*(args or ()), **(kwargs or {})) project | TypeError: get_response() got multiple values for argument 'chat_id' project | [03/Jul/2023 13:52:16] ERROR "django.server" "POST /chat/chat/1/283/new_message/ HTTP/1.1" 500 87645 -
Django custom widget: best approach
Django: custom widget I use a material-kit library for django which offers a design for rendering form fields except for selects which is only available in the PRO version. I coded a custom selectpicker widget which renders similar to the selectpicker of the PRO version of material-kit. In a form, I have a lot of "select" fields to render with my selectpicker widget. To limit the repetition of the code I defined a template select_field.html which displays the selectpicker.html of my widget when I insert a field having this widget in my final template using an include. Isn't there a more efficient and/or elegant way to achieve the same result? #model.py dem_sex = models.IntegerField('Sexe', null=True, blank=True) #forms.py dem_sex = forms.TypedChoiceField(widget=Selectpicker(label='Sexe - SELECTPICKER',attrs={'class': ''}),choices=SEX_CHOICES, empty_value=None,required=False) #widget.py from django.forms.widgets import TextInput class Selectpicker(TextInput): template_name = 'widgets/selectpicker.html' def __init__(self, label=None, choices=None, *args, **kwargs): self.choices = choices self.label = label super().__init__(*args, **kwargs) def get_context(self, name, value, attrs=None): context = super().get_context(name, value, attrs) if self.choices: context['choices'] = self.choices if self.label: context['label'] = self.label return context #selectpicker.html {% with css_classes=widget.attrs.class|default:'' %} <div class="row ms-3 me-3"> <div class="col-md-12 selectpicker-div"> <div class="selectpicker"> <div class="label floating-label">{{label}}</div> <input class="textBox hidden" type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value is None … -
Prefetch related not working in django admin
I'm trying to show name of related model in my django admin and i'm using prefetch related but i still got 200+ sql queries how can i solve that? models.py class ObjectList(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) name = models.CharField(max_length=250) sections = models.ManyToManyField('SectionList', default=None, related_name='object_sections', blank=True) class CleanSections(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) name = models.CharField(max_length=120) def __str__(self): return f'{self.name}' class SectionList(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) object = models.ManyToManyField(ObjectList, related_name='sections_object', default=None) clean_sections = models.ForeignKey(CleanSections, to_field='uuid', on_delete=models.CASCADE, null=True, related_name='sections_clean_name') def __str__(self): return f'{self.clean_sections.name}' admin.py class ObjectListAdmin(admin.ModelAdmin): list_display = ('uuid', 'name') list_filter = ('name',) search_fields = ('uuid', 'name') ordering = ('uuid', 'name') fields = ('uuid', 'name', 'sections') def get_queryset(self, request): base_qs = super(ObjectListAdmin, self).get_queryset(request) return base_qs.prefetch_related('sections__clean_sections') -
{% block content %} {% endblock %} displayed as text
I'm going through an online tutorial on python web development: https://www.youtube.com/watch?v=dam0GPOAvVI&list=PL7AeU6Jfo1ue-VZ6SI9x0EOCW2hhGC1l6&index=4&t=2214s However, despite double check all the codes are the same, I can't get visual studio to recognize the {% block content %} {% endblock %} part of the code. The expected output should be only the contents between {% block content %} {% endblock %}, which is none in this case. However, '{% block content %} {% endblock %}' is displayed as text on the web page, which it should not be. And the rest of the codes on other templates did not work as well. It seems that visual studio code does not recognize this syntax, maybe I need to configure some setting for it to work but I can't find it, any help is much appreciated. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" crossorigin="anonymous" /> <title> {% block title %}Home{% endblock %} </title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar"> <span class="navbar-toggler-icon"></span> </button> <div class = "collapse navbar-collapse" id="navbar"> <a class="nav-item nav-link" id="login" href="/login">Login</a> <a class="nav-item nav-link" id="SignUp" href="/sign_up">Sign Up</a> <a class="nav-item nav-link" id="logout" href="/logout">Log Out</a> <a class="nav-item … -
How can I go to homepage from another page in Django? I am unable to exit from last called definition
def save(request,id): if request.method=='POST': if request.POST.get('name'): table=Userdb.objects.get(id=id) table.name=request.POST.get('name') table.url=request.POST.get('url') table.phone=request.POST.get('phone') table.dob=request.POST.get('dob') table.save() #messages.success(request,"record saved successfully") #return redirect('userlist') #return HttpResponseRedirect({%urls 'index'% }) return render(request,"index.html") Here at last part,I have directed to index.html. But actually I am not exited the save definition. please refer next snapshot. The url in webpage dont show index.html but shows save. Also css of index webpage is lost. I tried various urls but didnt work. Also tried to change setings.py still no avail. I want to navigate to home page without trace of any older definition -
how can i fix these error in django admin and veiws files?
i have a problem witch i have a custom User model in my Account app and i just put AUTH_USER_MODEL = 'Account.User' in my setting.py. The problem i have is that when i go on admin panel and click on a user in the Users list and when i want to update or delete it i get an error (This error is not only for the User model and other models that are in the admin panel, i'm not able to delete or update them) IntegrityError at /admin/Account/user/1/delete/ FOREIGN KEY constraint failed IntegrityError at /admin/Account/user/1/change/ FOREIGN KEY constraint failed Also when i want to register a user with my register view it always gives me this error witch i choise it if the user exist in the Users list { "error": "Username has been already used." } The register view class code for checking the email and username: if User.objects.filter(email=email).exists(): return Response(data={"error": "Email has been already used."}, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(username=username).exists(): return Response(data={"error": "Username has been already used."}, status=status.HTTP_400_BAD_REQUEST) My User model: from django.db import models from django.contrib.auth.models import AbstractUser, Group, Permission class User(AbstractUser): id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) full_name = models.CharField(max_length=255, default="") simple_description = models.CharField(max_length=255, default="tourist") biography = models.TextField(null=True, …