Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hired at a new job - I can do 85% of responsibilities except some things related to the website. How do I get a sitemap?
I am in charge of adding content to a website - it uses Wagtail. I know nothing about programming. My superior has asked me to do a website audit and wants to know if the sitemap file is set up correctly. My problem is that I do not know how to get a sitemap. On a broader level I have no idea who created the website or how to access the more complex areas (Django contrib sitemap app?) I apologize for being so ignorant but could anyone describe to me the first steps I should take? That might include questions I could ask the people around me to gain access to what I need to get to. -
Docker-compose is able to compile program but is unable to open link to Local host
I have a basic Django project that I have put into a docker container. Currently I have it running on https locally just for the development phase because it is a requirement. When I run my program without docker it opens successfully on https://127.0.0.1:8000. Which is the address the message says its currently running on. But when I use the same logic on my docker container after running docker-compose up the container compiles but I am unable to load the web page. When I try to run the address from the docker container I just get the generic site cannot be reached error. Link I used to get https during development: Docker-compose.yml version: "3.8" services: django: build: . container_name: frontend command: python manage.py runserver_plus --cert-file cert.pem --key-file key.pem volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - pgdb pgdb: image: postgres container_name: backend environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres Dockerfile FROM python:3.12.3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install django RUN pip install -r requirements.txt settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'location', 'rest_framework', 'django_extensions', ] I tried to change the port number but it still didn't work. -
Django query for a select item return '---------'
I'm trying to populate a select item with a django queryset. It's working fine but at the begining of the list of the dropdown menu on the select item I always have a '---------' as first option. forms.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField(queryset=models_products.objects.values_list('product_denomination', flat=True),required=False, widget=forms.Select(attrs={'id': 'editable-select-2'})) The "product_denomination" on the database only contains 2 lines but I always have this '---------' on first option. What am I missing ? -
NOT NULL constraint failed on PUT request in Django
I'm new to Django and I'm having trouble handling form-data and raw data in PUT requests. I need to update records of a Person model via a PUT request. The Person model has several fields including fname, sname, age, and gender, all of which are required. I have a view to handle the PUT request, and I’m trying to handle both JSON and form-data formats in the request body. However, when I send a PUT request via Postman, I encounter the following error: Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: api_person.fname To handle different request formats, I first attempt to parse the request body as JSON. If JSON parsing fails, I fall back to handling form-data. Here’s the relevant part of my view: ` try: # Attempt to parse request body as JSON data = json.loads(request.body) fname = data.get('fname') sname = data.get('sname') age = data.get('age') gender = data.get('gender') except json.JSONDecodeError: # Handle form-data if JSON parsing fails fname = request.POST.get('fname') sname = request.POST.get('sname') age = request.POST.get('age') gender = request.POST.get('gender') # Update person object with received data person.fname = fname person.sname = sname person.age = age person.gender = gender person.save() ` I expected this approach to handle both request … -
using nginx host multiple django apps/docker in one server. return to root path not the apps' path
I have a django app. The code snippet for the function load_form(request) in views.py. ''' def load_form(request): if request.method == 'POST': newQAForm = QAForm(request.POST) if newQAForm.is_valid(): instance = newQAForm.save(commit=False) instance.save(using='RadDataWarehouse') return redirect('confirmation') ''' and another function ''' def confirmation(request): return render(request, 'confirmation.html') ''' It runs well in local. It will direct it to http://127.0.0.1:8000/confirmation/ after save the form to database. After I deployed it to linux server. I had a issue after save it to database. It will direct to https://abcdomain.com/confirmation/; But I suppose it will go to https://abcdomain.com/protocolqa/confirmation/ The nginx.conf for the Reverse Proxy is below: ''' location /protocolqa/ { proxy_pass http://localhost:8511/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Script-Name /protocolqa; proxy_set_header X-Original-URI $request_uri; } ''' how to fix it and let it got to https://abcdomain.com/protocolqa/confirmation/ -
Best approach to object creation in the background without using a task queue system?
I have been thinking of the best approach to a record creation in the background without using django signals, or celery, etc. I do not want to use signals due to the fact that the sender Model would be called a very high number of times, as that table gets created/updated quite often. So I am looking to avoid this approach. My goal is to run a function that goes through some complex logic, ultimately ending in an EmailRecordTracker object creation in which I am doing some tracking to determine whether an email needs to be sent out or not at a later point in time. The function I need to create needs to get hit after a user submits a form and the form is fully saved. I was looking into asynchronous support possibly. https://docs.djangoproject.com/en/5.0/topics/async/ Workflow is pretty simple: User submits form, updates a form, etc. User is able to continue to navigate through app while my function to create an EmailTrackerRecord gets ran in the background. Any advice would be appreciated! -
Is there a way to create a run configuration for a manage.py command in Pycharm
I want to be able to run a manage.py management command via a Pycharm run configuration. Is there a way to do this? -
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.