Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
htmx insert multiple table rows
I'm using Django, if that makes any difference. Anyway, I have this tbody element in my template: <tbody id="log-stream-table-body" hx-get="{% url 'pages:log_stream_rows' %}?last_ts={{ last_log_ts }}" hx-trigger="every 30s" hx-target="this" hx-swap="afterbegin" > {% include "pages/_home_log_stream_rows.html" with log_stream=log_stream %} </tbody> The url it's pointing to returns this template snippet (which is actually pages/_home_log_stream_rows.html used in the include above): {% for log in log_stream %} <tr> <td>{{ log.ts|date:"Y-m-d H:i:s.u" }}</td> <td>{{ log.process }}</td> <td>{{ log.source }}</td> <td>{{ log.message }}</td> </tr> {% endfor %} <div id="log-stream-hyperscript" hx-swap-oob="outerHTML" data-log-ts="{{ last_log_ts }}" ></div> The problem is that I'm returning multiple tr elements at the top level, so the whole thing just fails. I can wrap it in a <template> tag, and it works, but of course then nothing is visible. Wrapping in anything else (div, andother tbody) just breaks the display in different ways. How can I group these multiple tr elements so that htmx adds them in correctly at the top of my table? -
How to access a translation defined in the base model from views and the admin panel of a child model
In a project I have inherited I have a few polymorphic models based on a common model. Something like: from django.db import models from polymorphic.models import PolymorphicManager, PolymorphicModel class Product(PolymorphicModel): name=models.CharField(max_length=127) objects=PolymorphicManager class Book(Product): pass class Drink(Product): pass Personally, I would not use polymorphism, but it's a bit too late for that and way out of scope. I am tasked with adding translations for the name on the base model using parler, however, the documentation for parler only covers translating fields on the child models. Nevertheless, I modified the models as such: from django.db import models from parler.models import TranslatableModel, TranslatedFields from parler.managers import TranslatableManager, TranslatableQuerySet from polymorphic.models import PolymorphicManager, PolymorphicModel from polymorphic.query import PolymorphicQuerySet class ProductQuerySet(PolymorphicQuerySet, TranslatableQuerySet): pass class ProductManager(PolymorphicManager, TranslatableManager): queryset_class = MarkerQuerySet class Product(PolymorphicModel): translations = TranslatedFields( name=models.CharField(max_length=127) objects=ProductManager class Book(Product): pass class Drink(Product): pass And it seems to work fine in the django shell: In [1]: from product.models import Book In [2]: b0 = Book.objects.first() In [3]: b0 Out[3]: <Book: A Brief History of Time> In [4]: b1 = Book() In [5]: b1.name = 'Hitchhikers Guide to the Galaxy' In [6]: b1.save() In [7]: b2 = Book(name='Slaughterhouse V') In [8]: b2.save() When I run my endpoint … -
problems with migrations when running tests in django
When running python3 manage.py test I get the error: return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "eventos_produtora" does not exist makemigration, migrate and runserver work normally. -
How to Avoid Using --run-syncdb with python manage.py migrate
I am working on a Django project that I cloned from GitHub. When I try to run python manage.py migrate, it fails and requires me to use --run-syncdb. However, I want to make it so that python manage.py migrate is sufficient without the need for --run-syncdb. I noticed that there is no migrations folder in my project. Here are the steps I have taken so far: Verified that the project does not have any existing migration files. Tried to run python manage.py makemigrations to generate migration files, but it still fails. How can I resolve this issue and ensure that python manage.py migrate works without requiring --run-syncdb? Is there a specific reason why the migrations folder might be missing, and how can I recreate it? -
Facing issue while installing libdmtx-devel package in AWS EC2 Linux server
I want to install libdmtx-devel package in AWS EC2 Linux server. But I am unable to install. I am getting the following error. Help me solve this issue. 2024/07/11 11:57:38.809677 [INFO] Instance is Leader. 2024/07/11 11:57:38.809719 [INFO] Executing instruction: stopSqsd 2024/07/11 11:57:38.809726 [INFO] This is a web server environment instance, skip stop sqsd daemon ... 2024/07/11 11:57:38.809730 [INFO] Executing instruction: PreBuildEbExtension 2024/07/11 11:57:38.809734 [INFO] Starting executing the config set Infra-EmbeddedPreBuild. 2024/07/11 11:57:38.809746 [INFO] Running command: /opt/aws/bin/cfn-init -s arn:aws:cloudformation:ap-south-1:707710317193:stack/awseb-e-fnnry9i6kh-stack/d5578c90-355d-11ef-b9e5-02cdb2f89e67 -r AWSEBAutoScalingGroup --region ap-south-1 --configsets Infra-EmbeddedPreBuild 2024/07/11 11:57:41.635413 [INFO] Error occurred during build: Could not successfully install rpm packages (return code 1) 2024/07/11 11:57:41.635437 [ERROR] An error occurred during execution of command [app-deploy] - [PreBuildEbExtension]. Stop running the command. Error: EbExtension build failed. Please refer to /var/log/cfn-init.log for more details. This is the code inside .ebextensions/01_packages.config file in Django application commands: 01_update_yum: command: "yum update -y" packages: rpm: epel: https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm yum: mariadb105-devel: [] libdmtx-devel: [] commands: update_pip: command: 'python3.11 -m pip install --upgrade pip' set_mysqlclient_cflags: command: 'echo "export MYSQLCLIENT_CFLAGS=$(mysql_config --cflags)" >> /etc/profile.d/mysqlclient.sh' set_mysqlclient_ldflags: command: 'echo "export MYSQLCLIENT_LDFLAGS=$(mysql_config --libs)" >> /etc/profile.d/mysqlclient.sh' -
I am not able to upload MEDIA Files in Django Vercel server
I get this error: ClientError at /dashboard/add-profile-details An error occurred (400) when calling the HeadObject operation: Bad Request Request Method: POST Request URL: https://www.karlowebsytz.com/dashboard/add-profile-details Django Version: 5.0.6 Exception Type: ClientError Exception Value: An error occurred (400) when calling the HeadObject operation: Bad Request Exception Location: /var/task/botocore/client.py, line 1021, in _make_api_call Raised during: dashboard.views.create_profile Python Executable: /var/lang/bin/python3.12 Python Version: 3.12.3 Python Path: ['/var/task', '/opt/python/lib/python3.12/site-packages', '/opt/python', '/var/lang/lib/python3.12/site-packages', '/var/runtime', '/var/lang/lib/python312.zip', '/var/lang/lib/python3.12', '/var/lang/lib/python3.12/lib-dynload', '/var/lang/lib/python3.12/site-packages', '/opt/python/lib/python3.12/site-packages', '/opt/python'] Server time: Thu, 11 Jul 2024 12:24:06 +0000 This is my settings.py configuration AWS_ACCESS_KEY_ID = 'myid' AWS_SECRET_ACCESS_KEY = 'mykey' #(I have the actual values in my project) AWS_STORAGE_BUCKET_NAME = 'karlowebsytz' AWS_S3_REGION_NAME = 'us-east-1' AWS_QUERYSTRING_AUTH = False AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_FILE_OVERWRITE = False AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' This is my Vercel.json file { "version": 2, "builds": [ { "src": "karlowebsytzweb/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "karlowebsytzweb/wsgi.py" } ] } My s3 policy and cors are below { "Version": "2012-10-17", "Id": "Policy1720667374556", "Statement": [ { "Sid": "Stmt1720667373352", "Effect": "Allow", "Principal": "*", "Action": [ "s3:PutObject", "s3:GetObject", "s3:DeleteObject", "s3:ListBucket", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::karlowebsytz", "arn:aws:s3:::karlowebsytz/*" ] } ] } … -
How can I ignore inserting a duplicate in Django?
I have some static tables that I'm initializing like this with a Management Command Suit(name="Clubs").save() Suit(name="Hearts").save() Suit(name="Diamonds").save() Suit(name="Spades").save() I want to be able to re-run this anytime, in case there are new values, but I want to avoid inserting duplicates. The database has a Unique constaint, so if there are duplicates I'll get an error. Other than wrapping each individual statement in a try/catch, is there a way I can run several statements like this and ignore the Constraint Violation and keep going? -
Understanding PostgreSQL benefits over ElasticSearch
I need help understanding the solution. What is in the project. It is Django project. There is a table with users, dependent table to it many to many, a table with geolocation and a large amount of specific data that are stored for each user, let's call them LargeData. Now these data are saved in ElasticSearch, which is bound to data from PostgreSQL, except for LargeData, they are not saved in PostgreSQL, but are saved in ES when registering a user. Problem. After receiving data from ES, the program filters these data additionally, it turns out slowly, so it was decided to move the filtering to ES or PostgreSQL. I considered both options and came to the conclusion that it is better to use PostgreSQL for filtering, and ES for getting LargeData, so you can use a convenient ORM in the program and have the advantages of ES to find the necessary data. Another programmer came to the conclusion that it is better to leave all data in ES and add data filtering there as well. Questions. I thought it's better to use SQL to implement links between tables, search them through ORM, solve normalization problems, but the other programmer … -
Django ORM to query string treats model choice value as column
I have the following Django ORM code and something weird is happening. When I comment the if part for library_level, query is working fine. If I add any new Q expression then the value provided as Q(field=value), value is treated as another field. query = ( (Q(domains=[]) | Q(domains__contains=domain)) # rule matches domain & (Q(klass=[]) | Q(klass__contains=dom_class)) # rule matches class & (Q(standards__contains=cdisc_version)) # rule matches standards & (~Q(exclusions__contains=domain)) # domain is not in excluded list & (~Q(exclusions__contains=dom_class)) # dom_class is not in excluded list ) if not library_level: query &= ~Q(rule_type=DataCheckRuleType.DATASET_CHECK) required_checks = DataCheckRule.objects.filter(query).values( "rule_id", "domains", "message", "description", "exclusions", "klass", "standards", "detail_string", "ex_domains", "rule_type", "params", ) sql_query = str(required_checks.query) Printing above sql_query gives SELECT "datacheck_rules"."rule_id", "datacheck_rules"."domains", "datacheck_rules"."message", "datacheck_rules"."description", "datacheck_rules"."exclusions", "datacheck_rules"."klass", "datacheck_rules"."standards", "datacheck_rules"."detail_string", "datacheck_rules"."ex_domains", "datacheck_rules"."rule_type", "datacheck_rules"."params" FROM "datacheck_rules" WHERE (("datacheck_rules"."domains" = \'[]\' OR "datacheck_rules"."domains" @> \'"DATA"\') AND ("datacheck_rules"."klass" = \'[]\' OR "datacheck_rules"."klass" @> \'"UNKNOWN"\') AND "datacheck_rules"."standards" @> \'"SDTMIG 3.2"\' AND NOT ("datacheck_rules"."exclusions" @> \'"DATA"\') AND NOT ("datacheck_rules"."exclusions" @> \'"UNKNOWN"\') AND NOT ("datacheck_rules"."rule_type" = dataset_check)) You can see that 'dataset_check' is treated as column instead of string which is giving me an error, mentioned column don't exist. I am creating sql_query to use as relevant_checks = pd.read_sql(sql_query, connections["default"]) My DataCheckRuleType is … -
Send email via EmailMultiAlternatives sudenly stopped working
I encounter a strange error. The email sending stopped working since yesterday before all was fine. I did not change a thing at all. Error message is: 2024-07-11 09:35:01,147 share.email.service ERROR Traceback (most recent call last): File "/srv/deduu/./share/email/service.py", line 318, in send_email_from_template cls.send_admin_email(subject, recipient_list, html_message=message) File "/srv/deduu/./share/email/service.py", line 330, in send_admin_email cls.send_email(subject, from_mail, recipient_list, message, html_message) File "/srv/deduu/./share/email/service.py", line 279, in send_email return email_wrapper.send_mail() File "/srv/deduu/./share/email/service.py", line 91, in send_mail return_value = bool(self.mail.send()) File "/srv/deduu/.venv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/srv/deduu/.venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 109, in send_messages sent = self._send(message) File "/srv/deduu/.venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 125, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python3.8/smtplib.py", line 874, in sendmail (code, resp) = self.mail(from_addr, esmtp_opts) File "/usr/lib/python3.8/smtplib.py", line 539, in mail return self.getreply() File "/usr/lib/python3.8/smtplib.py", line 398, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed Strangely the sending of the mail works with a testscript with the same credentials and settings but using this snippet from email.message import EmailMessage import smtplib username = "info@test.de" password = r"*****" smtp_server = "mail.test.de" smtp_port = 47999 receiver_email = "user@test.de" subject = 'Test Email' body = 'This is a test email sent using smtplib in Python.' # Create message em = EmailMessage() em['From'] = username em['To'] = … -
Does httpsstreamingresponse block the thread? or How many clients are allowed in one thread?
I have implemented basic server sent event in django using httpsstreamingresponse, which at every 5 second send the response! class task_status_stream(AuthententicatedOrReadOnlyAPIView): # to respond as text/event-stream we need to ignore exisiting Client Content negotiation content_negotiation_class = IgnoreClientContentNegotiation # sending pf creation status to as StreamingHttpResponse def get(self, request): timeout = int(request.query_params.get('timeout', 300)) def event_stream(): start_time = time.time() try: while True: if time.time() - start_time > timeout: yield f"data: {json.dumps({'status': 'TIMEOUT'})}\n\n" break task = AsyncResult(task_id) if task.ready(): yield f"data: {json.dumps({'status': 'DONE'})}\n\n" # noqa W503 break else: yield f"data: {json.dumps({'status': 'PENDING'})}\n\n" time.sleep(5) # Check every 5 seconds except Exception as e: logger.error(f"Error during streaming: {e}") yield f"data: {json.dumps({'status': 'ERROR', 'message': str(e)})}\n\n" finally: logger.info("Ending the streaming response") response = StreamingHttpResponse(event_stream(), content_type='text/event-stream') response['Cache-Control'] = 'no-cache' response['X-Accel-Buffering'] = 'no' return response now does this above implementation would block the thread or block the port untill event stream is closed from client side? or it will keep executing for 300 seconds timeout! also another question is how many users at a time can do start this streaming response using one thread and how to increase that limit? -
Logout Process in Django and " Url Logout next" Parameter Error
I am creating a blog page using Django where users can log in and out, write, and share blog posts. After logging in, users should be able to add blog posts, and if they are not logged in, they should only be able to view posts published by others. I am using the Django "{% url 'logout' %}?next=/" parameter for logging out and making a POST request in the form. However, I have another POST request in my code, and these two requests are conflicting. How can I fix this issue? Here is the code I am using for the logout request: <ul class="dropdown-menu text-small "> <li><a class="dropdown-item" href="{% url 'blogapp:profile' %}">Profile</a></li> <li><a class="dropdown-item" href="{% url 'blogapp:settings' %}">Settings</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="{% url 'login' %}">Sign in</a></li> <!-- <li><a class="dropdown-item" href="{% url 'logout' %}?next=/">Log out</a></li> --> <div class="logout"><li><form action="{% url 'logout' %}?next=/" method="POST"> {% csrf_token%} <button type="submit" class="nav-link btn btn-link">Logout</button></li></div> </ul> Here is the code I am using for the other POST request: {% extends "base.html" %} {% block content %} <div class="container" style="margin-top: 25px; padding: 20px; width: 60%; margin: auto;"> <form action="" method="POST"> {% csrf_token %} <div style="text-align: center;"> <input type="text" name="blog_title" placeholder="Title..." style="width: 80%; font-size: 2em; padding: 10px; … -
How to get specific user data from a table with foreignKey to another tables Django
I have 3 table from django.db import models from django.contrib.auth.models import User class Boost(models.Model): title = models.CharField(max_length=50,null=False)# point, storage, point p/s, expire = models.BooleanField(default=False) expireDate = models.DateTimeField(null=True) visiblity = models.BooleanField(default=True) def __str__(self): return "id:"+self.title class BoostLevel(models.Model): id = models.AutoField(primary_key=True) boost = models.ForeignKey(Boost, on_delete=models.CASCADE) level = models.IntegerField(null=False) def __str__(self): return self.boost.title + " level: " + self.level.__str__() class UserBoostList(models.Model): boostLevel = models.ForeignKey(BoostLevel, on_delete=models.CASCADE) boostId = models.ForeignKey(Boost, on_delete=models.DO_NOTHING) userId = models.BigIntegerField(null=False) In my case, Boost is a title, Boost level are levels for boost and UserBoostList are User selected boost Each boost can have many level from 1 to X. Each user should start boost from level 1 to level 2 to and go on I need to check each user have which level of boost for each boost let me explain I have Boost A and boost B in Boost table and boosts level 1 ,2 ,3 ... for each boost separate, Ex(boost A level 1, boost A level 2 and ... AND boost B level 1 , boost B level 2 and ...) Now how can I get info for username like Alex to know which level he boosted for each boost Note: You can add or remove any field … -
Where to store referral code until purchasing somthing in django ecommerce website
I am new to django and I have an ecommerce shop. Now I have added a referral link feature in which after ordering a unique link will be generated and other can come to the website using that link. the referral link url is somthing like this : http://127.0.0.1:8000/orders/referral/qEAKfbOx15n3maHKtgBmhflH1ISPo45q And the url pattern is : path('referral/<str:unique_id>/', views.referral, name='referral') I am redirecting referral user to store page and pass unique id in referral view: def referral(request, unique_id): if get_object_or_404(OriginOrder, unique_id=unique_id): return redirect(reverse("store") + "?u_id=" + unique_id) now in store page although I have the unique_id but until purchasing something, The user may call a lot of urls like choosing products, search on categories and see the products detail, so in fact I need to store this unique id until purchasing something and then add a reward to the person who sent the referral link to current user. So what is the best option here. I heard about sessions but I do not know if It is a right option here. I also was thinking about adding a parameter to the cart of the user called referral code with a null value for default but the problem is that, cart is created … -
Django static files doesn't work on smartphones
I am using the Django framework to build my web app and have deployed it using ngrok. Why can't my phone access the static images in the template when visiting the ngrok URL, but my computer can? My template {% load static %} <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <img src="{% static 'img/hero-img-1.png' %}"> </body> </html> My setting.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = "django-insecure-@p&wu2ht6d&50!yox%%#k*i(8*q(yc(3qyusw@uydit0hm42r&" DEBUG = True ALLOWED_HOSTS = [ '6785-123-240-57-1.ngrok-free.app', '127.0.0.1', ] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'testdebug.apps.TestdebugConfig' ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "debug.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'templates').replace('\\', '/')], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "debug.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True STATIC_URL = "static/" DEBUG = True STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" My folder enter image description here Thank you … -
django-filter DateFromToRangeFilter can't not filte between two dates
I'm building vue3 + django DRF project. I'm making my consumelists from and I want to filte bewteen two days. likes 2024-06-01 to 2024-06-30. I used DateFromToRangeFilter but not work. please help. omz My model.py class ConsumeDetails(models.Model): date = models.DateField() category = models.CharField(max_length=100) subcategory = models.CharField(max_length=100) vendor = models.CharField(max_length=100) item = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=0) remarks = models.CharField(max_length=100) consumetype = models.ForeignKey(ConsumeType, on_delete=models.PROTECT) consumepurpose = models.ForeignKey(ConsumePurpose, on_delete=models.PROTECT) class Meta: managed = True app_label = 'myweb' db_table = 'Consume_Details' def __str__(self): return self.date My filter.py class ConsumeDetailsFilter(FilterSet): # date = filters.DateFilter(field_name='date') RegDate= DateFromToRangeFilter(field_name='date', lookup_expr='gte',lable='date range') category = filters.CharFilter(field_name='category', lookup_expr='icontains') subcategory = filters.CharFilter(field_name='subcategory', lookup_expr='icontains') vendor = filters.CharFilter(field_name='vendor', lookup_expr='icontains') item = filters.CharFilter(field_name='item', lookup_expr='icontains') class Meta: model = ConsumeDetails fields = ['RegDate','category', 'subcategory', 'vendor', 'item', 'price', 'remarks'] My serializers.py class ConsumeDetailsSerializer(serializers.ModelSerializer): consumepurpose = ConsumePurposeSerializer() consumetype = ConsumeTypeSerializer() class Meta: model = ConsumeDetails fields = '__all__' My views.py class ConsumeDetailsViewSet(ModelViewSet): queryset = ConsumeDetails.objects.all() serializer_class = ConsumeDetailsSerializer filterset_fields = ['consumepurpose','consumetype','category','subcategory','RegDate'] search_fields = ['category','subcategory','vendor','item'] pagination_class = MyPageNumberPagination Error message in here enter image description here I want use star_date and end_date to filte the range like the link below http://127.0.0.1:8000/accounts/consumedetails/?**start_date=2024-06-01&end_date=2024-06-30** -
Django view getting called twice (double get request) primary key gets set equal to None
Running a django project on localhost, and i have a go to profile button which sends a pk (the username) back to the profile view and currently i have some debugging code inside the view and i see it runs twice. First it prints the correct pk of whatever profile I clicked then it says pk :None and gives "GET /profile/None HTTP/1.1" 500 before error Received pk: tim [10/Jul/2024 21:15:52] "GET /profile/tim HTTP/1.1" 200 26400 before error Received pk: None Internal Server Error: /profile/None I have no idea why its calling twice, the weird thing is the site is still working, it correctly goes to the correct profile but just throws error in terminal. Thanks! -
How do I ensure that my Frontend is the Origin sending a POST request to my Backend
I have a Vue 3 frontend site that I want to be able to sign up new users. When the user enters their information into the frontend, the frontend will send a POST request to the backend which is a Django REST API. The backend will then create the user. But how can I verify that the frontend is the Origin sending the request? I would think there would be a problem if someone just set up a script to execute 1000 curl commands to flood my database with users (although I guess someone could still do this if they set up an automated script to enter information via selenium or something). Would it be secure for Django to look at the Origin header when handling the POST request or can this be forged? I have also already read the accepted answer here but it did not really answer my question. -
Accessing 'self.user' or 'self.user_id' in Django model's clean() method
I need to know if this is possible in a model's clean or save method (ideally clean), without using forms, as I want specific validation logic to be directly tied to the model so that both forms and manager commands (e.g., Model.objects.create() in shell or views) are validated equally. I have ModelB where user is a foreign key of ModelA. I then have a view where a form for ModelB is validated before ModelB is created: if form.is_valid(): form.save() As we all know, form.is_valid() calls model.clean() via self.instance.full_clean(). , and I'm looking to validate something about self.user under the clean() method of ModelB. However, in this Model B clean method, self.user produces: raise self.RelatedObjectDoesNotExist( models.ModelB.user.RelatedObjectDoesNotExist: ModelB has no user. and self.user_id returns None. Essentially, is it possible to reference self.user or self.user_id in ModelB's clean method, or must it go in its save method? -
Attribute Error, 'WSGIRequest' object has no attribute 'get' Django-HTMX
I'm building a homepage that includes a contact-us form. This contact-us form element should be reusable across multiple pages, so I've used HTMX to try incorporate. However am receiving the following error, which I can't make sense of because I'm submitting POST data. Request Method: POST Request URL: http://localhost:8000/contactus Django Version: 4.2.13 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'accounts', 'dashboard'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback (most recent call last): File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/utils.py", line 67, in render context = context or self.get_context() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 322, in get_context top_errors = self.non_field_errors().copy() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 358, in non_field_errors return self.errors.get( File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 196, in errors self.full_clean() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 433, in full_clean self._clean_fields() File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 440, in _clean_fields value = bf.initial if field.disabled else bf.data File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/boundfield.py", line 135, in data return self.form._widget_data_value(self.field.widget, self.html_name) File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/forms.py", line 220, in _widget_data_value return widget.value_from_datadict(self.data, self.files, html_name) File "/Users/robrobrob/Desktop/Projects/Trolleys/venv/lib/python3.9/site-packages/django/forms/widgets.py", line 297, in value_from_datadict return data.get(name) Exception Type: AttributeError at /contactus Exception Value: 'WSGIRequest' object has no attribute 'get' ** Forms.py ** This file contains … -
Where is nginx.conf kept on Google App Engine flexible environment?
I am getting nginx.error: client intended to send too large body so I'm trying to fix by making changes to nginx.conf. This is in a Google App Engine that uses Django and deploys to the flexible environment with a Dockerfile. It executes gunicorn to start the app. My nginx.conf file is in the same directory as my app.yaml file. So far, I've tried copying nginx.conf to /etc/nginx/nginx.conf in the Dockerfile just before starting gunicorn. I've tried naming the file nginx-app.conf as suggested elsewhere. I've tried commenting out the entire nginx.conf file to see if it is being used. In every case, I get the "client intended to send too large body" error. Where does nginx.conf live in the flexible environment? Can I change it and copy it to where it needs to be as part of my Dockerfile? Current Dockerfile: FROM ubuntu:bionic RUN apt-get -y update && apt-get -y upgrade \ ... RUN pip3 install virtualenv RUN virtualenv -p python3.8 env ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt ADD . /app WORKDIR /app ENV PORT 8000 EXPOSE 8000 COPY nginx.conf /etc/nginx/nginx.conf CMD exec gunicorn --workers 2 --threads 8 -b :$PORT mysite.wsgi:application My current … -
Django Debug=False returns error traceback
I support Django 4.0 project and notice that even though DEBUG=False, all errors return with tracebacks. I've commented all extras in settings.py, but still receive the traceback. All variebles are deffinately loading (DEBUG) and it happens both localy and on server. we don't need templates to return, just return json, so simply return the basic functionality. Please, give ideas where to look at? # from pathlib import Path import os from datetime import timedelta from django.utils.translation import gettext_lazy as _ # for translation from dotenv import load_dotenv import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration from django.utils import timezone from logging.handlers import TimedRotatingFileHandler BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROGECT_DIR = os.path.dirname(os.path.dirname((BASE_DIR))) load_dotenv(os.path.join(PROGECT_DIR, 'infra', '.env'), verbose=True) ENVIRONMENT = os.getenv('ENVIRONMENT') DEVELOPER = os.getenv('DEVELOPER') # LOG_DIRECTORY = os.path.join(BASE_DIR, 'logging') # if not os.path.exists(LOG_DIRECTORY): # os.makedirs(LOG_DIRECTORY) # LOGGING = { # "version": 1, # "disable_existing_loggers": False, # "formatters": { # "verbose": { # "format": "{levelname} {asctime} {pathname} {funcName} {process:d} {thread:d} {message}", # "style": "{", # }, # }, # "handlers": { # "console": { # "level": os.getenv('CONSOLE_LOG_LEVEL', 'DEBUG'), # "class": "logging.StreamHandler", # "formatter": "verbose", # }, # "file": { # 'level': os.getenv('FILE_LOG_LEVEL', 'DEBUG'), # 'class': 'logging.handlers.TimedRotatingFileHandler', # 'filename': os.path.join(LOG_DIRECTORY, 'yume.log'), # 'formatter': 'verbose', # 'encoding': 'utf-8', # # … -
python send InMemoryUploadedFile to requests.request
In postmen I send data like this: My python code is: headers = { "Accept": "*/*", "Content-Type": "multipart/form-data; boundary=974767299852498929531610575", } response = requests.request( "POST", LINK, headers=headers, data={ 'product_id': 1, 'product_images': [file, ] } ) Where file has InMemoryUploadedFile format. But I've got error. Also I've tried file = my_file.file.getvalue() But still the error. How can I fix my cod and get 200 status? Any ideas? -
Wagtail view with URL params, or multiple custom URLs
I have a calendar that is used in a general Django app, but I also want to show it within the Wagtail app (which shows general text content/blog) for this site. I have got to the point where I can display the calendar on the Wagtail page, with some manual entry for the date params. The model for that looks like: class SchedulePage(PostPageExtras, RoutablePageMixin, Page): content_panels = Page.content_panels def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context['schedule'] = self.get_calendar() return context def get_calendar(self): the_year = 2024 the_month = 7 cal = ScheduleCalendar().formatmonth(the_year, the_month, withyear=True) return cal I have tried to work this out with the RoutablePageMixin but didn’t make any progress. I can generate the_year and the_month values that derive from .now(), so the calendar always shows the current month. But I want the user to be able to navigate to next/previous months. The way that this is done in the Django app is that there are two urls that point to the same view, and the view interprets the parameters as required: path('/schedule/', views.ScheduleCalendarView.as_view(), name='control-schedule-calendar'), re_path(r'^/schedule/(?P<year>\d+)/(?P<month>\d+)/$', views.ScheduleCalendarView.as_view(), name='control-schedule-monthview'), With these two URLs you'll get the same page display (at July 2024): https://example.com/schedule/ https://examle.com/schedule/2024/07/ Because, in the first … -
Nested Serializers create method for each serializer
I have a Club Model as well as an Address model. class Club(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(UserAccount,on_delete=models.CASCADE,related_name = 'owner_of') ##members = models.ManyToManyField(UserAccount,related_name = 'member_of') ##staff = models.ManyToManyField(UserAccount,related_name = 'staff_of') def __str__(self): return f'{self.name}' class Address(models.Model): name = models.CharField(max_length=100) street = models.CharField(max_length=150) city = models.CharField(max_length=100) state = models.CharField(max_length=100, blank=True, null=True) # Optional for countries without states province = models.CharField(max_length=100, blank=True, null=True) # Optional for countries without provinces country = models.CharField(max_length=50) postal_code = models.CharField(max_length=20) club = models.ForeignKey(Club,on_delete=models.CASCADE,related_name = 'address') def __str__(self): return f'{self.name}' They have their respected serializers. class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ['id', 'name', 'street', 'city', 'state', 'province', 'postal_code', 'country'] def create(self,validated_data): user=self.context['user'] club=Club.objects.get(owner=user) address=Address.objects.create(club=club,**validated_data) return address class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = ['id', 'name'] def create(self,validated_data): user=self.context['user'] club=Club.objects.create(owner=user,**validated_data) return club class ClubRegistrationSerializer(serializers.Serializer): address= AddressSerializer2() club=ClubSerializer2() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # We pass the "upper serializer" context to the "nested one" self.fields['address'].context.update(self.context) self.fields['club'].context.update(self.context) this is the data that I am posting { "club":{"name":"someclub"}, "address":{ "name":"Bodrum Location", "street":"140", "city":"bodrum", "state":"california", "province":"some provence", "postal_code":"123", "country":"USA" } } I can easily implement the create method of my view and do this: @action(detail=False,methods=['post']) def register(self, request): serializer = ClubRegistrationSerializer(data=request.data) serializer.is_valid(raise_exception=True) clubinfo_data=serializer.validated_data.pop("club") club_serializer=ClubSerializer(data=clubinfo_data) club_serializer.is_valid(raise_exception=True) club=club_serializer.save(owner=self.request.user) …