Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to process the input data from ModelMultipleChoiceField in Django
I've been trying to process the data captured from a simple Django Model Form, and for some reason, it isn't possible to access the group of items selected under ModelMultipleChoiceField. I'm only able to access only one item from the selected items in the form. The Model: class Student(models.Model): name = models.CharField(max_length=80) subjects = models.ManyToManyField(Subject) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name="students_of_house") The Model form: class AddStudentForm(forms.Form): name = forms.CharField(label="Full Name") house = ModelChoiceField(queryset=House.objects.all()) subjects = ModelMultipleChoiceField(queryset=Subject.objects.all()) The view function to process POST and create a Student Object.: def add_student(request): if request.method == "POST": name = request.POST["name"] house = House.objects.get(id=int(request.POST["house"])) subject_ids = request.POST["subjects"] new_student = Student(name=name, house=house) new_student.save() for sub_id in subject_ids: new_student.subjects.add(Subject.objects.get(id=int(sub_id)) new_student.save() return HttpResponseRedirect(reverse("administration:students")) context = { "add_student_form": AddStudentForm(), } return render(request, "administration/add_student.html", context) Now, I later tried using form = AddStudentForm(request.POST) and if form.is_valid(): route, which made it work successfully. But I'm having a hard time figuring out the reason why the above method isn't working. The code which worked: def add_student(request): if request.method == "POST": form = AddStudentForm(request.POST) if form.is_valid(): name = form.cleaned_data["name"] house = form.cleaned_data["house"] subject_ids = form.cleaned_data["subjects"] new_student = Student(name=name, house=house) new_student.save() for sub_id in subject_ids: new_student.subjects.add(Subject.objects.get(id=sub_id.id)) new_student.save() return HttpResponseRedirect(reverse("administration:students")) context = { "add_student_form": AddStudentForm(), } … -
Django Allauth headless Unauthorized 401 (Initial)
I'm receiving 401 when trying to reach the end point "/_allauth/browser/v1/auth/password/reset", althoug sending cookie, crsf and the key for email reseting. I'm following the flow of reseting the users password from a vuejs Frontend with this: async function sendEmailReset() { spin.value = true; try { const resp = await api.get("/api/email-reset/" + email.value); if (resp.data.status == "none") { error_message.value = "Este e-mail não existe no sistema. Faça o processo de registro novamente."; wrongCredentials.value = true; return; } else if (resp.data.status == "social") { error_message.value = "Este email foi cadastrado com uma conta social. Faça login com o Google."; wrongCredentials.value = true; return; } else { const response = await api.post( "/\_allauth/" + authClient + "/v1/auth/password/request", { email: email.value }, { headers: { "Content-Type": "application/json" }, } ); console.log(response); if (response.data.status == 200) { sentEmail.value = true; } else { error_message.value = "Ocorreu um erro ao enviar o e-mail. Verifique se o e-mail está correto."; wrongCredentials.value = true; } } } catch (error) { console.error(error); error_message.value = error.response?.data.detail || "Ocorreu um erro na conexão com o servidor. Se persistir, tente novamente mais tarde."; wrongCredentials.value = true; } finally { spin.value = false; email.value = ""; } } it works fine and send … -
Django custom admin template view problem
I changed the admin site index template in Django like this: admin.site.index_template = "admin/list-aprovals.html" but how can i send my model datas this page or can i add a custom view for this url: path('admin/', admin.site.urls), So, I want to work with the existing django admin, but I only want to change the template and see my models in this special template, but with the original admin app. Is this possible in Django? How do I solve this problem? I tried custom app but i want to use original contrib admin. -
How to add data to Django's database by the click of a button using JS
I'm trying to add this data on database when it's clicked. It updates on my website which is static. But the data in not updating on the Database. Showing list From database on index.html <ul id="myUL"> {% for name in names %} {% if name.com == True %} <li class="checked">{{name.names}}</li> {% else %} <li>{{name.names}}</li> {% endif %} {% endfor %} </ul> JavaScript code on index.html. I want to make it like if I click on the button then the the data will be added in the database. Then if i Refresh it The new task which I've implemented. It'll show. Also When the on of the item is checked it will be updated which is true or false. When I check one of the tasks it'll automatically update the database. // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); // Create a new list item when clicking on the "Add" button function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("You must write something!"); } else { document.getElementById("myUL").appendChild(li); } document.getElementById("myInput").value … -
Django Template Inheritance Issue: {% if %} Block Not Rendering When Extending base.html
Problem Description I'm working on a Django project where I have a form that, when submitted, calculates some results and displays them on the same page. The issue arises when I use a base template (base.html). Without using base.html, everything works perfectly, and the results are displayed correctly. However, when I extend from base.html, the content within the {% if results %}{% endif %} block in my test.html template doesn't get displayed at all. base.html Here is my base.html: <!DOCTYPE html> <html> <head> <title>{% block title %}AbiturTest{% endblock %}</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'main/css/style.css' %}"> <link rel="icon" type="image/x-icon" href="{% static 'main/img/icon.ico' %}"> <link rel="apple-touch-icon" href="{% static 'main/img/icon.png' %}"> <link rel="shortcut icon" href="{% static 'main/img/icon.ico' %}"> </head> <body> <header> <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'test' %}">Test</a></li> </ul> </nav> </header> <div class="container"> {% block content %}{% endblock %} </div> </body> </html> test.html Here is my test.html: {% extends 'main/base.html' %} {% block title %}Test - AbiturTest{% endblock %} {% block content %} <h1>Тест AbiturTest</h1> <form id="test-form" method="post"> {% csrf_token %} <ul> {% for question in questions %} <li>{{ question.text }} <div class="radio-buttons"> <input type="radio" id="q{{ question.id }}_1" class="radio-button" name="answer_{{ question.id }}" value="1" … -
aws app running django static s3 url missing colon wrong url
this is my first post and i was to highlight a problenm that i've struggled with for a whole day. While configuring my django project by recovering the static files from an s3 bucket i've ended up with a problem, the url prefixed in fron of the static resources was generating without : after the protocol, like this: <link rel="shortcut icon" type="image/png" href="https//django-examplebucketname.s3.amazonaws.com/static/images/favicon.png"> so at the css, js and all the other static resources were giving 404. in the tamplate i had: {% load static %} and the settings file instead was configured like that: WS_ACCESS_KEY_ID = "myid" AWS_SECRET_ACCESS_KEY = "mykey" AWS_STORAGE_BUCKET_NAME = "django-examplebucketname" AWS_S3_REGION_NAME = "my-region" AWS_S3_CUSTOM_DOMAIN = "django-examplebucketname.s3.amazonaws.com" AWS_S3_URL_PROTOCOL = "https" AWS_S3_USE_SSL = True AWS_S3_VERIFY = True AWS_LOCATION = "static/" STATIC_URL = "https://django-examplebucketname.s3.amazonaws.com/static/" STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" but the static url was not taken in consideration and once released over apprunning the url was always missing the : (colon) after the protocol no other configurations were applied over the project. With the local setting and whitenoise was working. I've checked: the policy on the bucket --> they were ok (trying to connect directly to a resource via the bucket url was reachable) changing the static_url manually override the static … -
Pygame in django
I'm trying to make an online game using Django, but having some trouble: Here is my game code in py/main.py import pygame import sys def main(): pygame.init() screen = pygame.display.set_mode((50, 50)) pygame.display.set_caption("Test") while True: screen.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() pygame.display.update() When I run server, it said " no module name 'pygame' " After that, i tried to "py -m pip install pygame" but it said: already have enter image description here Then how can I import pygame in Django? -
How the PrivateFileField handles validators in django?
class AbstractFirmwareImage(TimeStampedEditableModel): build = models.ForeignKey(get_model_name('Build'), on_delete=models.CASCADE) file = PrivateFileField( 'File', upload_to=get_build_directory, max_file_size=app_settings.MAX_FILE_SIZE, storage=app_settings.PRIVATE_STORAGE_INSTANCE, max_length=255, validators=[MaxLengthValidator(255)], ) type = models.CharField( blank=True, max_length=128, choices=FIRMWARE_IMAGE_TYPE_CHOICES, help_text=_( 'firmware image type: model or ' 'architecture. Leave blank to attempt ' 'determining automatically' ), ) I want to increase the limit of file name length to 255 and it is implemented correctly that I know as I have checked it multiple times on my local serverand my server. But when I test it for a bigger filename, the tests pass without showing an error? Why is it so? def test_filename_within_limit(self, **kwargs): org = kwargs.pop('organization', self._get_org()) category = kwargs.pop('category', self._get_category(organization=org)) build1 = self._create_build(category=category, version='0.1') file = SimpleUploadedFile('a' * 74763, b'') image = self._create_firmware_image( build=build1, type=self.TPLINK_4300_IMAGE, file=file ) image.full_clean() def test_filename_exceeds_limit(self): file = SimpleUploadedFile('a' * 300, b'') image = FirmwareImage(file=file) with self.assertRaises(ValidationError): image.full_clean() def _create_build(self, **kwargs): opts = dict(version='0.1') opts.update(kwargs) category_opts = {} if 'organization' in opts: category_opts = {'organization': opts.pop('organization')} if 'category' not in opts: opts['category'] = self._get_category(**category_opts) b = Build(**opts) b.full_clean() b.save() return b def _create_firmware_image(self, **kwargs): opts = dict(type=self.TPLINK_4300_IMAGE) opts.update(kwargs) build_opts = {} if 'organization' in opts: build_opts['organization'] = opts.pop('organization') if 'build' not in opts: opts['build'] = self._get_build(**build_opts) if 'file' not in opts: opts['file'] = … -
Python 3.12 Sentry-sdk AttributeError: module 'collections' has no attribute 'MutableMapping'
I tried to use sentry-sdk latest version with Python 3.12, but when I run my django app, it shows me following error: AttributeError: module 'collections' has no attribute 'MutableMapping' Full trace as follows: File "/usr/local/lib/python3.12/site-packages/sentry_sdk/__init__.py", line 1, in <module> from sentry_sdk.hub import Hub, init File "/usr/local/lib/python3.12/site-packages/sentry_sdk/hub.py", line 5, in <module> from sentry_sdk.scope import Scope, _ScopeManager File "/usr/local/lib/python3.12/site-packages/sentry_sdk/scope.py", line 11, in <module> from sentry_sdk.attachments import Attachment File "/usr/local/lib/python3.12/site-packages/sentry_sdk/attachments.py", line 5, in <module> from sentry_sdk.envelope import Item, PayloadRef File "/usr/local/lib/python3.12/site-packages/sentry_sdk/envelope.py", line 6, in <module> from sentry_sdk.session import Session File "/usr/local/lib/python3.12/site-packages/sentry_sdk/session.py", line 5, in <module> from sentry_sdk.utils import format_timestamp File "/usr/local/lib/python3.12/site-packages/sentry_sdk/utils.py", line 1302, in <module> HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars() ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/sentry_sdk/utils.py", line 1272, in _get_contextvars if not _is_contextvars_broken(): ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/sentry_sdk/utils.py", line 1213, in _is_contextvars_broken from eventlet.patcher import is_monkey_patched # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/__init__.py", line 6, in <module> from eventlet import convenience File "/usr/local/lib/python3.12/site-packages/eventlet/convenience.py", line 7, in <module> from eventlet.green import socket File "/usr/local/lib/python3.12/site-packages/eventlet/green/socket.py", line 21, in <module> from eventlet.support import greendns File "/usr/local/lib/python3.12/site-packages/eventlet/support/greendns.py", line 78, in <module> setattr(dns, pkg, import_patched('dns.' + pkg)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/support/greendns.py", line 60, in import_patched return patcher.import_patched(module_name, **modules) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/patcher.py", line 132, in import_patched return inject( ^^^^^^^ File "/usr/local/lib/python3.12/site-packages/eventlet/patcher.py", line 109, in inject module = … -
User defined logvars for Django application deployed on uWSGI server
I have deployed a Django application on a uWSGI server, which has the following middleware # myapp/middleware.py from django.utils.deprecation import MiddlewareMixin class LogUserMiddleware(MiddlewareMixin): def process_request(self, request): request.META['REMOTE_USER'] = 'test' The middleware is added in the settings.py file as well # myapp/settings.py MIDDLEWARE = [ ... 'myapp.middleware.LogUserMiddleware', ... ] Then in the uWSGI config file also the logvar is used ... log-format = %(ltime) %(addr){uWSGI} : %(method) %(uri) %(status) %(REMOTE_USER) ... But still the logs show as 19/May/2024:09:01:49 +0000 127.0.0.1{uWSGI} : GET /health_check 200 - Basically the logvar is getting replaced with - instead of showing test Is there any extra config to be done? -
How to run the build command before the build on Digital Ocean App Plateform
I need the json key file to configure my google cloud storage credentials in my settings.py (Django app) `GS_SERVICE_ACCOUNT = "static/GCS_key_api.json" GS_PROJECT_ID = os.getenv('GS_PROJECT_ID') GS_CREDENTIALS = service_account.Credentials.from_service_account_file(GS_SERVICE_ACCOUNT)` Here the logs of the build on App Plateofrm: 2024-05-19T09:24:41.171400485Z [34m╭────────────[34m[30m[44m git repo clone [0m[0m[34m───────────╼[0m 2024-05-19T09:24:41.171433696Z [34m│[0m [34m › fetching app source code[0m 2024-05-19T09:24:41.171437957Z [34m│[0m => Selecting branch "main" 2024-05-19T09:24:41.233929376Z [34m│[0m => Checking out commit "b0f8c02acbc8ef86ba30b50e4295f53a938aa584" 2024-05-19T09:24:41.237120654Z [34m│[0m 2024-05-19T09:24:41.239089601Z [34m│[0m [32m ✔ cloned repo to [35m/workspace[0m[0m 2024-05-19T09:24:41.317807317Z [34m╰────────────────────────────────────────╼[0m 2024-05-19T09:24:41.317827278Z 2024-05-19T09:24:41.492647202Z [34m › configuring build-time app environment variables:[0m 2024-05-19T09:24:41.492841261Z EMAIL_HOST_USER EMAIL_HOST_PASSWORD GS_SERVICE_ACCOUNT_JSON STRIPE_API_KEY SECRET_KEY GS_BUCKET_NAME PUBLIC_GS_BUCKET_NAME EMAIL_HOST GS_PROJECT_ID DEBUG DJANGO_ALLOWED_HOSTS EMAIL_PORT 2024-05-19T09:24:41.492854441Z 2024-05-19T09:24:41.494640715Z [34m › configuring custom build command to be run at the end of the build:[0m 2024-05-19T09:24:41.498131225Z [34m│[0m bin/pre_build.sh 2024-05-19T09:24:41.498140596Z 2024-05-19T09:24:41.567448183Z [34m╭────────────[34m[30m[44m buildpack detection [0m[0m[34m───────────╼[0m 2024-05-19T09:24:41.584376861Z [34m│[0m [34m › using Ubuntu 22.04 stack[0m 2024-05-19T09:24:41.933275054Z [34m│[0m Detected the following buildpacks suitable to build your app: 2024-05-19T09:24:41.933296537Z [34m│[0m 2024-05-19T09:24:41.933299356Z [34m│[0m digitalocean/python-appdetect v0.0.3 2024-05-19T09:24:41.933301358Z [34m│[0m heroku/python v4.242.4 (Python) 2024-05-19T09:24:41.933303328Z [34m│[0m digitalocean/procfile v0.0.4 (Procfile) 2024-05-19T09:24:41.933323594Z [34m│[0m digitalocean/custom v0.1.2 (Custom Build Command) 2024-05-19T09:24:41.933326093Z [34m│[0m 2024-05-19T09:24:41.933329053Z [34m│[0m For documentation on the buildpacks used to build your app, please see: 2024-05-19T09:24:41.933330985Z [34m│[0m 2024-05-19T09:24:41.933332932Z [34m│[0m Python v4.242.4 https://do.co/apps-buildpack-python 2024-05-19T09:24:41.936049330Z [34m╰─────────────────────────────────────────────╼[0m 2024-05-19T09:24:41.936066543Z 2024-05-19T09:24:41.938555872Z [34m╭────────────[34m[30m[44m app build [0m[0m[34m───────────╼[0m 2024-05-19T09:24:42.018292005Z [34m│[0m -----> No … -
Flatten DRF's nested serializer
I have two models for each user, a User model and a Profile model. class User(BaseModel, AbstractUser): username = None image = models.CharField(max_length=300, blank=True, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=300) emailConfirmed = models.BooleanField(default=False) phoneNumber = models.CharField(max_length=15, blank=True, null=True) phoneNumberConfirmed = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() class Profile(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profiles', null=True, blank=True) firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=30) locale = models.CharField(max_length=2) A user can have multiple profiles, but for each locale, a user can have only one profile. And I use these models as a base to create other user models, for example, a Member model: class Member(User): birthdate = models.DateField(blank=True, null=True) class MemberProfile(Profile): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='member_profiles', null=True, blank=True) education = models.CharField(max_length=300, blank=True, null=True) address = models.CharField(max_length=300, blank=True, null=True) # other fields only for members Now for the list and create functionalities of this Member model, I've written a ListCreateAPIView like this: @extend_schema(tags=[Namespace.MEMBERS.value]) class MemberListCreateView(generics.ListCreateAPIView): serializer_class = MemberSerializer permission_classes = [IsAuthenticated, IsAdminUser] filter_backends = [filters.DjangoFilterBackend] filterset_class = SearchFilter http_method_names = ["get", "post"] def get_queryset(self): return Member.objects.all() def get_serializer_context(self): context = super().get_serializer_context() context["locale"] = self.kwargs.get("locale", None) return context def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) def list(self, request, *args, … -
PyCharm Cannot load Django project after last update
I just opened PyCharm to work on a small side-project. A django app that does some stuff (I think irrelevant to the problem.) I am on Tumbleweed Operating System: openSUSE Tumbleweed 20240517 KDE Plasma Version: 6.0.4 KDE Frameworks Version: 6.2.0 Qt Version: 6.7.0 Kernel Version: 6.8.9-1-default (64-bit) Graphics Platform: Wayland Processors: 12 × 12th Gen Intel® Core™ i7-1255U Memory: 31.0 GiB of RAM Graphics Processor: Mesa Intel® Graphics Manufacturer: LENOVO Product Name: 21C1002HGE System Version: ThinkPad L14 Gen 3 and I don'T know, maybe it's related to "the big tumbleweed update with kde6 and changing to wayland" or whether it's a pyCharm problem: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kevin/PycharmProjects/VocabelTrainer/manage.py", line 22, in <module> main() File "/home/kevin/PycharmProjects/VocabelTrainer/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (venv) shouldN't pycharm automatically start the venv that I'm working in? is it normal that it cannot find django if the venv isn't running -
404 found error for post request at backend
I am unable to make post request to backend side using react. Here is my auth file and error file: I am expecting to make a request at http://localhost:8000/api/v1/user/register/ But the site is making the request at: http://localhost:5173/user/register/ (404) How to set the post request url correct? -
Is there a better way to update all relation rows with `ForegnKey` relation in `Django ORM`
I have two models, one like this: class PhysicalSensor(models.Model): name = models.CharField(unique=True, max_length=255) def __str__(self) -> str: return self.name class Sensor(models.Model): physical_sensor = models.ForeignKey(PhysicalSensor, on_delete=models.RESTRICT, null=True, blank=True) So, when I want to add a PhisycalSensor record, I want to set the Sensor records to that. Right now I handle this in my Serializer class: class PhysicalSensorSerializer(ModelSerializer): sensors = SensorSerialiazer(required=False, many=True) class Meta: fields = ("__all__") model = PhysicalSensor def create(self, validated_data): sensors = validated_data.pop("sensors") ph_sensor = super().create(validated_data) for sensor in sensors: s = Sensor.objects.get(sensor["id"]) s.physical_sensor = ph_sensor s.save() and for edit of PhysicalSensor, I use the same thing in .update() method of my Serializer. Is there any batter way of doing this or a best practice for this ? -
"'BillInvoice' instance needs to have a primary key value before this relationship can be used" Error
I'm experiencing an issue with my Django project where I'm trying to create a BillInvoice and its associated BillLineItem instances. The error I'm encountering is: "'BillInvoice' instance needs to have a primary key value before this relationship can be used" Context: I have a form view (CreateInvoiceView) that handles the creation of invoices and their line items using a formset. The relevant parts of my code are as follows: This is my model.py Userprofile class UserProfile(models.Model): ROLE = [ ('Select Role', 'Select Role'), ('Admin', 'Admin'), ('CBUMT', 'CBUMT'), ('Pharmacist', 'Pharmacist'), ('Doctor', 'Doctor'), ('Nurse', 'Nurse'), ('Referral Provider', 'Referral Provider'), ('Member', 'Memeber'), ('Dependent', 'Dependent'), ] GENDER = [ ('None', 'None'), ('Male', 'Male'), ('Female', 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) id_number = models.CharField(max_length=30, blank=True, null=True) is_medical_staff = models.BooleanField(default=False) role = models.CharField(max_length=50, choices=ROLE, default='CBUMT') gender = models.CharField(max_length=20, choices=GENDER, default='None') date_of_birth = models.DateField(blank= False, null=False, default=timezone.now) phone = models.CharField(max_length=20, blank=True, null=True) qualification = models.CharField(max_length=100, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_pic = models.ImageField(null=True, blank=True, upload_to='images/', default='img/placeholder.jpg') @property def age(self): today = date.today() age = today.year - self.date_of_birth.year - ((today.month, today.day) < (self.date_of_birth.month, self.date_of_birth.day)) return age def __str__(self): return str(self.user) + ' | ' + self.role **BillInvoice** class BillInvoice(models.Model): TYPE_CHOICES = [ ('Medicine', 'Medicine'), ('Auxillary', 'Auxillary'), ('Mixed', … -
Django Use two db in one model
I use RDS. The db have different schemas for Users and Products class Product(models.Model): id = models.AutoField(primary_key=True) class User(models.Model): id = models.AutoField(primary_key=True) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=public"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", default=""), "PASSWORD": config("DB_PASSWORD", default=""), "HOST": config("DB_HOST", default="db"), "PORT": config("DB_PORT", default=""), }, "data": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=products"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", default=""), "PASSWORD": config("DB_PASSWORD", default=""), "HOST": config("DB_HOST", default="db"), "PORT": config("DB_PORT", default=""), }, } Can I create relation between this two tables from different db schemas? Or only one decision move Product table to default db? -
Sorted serializer data by group DJANGO RESTFRAMEWORK
My model: class VariantCombination(models.Model): product = models.ForeignKey(Product, related_name='variant', on_delete=models.CASCADE, null=True, verbose_name="Продукт") variant = models.ForeignKey(Variant, on_delete=models.CASCADE, null=True, blank=False, verbose_name="Варианты") variant_value = models.ForeignKey(VariantValue, on_delete=models.CASCADE, null=True, blank=False, verbose_name="Значение варианты") price = models.FloatField(default=None, verbose_name="Цена", null=True, blank=False) class Meta: verbose_name = "Вариант" verbose_name_plural = "Варианты" def __str__(self): return self.product.name My serialer: # Variant Combination Serializer class VariantCombinationSerializer(serializers.ModelSerializer): variant_name_id = serializers.IntegerField(source="variant.id", read_only=True) variant_name = serializers.CharField(source="variant.name", read_only=True) variant_value = serializers.CharField(source="variant_value.value", read_only=True) product_id = serializers.IntegerField(source="product.id", read_only=True) category_id = serializers.IntegerField(source="product.category.id", read_only=True) class Meta: model = VariantCombination fields = ['id', 'variant_name_id', 'variant_name', 'variant_value', 'price', 'product_id', 'category_id'] # Product serializer class ProductSerializer(serializers.ModelSerializer): category_id = serializers.IntegerField(source="category.id", read_only=True) category_name = serializers.CharField(source="category.name", read_only=True) brand_id = serializers.IntegerField(source="brand.id", read_only=True) brand_name = serializers.CharField(source="brand.name", read_only=True) currency_id = serializers.CharField(source="currency.id", read_only=True) currency = serializers.CharField(source="currency.name", read_only=True) images = ProductsImageSerializer(many=True, read_only=True) uploaded_images = serializers.ListField( child=serializers.ImageField(allow_empty_file=False, use_url=False), write_only=True ) product_variant = ProductVariantSerializer(source="product", many=True) variants = VariantCombinationSerializer(source="variant", many=True) class Meta: model = Product fields = ['id', 'category_id', 'category_name', 'brand_id', 'brand_name', 'currency_id', 'currency', 'uploaded_images', 'name', 'description', 'is_available', 'create_time', 'update_time', 'image', 'images', 'product_variant', 'variants'] My result now: My result now I need result: I need result thanks Sorted serializer data by group DJANGO RESTFRAMEWORK I want to sort by group serialer data. I want to sort by group serialer data. I want to sort by group … -
I can't seem to load data from mysql to django's templates
I've been trying for hours, and i can't seem to get data from mysql to django. i've checked everything, views, urls, the html files, admin etc. I have a submission in 5 hours so it'll be great help if i chould get some help i Tried changing function names, changing the views, the admin.py. Looked up for hours but couldnt find anything class Bus(models.Model): name = models.CharField(max_length=50) bus_no = models.CharField(max_length=10, primary_key=True) class Meta: db_table = 'bus' def bus_detail(request): # Retrieve all buses with bus_no ranging from 1 to 7 buses = Bus.objects.filter(bus_no__range=(1, 7)) # Pass the retrieved buses to the template context return render(request, 'bus-timings.html', {'buses': buses}) <table> <thead> <tr> <th>Bus Name</th> <th>Bus Number</th> </tr> </thead> <tbody> <!-- Loop through each bus and display its details --> {% for bus in bus %} <tr> <td>{{ bus.name }}</td> <td>{{ bus.bus_no }}</td> </tr> {% endfor %} </tbody> </table> -
Custon user form conflict in variables
Trying to use custom forms to use info from models, for signup, login, etc. models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # error is in CustomUser, next line class CustomUser(AbstractUser): username = models.CharField(max_length=32, blank=False) date = models.DateField(default=datetime.now) email = models.EmailField(max_length=32, unique=True, blank=False) password = models.CharField(max_length=32, blank=False) forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm # UpdateView from django.views.generic import CreateView class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CreateView fields = ('username', 'email') class CustomUserChangeForm(UserChangeForm): class Meta: model = CreateView fields = ('username', 'email') class UserAdmin(UserCreationForm): class Meta(UserCreationForm.Meta): model = CreateView fields = ('username', 'email') Error displayed after successfully running runserver.: ERRORS: antelope.CustomUser.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'antelope.CustomUser.groups' clashes wit h reverse accessor for 'auth.User.groups'. ups'. HINT: Add or change a related_name argument to the definition for 'antelope.CustomUser.groups' or 'auth.User.gro antelope.CustomUser.user_permissions: (fields. E304) Reverse accessor 'Permission.user_set' for 'antelope.CustomUser.user _permissions' clashes with reverse accessor for 'auth.User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'antelope. CustomUser.user_permissions' or 'aut h.User.user_permissions'. auth.User.groups: (fields. E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor f or 'antelope.CustomUser.groups'. ups'. HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'antelope. CustomUser.gro auth.User.user_permissions: (fields. E304) Reverse accessor … -
django class based views, follow system
I want to use If statement and I use class based views. the problem is I don't know how to implement if statement in class based views here is the view: class ProfileView(DetailView): model = CustomUser template_name = 'profile.html' def get_context_data(self, *args, **kwargs): users = CustomUser.objects.all() context = super(ProfileView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(CustomUser, slug=self.kwargs['slug']) context["page_user"] = page_user return context I tried many time and i didn't work -
How to upload and store multiple images in Django 4
Django 4 Need user to be able to upload either an archive of images or just a few images at a time. Then these pages are numbered according to the order in which the user has placed them and stored in the database. Thus, when you open a page with images, there will be all the images just uploaded for this page in the correct order UPD: I would also be grateful if you could tell me how to rename files, change their extension, for example from .png to .jpg and in the path of saving in the model, for example, poster = models.ImageField(upload_to=‘posters/’, blank=False, null=False, verbose_name=‘Posters’) in the attribute upload_to add a value depending on what page the images are uploaded to. For example, if the page is called ‘opera’, the image path would be ‘posters/opera/1.jpg’, ‘opera/2.jpg’, etc. For the ‘Romeo and Juliet’ page it would be ‘posters/Romeo-and-Juliet/1.jpg.’ -
why recognize my models in an other app in django how can i call models in other app
from product.models import Product CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): cart = self.cart.copy() for item in cart.values(): item['product'] = Product.objects.get(id=int(item['id'])) item['total'] = int(item['price']) * int(item['quantity']) yield item def unique_id_generator(self, id, color, size): result = f"{id} - {color} - {size}" return result def add(self, product, quantity, color, size,): unique = self.unique_id_generator(product.id, color, size) if unique not in self.cart: self.cart[unique] = { 'quantity': 0, 'price': str(product.price), 'color': color, 'size': size, 'id': str(product.id), } self.cart[unique]['quantity'] += int(quantity) self.save() def save(self): self.session.modified = True hi every one i have problem in my site i will write code Cartmodule session base in django but i have problem in my model in the other app in the other app i have create models but i dont fetch in my other app my error like is : invalid literal for int() with base 10: 'black' how can i fix this error hi every one i have problem in my site i will write code Cartmodule session base in django but i have problem in my model in the other app in the other app i have … -
[Nginx][Django] Cannot access the media files in production via Nginx
I am trying to access the media files using Nginx. The file exists in the directory: /usr/src/app/backend/media/profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36, where the part profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36 is created dynamically. The media root is: /usr/src/app/backend/media. I know the file exists cause I am able to see it in the container. This is my nginx config: proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=STATIC:10m inactive=7d use_temp_path=off; upstream backend { server backend:8000; } upstream frontend { server frontend:3000; } server { listen 80 default_server; server_name _; server_tokens off; gzip on; gzip_proxied any; gzip_comp_level 4; gzip_types text/css application/javascript image/svg+xml; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; client_max_body_size 100M; location /_next/static { proxy_cache STATIC; proxy_pass http://frontend; } location /static { proxy_cache STATIC; proxy_ignore_headers Cache-Control; proxy_cache_valid 60m; proxy_pass http://frontend; } location /media/ { autoindex on; alias /usr/src/app/backend/media/; } location / { proxy_pass http://frontend; } location /api/ { proxy_pass http://backend; proxy_set_header Host $http_host; } } When trying to access the file I get 404. This is the link to file: http://localhost/media/profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36/da258fe5-f57c-44d2-94cf-00bef250b86d.png I tried modifying nginx, cause I think this is the reason, but without success. -
when I console.log fetched data it appears as undefined but it appears when I refresh
I have this function in react to fetch the data from my django api: const [filterData, setFilterData] = useState([]); const fetchFilterData = async () => { const filter_url = 'http://127.0.0.1:8000/api/filters/' try { const response = await fetch(filter_url) const result = await response.json(); setFilterData(result) } catch (error) { console.error('error fetching data: ', error); } } and when I try to console.log the data it is show as undefined at first but if I change something in the code (like add a white space or a new line) and save the fetched data appears and everything works fine but the issue is that I can't render that data or pass it down as a prop to other components here's the react useEffect hook: useEffect(() => { fetchData(); fetchFilterData(); }, []); and I have tried logging the data in several ways but no use it always returns undefined at first here are several ways I have tried: inside fetchFilterData function: if (filterData) {console.log(filterData.all_blocks) } else { console.log("this data is undefinde") } *and this has return undefinde as well and I still don't know why * passing it down as a prop to another component: return ( {filterData && <DropDown items={filterData.all_blocks} /> } ); …