Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy react js + django + CentOS + SSL
I need some help deploying react js + django + CentOS + SSL. Here's what I have: react-ui/src/config/constant.js BACKEND_SERVER = "http://mysite.mydomain.xxx:8000/api/"; react-ui/package.json "start": "HTTPS=true react-scripts start", "build": "HTTPS=true react-scripts build", react-ui/.env HTTPS=true yarn start django I know some of these are high risk entries, but I am working on getting this functional. ALLOWED_HOSTS = [ '*' ] CORS_ALLOW_ALL_ORIGINS=True # Load the default ones CORS_ALLOWED_ORIGINS = ["https://localhost:3000", "https://mysite.mydomain.xxx:3000"] CSRF_TRUSTED_ORIGINS = ["https://localhost:3000", "https://mysite.mydomain.xxx:3000"] SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_EXPIRE_AT_BROWSER_CLOSE=True run django python manage.py runserver 0.0.0.0:8000 /etc/nginx/nginx.conf upstream mysite_server { server unix:/home/myuser/mysite/django-api/mysite.sock fail_timeout=0; } server { listen 80; server_name mysite.mydomain.xxx; #location = /favicon.ico { access_log off; log_not_found off; } #location /static/ { # root /home/myuser/mysite/django-api; #} #location / { # proxy_set_header Host $http_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_pass http://unix:/home/myuser/mysite/django-api/mysite.sock; # } return 301 https://mysite.mydomain.xxx$request_uri; } server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name mysite.mydomain.xxx; root /usr/share/nginx/html; ssl_certificate "/etc/pki/tls/private/star-yyy-xxx.bag"; ssl_certificate_key "/etc/pki/tls/private/star-yyy-xxx.bag"; # ssl_certificate "/etc/pki/nginx/server.crt"; # ssl_certificate_key "/etc/pki/nginx/private/server.key"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers PROFILE=SYSTEM; ssl_prefer_server_ciphers on; # # # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; # location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header … -
Flutter app uploaded on play store but not fetching data through django backend connection even though it the code was working fine in the local studi
I have created a flutter app whoch is connected with the django backend website and uploaded this app on playstore when the app was uploaded successfully I download the app and when I run the app and try to fetch the data to the app from website django backend connection no data was being fetched there was no cennection between the app and the django backend of website which I downloaded it on playstore even though the app was working fine in android studio during testing. This is the link of my app https://play.google.com/store/apps/details?id=com.beneprep.mdcat -
`pytest -rP` got error while `pytest` didn't to run Selenium with Django and pytest-django on Windows 11
I set tests/test_ex1.py as shown below. *I use Django 4.2.1, pytest-django 4.5.2 and Selenium 4.11.2 on Windows 11: django-project |-core | |-settings.py | └-urls.py |-my_app1 |-my_app2 └-tests |-__init__.py └-test_ex1.py # Here Then, I defined test_example() with print("OK") to test Django Admin in TestBrowser1 class as shown below: # "tests/test_ex1.py" from django.test import LiveServerTestCase from selenium import webdriver class TestBrowser1(LiveServerTestCase): def test_example(self): print("OK") driver = webdriver.Chrome() driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in driver.title Then, I could successfully run Selenium with pytest by not printing OK as shown below: $ pytest ===================================== test session starts ===================================== platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0 django: settings: core.settings (from ini) rootdir: C:\Users\kai\test-django-project2 configfile: pytest.ini plugins: Faker-19.3.0, django-4.5.2, factoryboy-2.5.1 collected 1 item tests\test_ex6.py DevTools listening on ws://127.0.0.1:56055/devtools/browser/271a3af7-5697-47e5-a7db-fd80c52ed70d . [100%] ====================================== 1 passed in 5.11s ====================================== But, I could not successfully run Selenium with pytest -rP by getting the error below even though it printed OK. *pytest -s, pytest --capture=no and pytest --capture=tee-sys also got the same error below even though it printed OK as well: $ pytest -rP ===================================== test session starts ===================================== platform win32 -- Python 3.9.13, pytest-7.4.0, pluggy-1.2.0 django: settings: core.settings (from ini) rootdir: C:\Users\kai\test-django-project2 configfile: pytest.ini … -
Reverse for 'blog-single' with keyword arguments
I'm trying to create simple blog, I have a blog-home page that show the lastest puplished post and I want to open a single-blog page for each post but I encounter with this error : Reverse for 'blog-single' with keyword arguments '{'post_id': ''}' not found. 1 pattern(s) tried: ['blog/blog/(?P<post_id>[0-9]+)/\Z'] do you know how can I solve this ? [view](https://i.stack.imgur.com/eW6I4.jpg) [url](https://i.stack.imgur.com/kMdy0.jpg) [blog-home.html](https://i.stack.imgur.com/lvxOv.jpg) I check all the names and links in view, url and template but nothing was wrong -
Django Access Formset Instances from within Forms
I'm building a website where students can answer multiple questions on an assignment. I have models to store these objects. I'm trying to create a formset of questions for an assignment. To do this, I'm using an inlineformset_factory to handle multiple questions. It is important the questions be created before the formset is submitted, and that the formset updates each question. My application has the following models: Models from django.db import models class Assignment(models.Model): name = models.CharField(max_length=255) class AssignmentSubmission(models.Model): """Can be completed multiple times by students. Teachers can view/mark submissions.""" assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) class QuestionType(models.TextChoices): """Identifies what types of questions can be created.""" SHORT_ANSWER = "short_answer" LONG_ANSWER = "long_answer" FILE_UPLOAD = "file_upload" class Question(models.Model): """Used for adding additional submission fields to Quests. This model is used for all types of questions, including multiple choice, short answer, file upload, etc. """ instructions = models.TextField() assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) type = models.CharField( max_length=20, choices=QuestionType.choices, default=QuestionType.SHORT_ANSWER ) class QuestionSubmission(models.Model): """Used for storing a student's response for an individual question in an AssignmentSubmission. This model is used for all types of questions, including multiple choice, short answer, file upload, etc. When a student submits an Assignment, each Question will have a QuestionSubmission created … -
VSCode test tab for Django project, Apps aren't loaded yet
I am fighting for hours with configuring my django project to use this test tab of vs code with pytest. So for run of pytest --collect-only typed in terminal outside my .venv I am getting output as I expect - test are being collected. But after reloading tests in test tab and looking into output > python I got raise AppRegistryNotReady("Apps aren't loaded yet.") E django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. =============================== warnings summary =============================== .venv/lib/python3.11/site-packages/_pytest/config/__init__.py:1373 /Users/dawid/Documents/Projects/parking_test/parking_test/.venv/lib/python3.11/site-packages/_pytest/config/__init__.py:1373: PytestConfigWarning: Unknown config option: DJANGO_SETTINGS_MODULE self._warn_or_fail_if_strict(f"Unknown config option: {key}\n") -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html =========================== short test summary info ============================ ERROR parking/tests/test_api.py - django.core.exceptions.AppRegistryNotReady:... ERROR parking/tests/test_pytest.py - django.core.exceptions.AppRegistryNotRea... Here is my .vscode/settings.json { "python.linting.enabled": true, "python.linting.pylintEnabled": true, "python.formatting.provider": "black", "python.formatting.blackArgs": [ "--line-length", "79" ], "python.testing.pytestArgs": [ ".", ], "python.envFile": "${workspaceFolder}/.env", "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, "python.testing.pytestPath": ".venv/bin/pytest", } ./pytest.ini [pytest] DJANGO_SETTINGS_MODULE=app.settings python_files = test*.py I tried many solution found mostly on stack/gh but none of them works for me -
Access to contents of the selected object in a Django OneToOneField
I would like to retrieve specific field data from a selected object within a OneToOneField relation. I have three models: Model1 contains the 'malfunction_1' field, which I intend to copy into the 'malfunction_3' field within Model3. Model2 possesses the OneToOneField. When a Model2 object is created and an object is chosen within the OneToOneField, another Model3 object should be generated. The content from 'malfunction_1' (Model1) and 'dynamik_2' (Model2) should then be duplicated into 'malfunction_3' and 'dynamik_3' fields, respectively. class Model1(models.Model): malfunction_1 = models.CharField(max_length=255, null=True, default=None) class Model2(models.Model): given_malfunctions = models.OneToOneField(Model1, blank=True, on_delete=models.CASCADE, default=None) dynamik_2 = models.CharField(max_length=255, default=None, blank=True) class Model3(models.Model): connection_to_model2 = models.ForeignKey(Model2, on_delete=models.CASCADE, default=None) malfunction_3 = models.CharField(max_length=255, null=True, default=None, blank=True) dynamik_3 = models.CharField(max_length=255, default=None, blank=True) would you use a receiver method or define a normal function for this use case? -
How to make django not duplicate custom class logs
I wrote MyClass which i'm using inside of DRF ViewSet "create" method. In this class i declared new logger with _set_logger method. The problem is that django duplicates MyClass logs, which I don't want: MyClass _set_logger method: import logging class MyClass: def _set_logger(self) -> None: self.log = logging.getLogger('logger_name') sh = logging.StreamHandler() sh.setLevel(logging.ERROR) formatter = logging.Formatter( "%(name)s | %(levelname)s | %(funcName)s | %(message)s" ) sh.setFormatter(formatter) self.log.addHandler(sh) The way i'm using MyClass in ViewSet "create" method: class SomeViewSet(ModelViewSet): def create(self, request, *args, **kwargs): obj = MyClass() obj.do_something(request) return super().create(request, *args, **kwargs) Logs: # my logs logger_name | funcName | CRITICAL | error_msg # django logs CRITICAL 2023-08-17 00:10:44,138 module_name 11 140294782023360 error_msg I tried changing logger_name to __name__ , expecting django and MyClass to use the same logger, but that didn't happen. class MyClass: def _set_logger(self) -> None: self.log = logging.getLogger(__name__) -
How to initialize Django database without using existing migrations?
I have a Django project, which contains dozens of migrations, and I want to initialize it on a new database. How do I do this without running all the migrations, which can take a lot of time to run? In earlier versions of Django, it used to have a "syncdb" command that you could run to create all tables in a blank database, bypassing all migrations. Current Django's migrate command has a --run-syncdb option, but the docs say: Creates tables for apps without migrations. Since all my apps have migrations, I interpret this to mean it does nothing in my case. Does modern Django no longer have anyway to initialize a database without tediously running through every single migration? Note, I'm not asking how to initialize a Django database. I'm asking how to do it more efficiently than by running migrations, which are designed to modify an existing database, not initialize one from scratch. -
Save generated image to model AND upload to S3?
I cannot find documentation on how to do what I need to do. My goal(s): User fills out a form with basic info Server-side a qr code is generated for that user. This qr code image needs to be uploaded to S3 to not bog down the server storage. This needs to be referenced in a model. WHY? This image will need to be displayed later in various front-end frameworks so at least the URL should be somewhere. It is stated lower but note: the s3 upload IS functional via form in admin. Currently I am building this out as an API to be used by various front-end frameworks so no forms in django will be used. All code is in testing mode so there is currently no security (just FYI). I am just trying to get this functionality working. Current model: from django.db import models # Customer model only class Customers(models.Model): customerId = models.CharField(max_length=25, unique=True) qr = models.FileField(upload_to='media/') #THIS IS WHERE IT WOULD BE STORED email = models.EmailField(unique=True) password = models.CharField(max_length=255) phone = models.CharField(max_length=20, unique=True) displayTag = models.CharField(max_length=255, unique=True) Views.py that is doing the saving from django.shortcuts import render from django.http import JsonResponse as j from qrewards_api_pj.helper import generate_id, … -
Django collectstatic ends up with "AWS S3 Boto3 Python - An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied"
I'm using Heroku+S3+Cloudfrong and I'm facing the titled error when trying to collectstatic. I'm having all the necessary IAM permissions, including AmazonS3FullAccess. The django settings set AWS_DEFAULT_ACL=None. My S3 bucket is configured with "Object Ownership" with "ACLs enabled" and it unblocks all public access (i.e. all set as public). Bucket Policy: { "Version": "2008-10-17", "Id": "PolicyForCloudFrontPrivateContent", "Statement": [ { "Sid": "AllowCloudFrontServicePrincipal", "Effect": "Allow", "Principal": { "Service": "cloudfront.amazonaws.com" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::<my_bucket>/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::<my_stream>:distribution/<my_id>" } } } ] } Bucket CORs: [ { "AllowedHeaders": [ "Authorization" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 }, { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "HEAD", "GET", "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [ "ETag", "x-amz-meta-custom-header" ] } ] The closest case I found here is AWS S3 Boto3 Python - An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied but it doesn't solve my issue... Thanks ahead -
Ngnix + Django + Gunicorn not found static and media
I'm trying to deploy the site on the server, but static and media are not loaded on it. I tried to juggle the url pattern and config nginx, but all in vain. The most interesting thing is that he loads only index.css, and does not see all the others server { listen 443; server_name domain.com; location /media { alias /root/djangoproj/media; } location /static { alias /root/djangoproj/static; } location / { proxy_pass http://unix:/run/gunicorn.sock; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_no_cache 1; proxy_cache_bypass 1; } } I tried to juggle the url pattern and config nginx -
Docker container Django debug mode true, still production mode
I have dockerized django app. And I have an .env file with debug=1. But when I run the docker container it is in apparently in production mode: debug=false. This is my docker-compose file: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" env_file: - ./.env volumes: - ./zijn:/app command: > sh -c " python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" environment: - DB_HOST=db - DB_NAME=zijn - DB_USER=zijn - DB_PASS=235711 - DEBUG=1 depends_on: - db db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data/ environment: - POSTGRES_DB=dzijn - POSTGRES_USER=zijn - POSTGRES_PASSWORD=235711 volumes: dev-db-data: dev-static-data: and the .env file: DEBUG=1 SECRET_KEY="django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u" DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] DB_NAME="zijn" DB_USER="zijn" DB_PASS="235711" DB_HOST=db DB-PORT=54326 And also my settings.py is debug mode=True: SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG') == "True" ALLOWED_HOSTS = [] ALLOWED_HOSTS_ENV = os.environ.get('ALLOWED_HOSTS') if ALLOWED_HOSTS_ENV: ALLOWED_HOSTS.extend(ALLOWED_HOSTS_ENV.split(',')) Because it returns the message: dotenv.read_dotenv() dwl_backend-app-1 | CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. And also the templates are not loaded. Question: how to start docker container with debug=True? -
Why am I seeing an NGINX 502 error in Chrome, only on MacOS?
I have a very strange issue happening. Multiple users have reported it, across multiple computers, and multiple sites. They keep getting an NGINX 502 error. It only occurs on Google Chrome. It has only been reported from users using MacOS. I have not been able to recreate the issue I haven't found anything in logs, aside from I can see the access failure. The only commonality between the sites, is they have all been a Django/NGINX/Uwsgi stack on CentOS. The issue is not present if the user switches to incognito. The issue persists if the website cache is cleared. The issue disappears if the entire browser cache is cleared. One site is new, the other is old and has not had a configuration change since the problem began. The problem is sporadic, and seemingly random. First noted in the past ~1 month. Any thoughts on this would be helpful. Since I can't recreate the issue, I am having a hard time troubleshooting. Thanks in advance. -
Django Select2 field query return no select options
On a Django model, I have a foreign key field 'owner', refer to User model. I have a view class and form class for the model instance creation page. I made the form 'owner' field using select2 widget as below. All worked fine. class OwnerWidget(ModelSelect2Widget): search_fields = ["name__istartswith", "email__icontains",] Now I changed the page to use bootstrap modal. All other model fields behaved okay but not the 'owner' field: when I type in search characters like 'te', it start to send query to the server, but server returned 404 not found. See log below. "GET /select2/fields/auto.json?term=te&_type=query&q=te HTTP/1.1" 404 2699 I have nowhere configured the path '/select2/fields/auto.json'. I guess it's select2 default path. Did I miss anything on the view or form classes in order for this path to work? or I need to configure a different URL path somehow base on my view and form? I added line below to the widget, but no help. model = settings.AUTH_USER_MODEL I have no clue how this select2 search work. Any help appreciated. -
Change email verify code to 6 digits code in authemail django
I am using authemail for email verifications of users. I need to change code's length to 6 and make it only digits. In authemail models I have following function and I want to override it. This function is not in any class. def _generate_code(): return binascii.hexlify(os.urandom(20)).decode('utf-8') I am attaching link so you can check models yourself authemail I have tried to override this function in my models like following but Its instead of my custom function, authemail's function is called. from django.db import models from authemail.models import EmailUserManager, EmailAbstractUser, SignupCodeManager, SignupCode import os import binascii from .auth import custom_generate_code class CustomSignupCodeManager(SignupCodeManager): def create_signup_code(self, user, ipaddr): code = custom_generate_code() signup_code = self.create(user=user, code=code, ipaddr=ipaddr) return signup_code def set_user_is_verified(self, code): try: signup_code = self.get(code=code) signup_code.user.is_verified = True signup_code.user.save() return True except self.model.DoesNotExist: pass return False class MyCustomSignupCode(SignupCode): objects = CustomSignupCodeManager() -
There is a problem for updating database using forms.form in Django and I want use only one 'update' button to update many database data
what I want do make is that show the existing data in the database to a user through HTML page. let a user update the existing data if he wants to do. Promblem 1> the problem is that,when running my code, a user input the new data and clicked 'update' button, but the update did not work. I don't know whether it is the reason or not, anyway, when I put 'def show_data' and 'def input' together, updating did work well. However 'def show_data'and 'def input' should be separate. 'def show_data' : it is for saving the data from excel file into the database using pandas 'def input': it is for receiving the input data from a user and updating the existing data with the input data Promblem 2> There are many 'update' button in the web page. I want to make only one 'update' button at the bottom of web page for updating all data user input into the database. Please refer to the below codes and result image. <forms.py> from django import forms from report.models import Upload, Memo class InputForm(forms.Form): item_id = forms.IntegerField(widget=forms.HiddenInput()) memo = forms.CharField() user_input = forms.CharField() <models.py> from django.db import models class Memo(models.Model): memo = … -
"I get utf-8 error when django makemessages command runs"
Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "myvenv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "myvenv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "myvenv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "myvenv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 430, in handle potfiles = self.build_potfiles() ^^^^^^^^^^^^^^^^^^^^^ File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 508, in build_potfiles self.process_files(file_list) File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 599, in process_files self.process_locale_dir(locale_dir, files) File "myvenv\Lib\site-packages\django\core\management\commands\makemessages.py", line 675, in process_locale_dir msgs, errors, status = popen_wrapper(args) ^^^^^^^^^^^^^^^^^^^ File "myvenv\Lib\site-packages\django\core\management\utils.py", line 26, in popen_wrapper p.stdout.decode(stdout_encoding), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 978: invalid start byte When I run the "django makemessages" command, I keep getting this error. I've gone through all the files in a loop to check for UTF-8 issues, but I couldn't find any. I've verified that all my files are encoded in UTF-8, but I still keep encountering this error. -
The X variable is not set. Defaulting to a blank string
I have a django secret key in a .env which is being read as a blank string part of the secret key is attached below SECRET_KEY=|$u6qthu06zp|$q at the point where the $ sign starts I keep getting the message level=warning msg="The "u6qthu06zp" variable is not set. Defaulting to a blank string." level=warning msg="The "q" variable is not set. Defaulting to a blank string." the settings file has import os import environ PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) env = environ.Env(DEBUG=(bool,False)) environ.Env.read_env(env_file=".env") and in the final secret key is written SECRET_KEY = env("SECRET_KEY") however I am not being able to run the docker-compose build --remove-orphan as the SECRET_KEY is coming back as an empty string seemingly because the $ sign is causing some kind of failure. Any advice will be appreciated -
Django i18n is not detecting texts inside the for loop
I couldn't understand why the i18n is not detecting the data in my loop: {% trans service.title %} anyone who can help!? Thanks in advance! {% load i18n %} {% for service in services %} <div class="col-sm-3"> <div class="service bg-white"> <div class="img-block"> <img alt="" class="service-img img-fluid" src="{{service.img.url}}"> </div> <div class="service-feature"> <h4 class="feature-text text-center"> {% trans service.title %} </h4> <p>{{service.desc}}</p> </div> </div> </div> {% endfor %} I tried several different ways such: {% translate service.title %} no reactions {{ service.title|trans }} no reactions -
Displaying Real-time Data from Arduino IDE to Django
I am new to Django. Is there a possible way to display the value from the Arduino IDE to Django in real time? The data that displays in the inserted coins came from Arduino, but it does not automatically change unless you refresh the site. views.py from django.shortcuts import render import serial def home (request): return render(request, 'home.html' ) def usb (request): try: arduino = serial.Serial('COM6', 9600) data = arduino.readline().decode().strip() arduino.close() except Exception as e: data = f"Error communicating with Arduino: {str(e)}" return render(request, 'usb.html', {'data' : data}) def nfc (request): return render(request, 'nfc.html') def bluetooth (request): return render(request, 'bluetooth.html') usb.html <div class="estimated-price"> <label>Inserted Coins:</label> <span id="inserted-coins">₱{{data}}</span> </div> The data that displays in the inserted coins came from the arduino but it does not change automatically, i also need to refresh the page in order to update the data enter image description here Is there a way to display the data in real-time without refreshing the file? -
Wagtail custom permissions
I have a wagtail site. I have certain pages that I only want certain users to be able to access. I have used the standard django permissions setup to do this: models.py class Case(TimeStampedModel): case_userdefined_id = models.CharField( max_length=17, null=False, blank=False, unique=True, default='default' ) user = models.ForeignKey( get_user_model(), blank=False, null=True, on_delete=models.SET_NULL) class Meta: permissions = (("can_access_case", "Can Access case"),) views.py class CreateCaseView(PermissionRequiredMixin, CreateView): permission_required = 'Case.can_access_case' print('test2') template_name = 'cases/create_case.html' form_class = CaseForm success_url = reverse_lazy('patients') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = CaseForm() context['form'] = form return context wagtail_hooks.py from django.contrib.auth.models import Permission from wagtail import hooks @hooks.register('register_permissions') def view_restricted_page(): return Permission.objects.filter(codename="can_access_case") Then in the wagtail admin I have created a group 'case_access' and ticked the custom permissions to allow access. I have then made various users members of this group. However these users still get a '403 forbidden' screen, it is only superusers that can access the relevant pages. What else do I need to do? -
Having problem in rendering forms for each instance
I am creating a quiz website. Within the website there are multiple quiz topics, where each topic has a set of questions and each question has a set of answers as option. When i select a quiz topic I want it to show the questions and options. I tried doing the following. I created the following models difficulty_choices=(('easy','easy'),('hard','hard'),('medium','medium')) class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) TimeLimit=models.IntegerField(blank=True) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE,null=True,blank=True) and forms.py is class QuizForm(forms.ModelForm): class Meta: model = Quiz fields = ['text'] exclude = ["text"] # Add other fields as needed selected_answer = forms.ChoiceField( label="", choices=[], # We'll update choices dynamically widget=forms.RadioSelect ) def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) quiz_instance = kwargs.get('instance') questions = quiz_instance.get_questions() answer_choices = [] for question in questions: answers = question.get_answers() answer_choices=[(answer.id, answer.text) for answer in answers] self.fields["selected_answer"] = forms.ChoiceField( label='select the correct option', choices=answer_choices, widget=forms.RadioSelect ) Here in forms I have used the for loop to iterate through each question … -
how to send an email to a particular account wid user'contact when that particular user clicks on a button
when an user clicks on a specific button, I want that user's mobile number (that they entered when they registered for an account) to be sent to a particular email i tried using js code (addeventlistener). also im doing it in django and the mobile number field and the place where im using js are in two different apps. document.addEventListener('DOMContentLoaded', function() { document.getElementById('send-button').addEventListener('click', function (event) { event.preventDefault(); var mobileNumber = document.getElementById('mobile_number').value; // Send mobile number to Django view using AJAX var xhr = new XMLHttpRequest(); xhr.open('POST', '{% url "send_mobile_number" %}', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { alert('Mobile number sent successfully.'); } else { alert('Failed to send mobile number.'); } } }; xhr.send('mobile_number=' + encodeURIComponent(mobileNumber)); }); }); -
How to List Categories with Dropdown in Django
I would like to add a dropdown menu to my Django project that lists all categories from the database. The challenge I'm facing is that while I can get the categories listed on a single page (category), I would like them to be accessible throughout the entire website. I would really appreciate if someone helps. Thanks in advance. views.py #dropdown list of categories class CategoryListView(View): template_name = 'media/categories_dropdown.html' def get(self, request, *args, **kwargs): categories = Category.objects.all() return render(request, self.template_name, {'categories': categories}) urls.py path('category/', CategoryListView.as_view(), name='category-list'), media/categories_dropdown.html {% for category in categories %} <option value="{{ category.slug }}">{{ category.name }}</option> {% endfor %}