Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF bulk insert crashes on serializer.data: too many values to unpack (expected 2)
I have two serializers and I use list_serializer_class for bulk inserts. I use viewset and in my viewset @action(methods=['post'], detail=False, url_path='bulk') def bulk_create(self, request): serializer = self.get_serializer(data=reusables, many=True) ......... self.perform_create(serializer) The data is successfully inserted into the database but when I try to get the data from the serializer headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I get the error: too many values to unpack (expected 2) probably beucase it's trying to decode the data using the first serializer and not the list_serializer_class These are my serializers: class ItemsSerializer(object, serializers.ListSerializer, serializers.ModelSerializer): name = serializers.CharField(source='display_name', max_length=90) def update(self, instance, validated_data): pass def create(self, validated_data): items = [Item(**item) for item in validated_data] return Item.objects.bulk_create(items) class Meta: model = Item fields = ('id', 'displayName', 'content', 'creationDate', 'modificationDate', 'ownerName', 'site', 'lastEditorName', 'uuid') class ItemSerializer(object, serializers.ModelSerializer): name = serializers.CharField(source='display_name', max_length=90) class Meta: list_serializer_class = ItemsSerializer model = ReusableBlock fields = ('id', 'name') -
How to resolve: ModuleNotFoundError: No module named 'leadsagents' in Django
I know the is a lot of similar questions but I've tried different solutions from stack overflow, the web and YouTube. This happened after making migrations to my db.sqlite3 file it worked until I tried adding new agents. Any help will be appreciated. Also I don't even know which files to upload because the is no module names leadsagent in my project. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'leadsagents'``` Will be happy to share requested files you might need to help me solve my error. -
How to connect django allauth socials to frontend?
I managed to setup allauth for github authentication but I dont know how to connect it properly to my frontend so I can login through frontend and fetch needed data for displayment. I tried many things. Currently I have managed to make it so when I login, I get redirected to a json page full of login data needed for frontend but still cant find a proper way to connect it. -
Tpye hints for mixins that reference attributes of a third-party base class
I'm trying to add type hints to a mixin class that is to be used alongside an external, third-party class. That is, the mixin relies on members of the third-party class. For example, a mixin for a Django form: # mixin_typing.py from django import forms class SuffixFormMixin: suffix: str def add_suffix(self, field_name: str) -> str: # prefix is an attribute of forms.Form return f"{self.prefix}__{field_name}__{self.suffix}" class SuffixForm(SuffixFormMixin, forms.Form): pass Understandably, mypy will complain about the add_suffix method: "SuffixFormMixin" has no attribute "prefix" IDE (PyCharm) will also throw a warning: Unresolved attribute reference 'prefix' for class 'SuffixFormMixin' Question: Is there any "easy" solution that lets the mixin understand that self contains attributes/methods of forms.Form? Here is a github issue that addresses this, but sadly didn't go anywhere: https://github.com/python/typing/issues/246 Maybe some kind of typing object or other mypy-fu that acts as a promise to the mixin class that the future "partner class" has the members that the mixin is using? Attempted solutions The suggestions I have found so far all have drawbacks: Type-hinting self to the partner class (works for mypy: ✅, doesn't work for IDE: ❌) I have seen suggestions to type hint self to the class that the mixin will later … -
Why are multiple bootstrap modals being rendered after HTMX hx-get?
I have a Django page using HTMX to populate some bootstrap styled tabs (Members, Events and Contacts). 'hx-get' is used to load the desired page content into the DOM. On the Members page, I have a button that opens a bootstrap modal form when clicked for the user to add a member. The issue is that the number of times the modal is rendered to the DOM when the button is clicked corresponds to the number of times the Members content is loaded. If the Members page is rendered twice (navigating from Members tab to Events tab, then back to Members), two modals appear in the DOM and so on. I initially thought it may be caused by the modal form also being rendered with hx-get. However, I've replaced the modal form with a basic modal on the same page and the issue persists. Why is only the modal being rendered multiple times? The members page is only being rendered once. Tabs code: <div class="container"> <div class="row"> <div class="nav flex-column nav-pills me-3 col" role="tablist" aria-orientation="vertical" id="tabs" hx-target="#tab-contents" _="on htmx:afterOnLoad take .active for event.target"> <button type="button" id="members-btn" role="tab" aria-controls="tab-contents" aria- selected="true" hx-get="{% url 'members' %}" class="nav-link active"> Members </button> <button type="button" … -
django "import excel to database" libraries
I need to do "import excel to database" using django. I know that some of the libraries that help are "django-import-export", "openpyxl", and others are "pandas", "xlrd", etc. What is the difference between these libraries? Which library is right for what I'm trying to do? -
Django CSRF protection for cross site post requests
I am using react as frontend and using django for backend. When I host both the frontend and backend on localhost, everything works fine and X-CSRFTOKEN is sent perfectly. const instance = axios.create({ withCredentials: true, withXSRFToken: true, xsrfHeaderName : 'X-CSRFTOKEN', xsrfCookieName : 'csrftoken' }); My DJango settings are (taken from this answer Django - check cookies's "SameSite" attribute): CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" SESSION_COOKIE_SAMESITE = "None" but when my frontend (firebase )and backend(eks aws) are hosted on different subdomains, I receive a 403 Forbidden Error. It should return a 201 ccreated response but instead it is returning a 403 error, CSRF verification failed. Request aborted. -
'Serverless Function Exceeded 250 MB' Error on Vercel Django Deployment?
I have this issue (" A Serverless Function has exceeded the unzipped maximum size of 250 MB. : https://vercel.link/serverless-function-size") when i'm trying to deploy to Vercel, I tried to remove as much as possible of non-needed packages but nothing changed, this is my installed packages from vercel: Successfully installed Django-4.2.3 MarkupPy-1.14 MarkupSafe-2.1.3 Pillow-10.0.0 PyJWT-2.8.0 PyYAML-6.0.1 Pygments-2.15.1 Unidecode-1.3.6 Werkzeug-2.3.6 amqp-5.1.1 asgiref-3.7.2 asttokens-2.2.1 backcall-0.2.0 billiard-4.1.0 certifi-2023.5.7 cffi-1.15.1 chardet-3.0.4 charset-normalizer-3.2.0 click-8.1.6 click-didyoumean-0.3.0 click-plugins-1.1.1 click-repl-0.3.0 colorama-0.4.6 crispy-bootstrap5-0.7 cryptography-41.0.2 cssselect2-0.7.0 decorator-5.1.1 defusedxml-0.7.1 diff-match-patch-20230430 django-admin-honeypot-1.1.0 django-allauth-0.54.0 django-appconf-1.0.5 django-bulk-update-or-create-0.3.0 django-categories-1.9.2 django-ckeditor-6.6.1 django-components-0.35 django-compressor-4.4 django-constance-2.9.1 django-crispy-forms-2.0 django-debug-toolbar-4.1.0 django-decorator-include-3.0 django-etc-1.4.0 django-filer-3.0.4 django-filter-23.2 django-grip-3.4.0 django-hitcount-1.3.5 django-htmx-1.16.0 django-import-export-3.2.0 django-ipware-5.0.0 django-jazzmin-2.6.0 django-js-asset-2.1.0 django-maintenance-mode-0.18.0 django-modeltranslation-0.18.11 django-mptt-0.14.0 django-ninja-0.22.2 django-picklefield-3.1 django-polymorphic-3.1.0 django-qsstats-magic-1.1.0 django-robots-5.0 django-rosetta-0.9.9 django-select2-8.1.2 django-shortcuts-1.6 django-split-settings-1.2.0 django-sql-explorer-3.2.1 django-widget-tweaks-1.4.12 easy-thumbnails-2.8.5 et-xmlfile-1.1.0 executing-1.2.0 gripcontrol-4.2.0 gunicorn-21.2.0 h11-0.9.0 h2-3.2.0 hpack-3.0.0 hstspreload-2023.1.1 html2text-2020.1.16 httpcore-0.9.1 httpx-0.13.3 hyperframe-5.2.0 idna-2.10 install-1.3.5 ipython-8.12.2 jedi-0.18.2 kombu-5.3.1 ldif3-3.1.1 lxml-4.9.3 matplotlib-inline-0.1.6 oauthlib-3.2.2 odfpy-1.4.1 openpyxl-3.1.2 packaging-23.2 parso-0.8.3 pexpect-4.9.0 pickleshare-0.7.5 polib-1.2.0 prompt-toolkit-3.0.39 psycopg2-binary-2.9.9 ptyprocess-0.7.0 pubcontrol-3.5.0 pure-eval-0.2.2 pycparser-2.21 pydantic-1.10.11 python-card-me-0.9.3 python-dateutil-2.8.2 python-dotenv-1.0.1 python-fsutil-0.10.0 python3-openid-3.2.0 pytz-2023.3 rcssmin-1.1.1 reportlab-4.0.4 requests-2.31.0 requests-oauthlib-1.3.1 rfc3986-1.5.0 rjsmin-1.2.1 six-1.16.0 sniffio-1.3.0 sorl-thumbnail-12.9.0 sqlparse-0.4.4 stack-data-0.6.2 svglib-1.5.1 tablib-3.5.0 tinycss2-1.2.1 toposort-1.10 traitlets-5.9.0 typing_extensions-4.7.1 tzdata-2023.3 tzlocal-5.0.1 ua-parser-0.18.0 unicode-slugify-0.1.5 unicodecsv-0.14.1 urllib3-1.26.6 user-agents-2.2.0 vine-5.0.0 wcwidth-0.2.6 webencodings-0.5.1 whitenoise-6.6.0 xlrd-2.0.1 xlwt-1.3.0 I removed as much as possible of non-needed packages but nothing changed, i also … -
How to properly use get_or_create in a django serializer and avoid 'already exists' error?
I have the following django models, serializer and viewset. class Article(AbstractBaseModel): manufacturer = models.ForeignKey( Manufacturer, on_delete=models.CASCADE, null=True, blank=True ) provider1 = models.ForeignKey( Provider, on_delete=models.CASCADE, null=True, blank=True, ) def get_absolute_url(self): return reverse( "smt_management_app:article-detail", kwargs={"name": self.name} ) class Manufacturer(models.Model): name = models.CharField( primary_key=True, max_length=50, null=False, blank=False ) def get_absolute_url(self): return reverse( "smt_management_app:manufacturer-detail", kwargs={"name": self.name} ) class Provider(models.Model): name = models.CharField( primary_key=True, max_length=50, null=False, blank=False ) def get_absolute_url(self): return reverse("smt_management_app:provider-detail", kwargs={"name": self.name}) class ArticleSerializer(serializers.ModelSerializer): manufacturer = ManufacturerSerializer(required=False, allow_null=True) provider1 = ProviderSerializer(required=False, allow_null=True) class Meta: model = Article fields = [ "name", "manufacturer", "provider1", ] def create(self, validated_data): manufacturer_data = validated_data.pop("manufacturer", None) if manufacturer_data: manufacturer, _ = Manufacturer.objects.get_or_create( name=manufacturer_data["name"] ) validated_data["manufacturer"] = manufacturer provider1_data = validated_data.pop("provider1", None) if provider1_data: provider1, _= Provider.objects.get_or_create( name=provider1_data["name"] ) validated_data["provider1"] = provider1 article = Article.objects.create(**validated_data) return article class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, ) filterset_class = ArticleFilter ordering_fields = "__all__" When posting a new article I encounter an unexpected behavior. The manufacturer and provider in the following example do both exist but only the provider causes an error. POST body: {"name":"article1","manufacturer":{"name":"123"},"provider1":{"name":"abc"}} ERROR body: {"provider1":{"name":["provider with this name already exists."]}} Why does it happen if everything is exactly the same for Manufacturer … -
Problem with redis/celery, why do some tasks triggers an Errno 111 but others don't?
I am currently building a web app with django. I am using redis and celery to send emails for various purposes. I have a background worker checking my db for mails to send every 5s (very short for testing purposes),if it finds mails flagged as unsent, then it sends them, this part works as intended. However when I call the same method directly from one of my views (to send an email for account creation), I have an Errno 111. Here's my celery.py file: import os from celery import Celery from celery.signals import after_setup_logger import logging.config from inscriptionsIff import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inscriptionsIff.settings') app = Celery('inscriptionsIff') app.config_from_object('django.conf:settings', namespace='CELERY') @after_setup_logger.connect def setup_loggers(logger, *args, **kwargs): logging.config.dictConfig(settings.LOGGING) app.conf.beat_schedule = { 'send-emails-every-x-seconds': { 'task': 'inscriptionsIff.tasks.process_and_send_emails', 'schedule': 5, # Replace 'x' with the number of seconds }, } app.autodiscover_tasks() Here's my tasks.py file: from celery import shared_task from django.core.mail import send_mail from .models import Submission from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site import hashlib from django.conf import settings @shared_task def send_email_task(email, subject, message): send_mail( subject, message, 'yourgmailaddress@gmail.com', [email], fail_silently=False, ) def hash_input(input_to_hash): # Use Django's SECRET_KEY to add a layer of unpredictability to the hash salted_id = str(input_to_hash) + settings.SECRET_KEY return hashlib.sha256(salted_id.encode()).hexdigest() @shared_task def process_and_send_emails(): … -
Errors in form with ModelForm
I'm not good in English I want to have a login page, I use ModelForm and LoginView. when I want to see the page I got this error: BaseModelForm.__init__() got an unexpected keyword argument 'request' and when I don't use the Form, always return to the same page. I checked the request.method, it's GET! here is my form: class LoginForm(ModelForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) class Meta: model = User fields = ['username', 'password'] view: class Login(LoginView): form_class = LoginForm template_name = 'account/login.html' def get_success_url(self): return reverse_lazy('account:home') and login.html <form action="{% url 'account:home' %}" method="post"> {% csrf_token %} <div class="input-group mb-3"> <input id="username" type="text" class="form-control" placeholder="Username"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input id="password" type="password" class="form-control" placeholder="Password"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <!-- /.col --> <div class="col-12"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div> <!-- /.col --> </div> </form> when I use my form(with function view), my browser don't suggest my saved logins. -
How to define extra dynamic field based on Foreign Key model field in django
I am trying to make extra display field in form that used to take value based on changing the related table field. suppose model.py # Create model.py class MyModel(models.Model): name = models.CharField() model2 = models.ForeignKey(MyModel2) class MyModel2(models.Model): name = models.CharField() description = models.CharField() forms.py # Create forms.py class MyForm(forms.ModelForm): extraField = forms.CharField(disabled=True) class Meta: model = MyModel field = '__all__' In this particular extraField. I need to related this field with model2.description value. Is there any way to do this. -
Errno 111 Connection refused: Issue with rendering PDF with xhtml2pdf in Django on a Linux server with static files images
I've successfully deployed my Django project on a Linux server, but I'm encountering an issue when trying to print PDF reports. The images located in the static folder are causing errors during the rendering process. <img class="logo" src="http://{{host}}/static/logo_1.jpeg"> enter image description here It's worth noting that I can access these images through their respective URLs, but I'm getting a connection refused error with xhtml2pdf. I'm curious if there might be some Apache2 configuration settings that I may have overlooked that could be causing this connection issue in the context of xhtml2pdf. Any insights or guidance on potential Apache2 configurations would be greatly appreciated. My goal is to determine if there's any permission or configuration issue with Django URLs that I might have overlooked. What doesn't make much sense to me is that I can view the images through the URL, but they can't be rendered in a PDF. Does this library use a different type of connection when importing images for PDF rendering? -
How to get status code for all urls in Django app
Есть ли возможность в Django 5.0 получить все ответы сервера для url адресов зарегистрированных в приложении? Или возможность передать url адрес и получить код ответа, но для уже авторизованного пользователя. Я пробовала использовать библиотеку requests. Без авторизации код ответа не является валидным, т.к в моем приложении все url адреа доступны только после авторизации. В зависимости от назначенных бизнес ролей, разным пользователям доступны разные url адреса. Я бы хотела иметь возможность заранее сформировать список доступных url адресов для авторизованного пользователя. Для авторизации и аутентификации используется Active Directory по протолку LDAP и в самом приложении нет паролей пользователя. -
DJango - File Upload - read - process & download
need your help!!! I am trying to create a web app where user will upload the pdf files > read files > process it > write in excel > then auto download in users system. Please do help with the code i am using py3.12 & django5 thanks in advance. code for above isseu -
Need help to add image functionality to my django project 🙏🙏
I made this project 2 years ago, and now i want to submit this as a final year project now can only do text messages so I want to add image sharing functionality and i haven't used django from long time can someone help me with it. this is like discord where we can create different rooms based on various topic, people and sign up and login, etc., first you will need to create a Create SuperUser using - python manage.py createsuperuser https://github.com/rhutik123/StudyBud i am a beginner in django so i never worked with images in django. I want to add image sharing functionality to room chat page. -
Django: Refrain from refreshing input fields after an error occured
I created a pre-registration form for users, and every time I entered the wrong captcha, the page was refreshed. The form has number of input fields, and I don't want the user to input their information again. How do I refrain it from refreshing? Here is my pre registration function. views.py def preRegistration(request): form = MyForm(request.POST) if request.method == 'GET': random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8)) refno = f"{random_chars}" return render(request, 'registration_form.html', {"refno": refno, "form": form}) if request.method == 'POST': studentId = request.POST.get('studentId') ... if form.is_valid(): Applicant.objects.create(studentId=studentId,...,refno=refno) messages.success(request, f'{refno}') return redirect('/registration/') else: messages.error(request, 'Wrong Captcha!') return redirect('/registration/') Pre-registration form. registration_form.html <div>Ref no:<input type="text" name="refno" value="{{ refno }}" id="refno" readonly> <div><input type="text" name="studentId"></div> ... <div>{{ form.captcha }}</div> -
How to resolve "ModuleNotFoundError: No module named 'storages.backends.azure_storage'"
I have a django app and I have the module: django-storages[azure] installed with the command: pip install django-storages[azure] And now I try to run the collectstatic command. But if I enter the command: python manage.py collectstatic I get this error: File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\core\files\storage\handler.py", line 35, in __getitem__ return self._storages[alias] ~~~~~~~~~~~~~~^^^^^^^ KeyError: 'staticfiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\core\files\storage\handler.py", line 52, in create_storage storage_cls = import_string(backend) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1381, in _gcd_import File "<frozen importlib._bootstrap>", line 1354, in _find_and_load File "<frozen importlib._bootstrap>", line 1325, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 929, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "C:\Users\USER\Desktop\Riley\lost-and-found-system\storages\backends\custom_azure.py", line 1, in <module> from storages.backends.azure_storage import AzureStorage ModuleNotFoundError: No module named 'storages.backends.azure_storage' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\USER\Desktop\Riley\lost-and-found-system\manage.py", line 22, in <module> main() File "C:\Users\USER\Desktop\Riley\lost-and-found-system\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\USER\Desktop\Riley\lost-and-found-system\shadow\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() … -
How to use '[' or ']' for the file name of upload_to in Django filefield
I'm trying to put the file name that includes '[' and ']' in the Django model. Examples include: [Test] Test.pdf However, the actual locally saved file names are as follows: Test.pdf Problems occur when importing files via file name because '[' and ']' are saved as removed. models.py: def evidence_directory_path(instance, filename): return f'{instance.user_uuid}/Evidence/{slugify(instance.product)}/{filename}' class Evidence(models.Model): user_uuid = models.CharField(max_length=50) title = models.CharField(max_length=200) product = models.CharField(max_length=500) uploadedFile = models.FileField(upload_to=evidence_directory_path) dateTimeOfUpload = models.DateTimeField(auto_now=True) The output of the following functions is as follows: def evidence_directory_path(instance, filename): print(filename) return f'{instance.user_uuid}/Evidence/{slugify(instance.product)}/{filename}' [Test]Test.pdf However, the actual file name saved is as follows: TestTest.pdf What kind of mistake am I making? I have no idea. -
Django models with hard coded model fields in filtersets
This question is about filtering. But to explain here is some supporting facts... There is a concept in my program of objects being virtual or not virtual. Using rest_framework I have two models in my models.py: So to do that I have tried: class ModelA(models.Model): @property def is_virtual(self): return False class ModelB(ModelA): @property def is_virtual(self): return True So ModelB inherits ModelA. And ALL ModelA objects are NOT virtual, and ALL ModelB objects ARE virtual. Instead of adding this to the database where the column is always True for ModelAs and False for ModelBs I would like to hardcode it in the model class and supporting classes. In my serializers.py I have: class ModelSerializer(serializers.ModelSerializer): is_virtual = serializers.SerializerMethodField() def get_is_virtual(self, obj): return obj.is_virtual All this above basically works UNTIL I want to filter search on is_virtual. In my filters.py: class ModelFilterSet(filters.FilterSet): is_virtual = filters.BooleanFilter(method='filter_is_virtual') def filter_is_virtual(self, queryset, name, value): if value: return queryset.filter(is_virtual=True) else: return queryset.filter(is_virtual=False) Then when I GET http://localhost:8080/api/modela/?is_virtual=false I get: Internal Server Error: /api/modela/ Traceback (most recent call last): File "D:\projects\my_app\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\projects\my_app\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\projects\my_app\venv\lib\site-packages\django\views\decorators\csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) … -
Django AdminSite overrides admin template
I tried to complete Django tutorial and it says that you can override Django's templates with providing example on how to change title of admin page (here). When I tried, nothing changed, so I went to google and investigate. My project structure currently looks like this (django_trial is my project's name): - django_trial/ - django_trial/ - polls/ - ... - templates/ - admin/ - base_site.html (copy of template from Django with modified title) - base_site.html (copy of admin/base_site.html from above, just in case) - venv I tried to see what template it loads, so I put code below in my polls/admin.py from django.template.loader import get_template a = get_template("admin/base_site.html") print(repr(a.origin)) and it printed <Origin name='/home/my_username/Projects/django_trial/templates/admin/base_site.html'>, so my template override seems to work somewhat correctly. Then I tried modifying actual library files and changing original .../venv/lib/python3.10/site-packages/django/contrib/admin/templates/admin/base_site.html didn't do anything as well. In the end, I managed to change admin page title when I modified .../venv/lib/python3.10/site-packages/django/contrib/admin/sites.py. There is a class AdminSite and it has the line site_header = gettext_lazy("Django administration") Seems it has top priority, so its modification actually changed admin page title. What could I do wrong so this line always take priority? -
My models are not showing in Django Admin after OTP Token implementation
I wanted to secure my Django Admin so I followed the steps in here and I implemented django-otp to the my website. The token works fine. I can login my admin page safely but my models doesn't show up in my admin page. For example: Before the OTP Implementation I was able to post a new blog or something but now I cant at all. There are nothing about blogs in my admin. I am logging as a superuser and I tried to create another superuser and logging but it didn't change. I think this error might be caused by the admin.py file configurations, but I'm not sure. Here is my urls.py from django.contrib import admin from django.urls import path, include, re_path from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns # new from django.conf import settings from django.views.static import serve from django.contrib.auth.models import User from django_otp.admin import OTPAdminSite from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.admin import TOTPDeviceAdmin class OTPAdmin(OTPAdminSite): pass admin_site = OTPAdmin(name='OTPAdmin') admin_site.register(User) admin_site.register(TOTPDevice, TOTPDeviceAdmin) urlpatterns = [ path('admin/', admin_site.urls), path('', include('pages.urls')), path('', include('portfolio.urls')), path('', include('services.urls')), path('', include('blog.urls')), re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}), ] Here is an example of my admin.py from django.contrib … -
How to properly scope validator function in parent class for use in child class
I'm trying to use validators, but I'm having a mysterious issue with using validators in a parent/child class. Right now I've created a base class for all media in my project; all media in this model need a name and a thumbnail: class BaseMedia(BaseModel): def validate_thumbnail(image_obj): validate_image_file_extension(image_obj) dimensions = [image_obj.width, image_obj.height] if dimensions[0] != 400 or dimensions[1] != 400: raise ValidationError( "Thumbnail dimensions must be 400 x 400; uploaded image is %s x %s" % (dimensions[0], dimensions[1]) ) media_title = models.CharField( max_length=25, verbose_name="Title (25 char)", null=True ) thumbnail = models.ImageField( null=True, verbose_name="Thumbnail (400 x 400 px)", upload_to="microscopy/images/thumbnails", validators=([validate_thumbnail],), ) and then I have a child class that inherits and implement the core media itself; for example: class MicroscopyMedia(BaseMedia): def validate_image(image_obj): validate_image_file_extension(image_obj) dimensions = [image_obj.width, image_obj.height] if dimensions[0] != 1920 or dimensions[1] != 1070: raise ValidationError( "Image dimensions must be 1920 x 1070; uploaded image is %s x %s" % (dimensions[0], dimensions[1]) ) media = models.ImageField( null=True, verbose_name="Media (1920 x 1070 px)", blank=True, upload_to="microscopy/images", validators=[validate_image], ) The idea being that all models will need a thumbnail, but within the child class I have a specific validator for each individual media type. However, when I try to make this migration, I get … -
django-registration class overriding
Because I need to add a captcha(django-recaptcha) to the registration form I want to override the RegistrationForm class from the django-registration module. I am using: django-registration==3.3 django==4.1 python(3.10) I've tried some options has shown below. forms.py from django_registration.forms import RegistrationForm class MyRegistrationForm(RegistrationForm): age = forms.IntegerField() class Meta(RegistrationForm.Meta): fields = RegistrationForm.Meta.fields + ['age'] urls.py from .forms import MyRegistrationForm from django_registration.backends.activation.views import RegistrationView path('accounts/register/', RegistrationView.as_view(form_class=MyRegistrationForm), name='registration_register') registration_form.html <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Submit' %}" /> </form> Nothing overrides the form. I don't understand why. Same thing for the RegistrationView. I can't override it for some reason. I've been arround these for a while now. Probably am missing something obvious by now. Help is appreciated. Thank you. -
How to get items stacked in a row together in a column thats col-3
I am trying to stack all the items under one another if there is more than one. I am using Django and currently its reproducing a new col-3 for each new item. I have tried bootstrap d-flex flex-wrap, however this is not working. <div class="col-12 col-lg-6"> <p>Order History</p> {% for order in orders %} <div class="row"> <div class="col-3"> <p>Date:</p> </div> <div class="col-3"> <p>Grand Total:</p> </div> <div class="col-3"> <p>Order Number:</p> </div> <div class="col-3"> <p>Items:</p> </div> </div> <div> <div class="row"> <div class="col-3"> <p><strong>{{ order.date }}</strong></p> </div> <div class="col-3"> <p><strong>&euro;{{ order.grand_total | floatformat:2 }}</strong></p> </div> <div class="col-3"> <a href="{% url 'order_history' order.order_number %}" title="{{ order.order_number }}"> {{ order.order_number|truncatechars:8 }} </a> </div> {% for item in order.lineitems.all %} <div class="col-3"> <p><strong>{{ item.product.name }} x {{ item.quantity }}</strong></p> </div> {% endfor %} </div> {% endfor %} </div> </div> The picture contains the current output. What I am trying to achieve is a list of items under each other.