Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when scrapping Selenium and Firefox
I have a scrapper inside my Django project. It works on Selenium + Firefox My Dockerfile # Install geckodriver # Copied from: https://hub.docker.com/r/selenium/node-firefox/dockerfile ARG GECKODRIVER_VERSION=0.26.0 RUN wget --no-verbose -O /tmp/geckodriver.tar.gz https://github.com/mozilla/geckodriver/releases/download/v$GECKODRIVER_VERSION/geckodriver-v$GECKODRIVER_VERSION-linux64.tar.gz \ && rm -rf /opt/geckodriver \ && tar -C /opt -zxf /tmp/geckodriver.tar.gz \ && rm /tmp/geckodriver.tar.gz \ && mv /opt/geckodriver /opt/geckodriver-$GECKODRIVER_VERSION \ && chmod 755 /opt/geckodriver-$GECKODRIVER_VERSION \ && ln -fs /opt/geckodriver-$GECKODRIVER_VERSION /usr/bin/geckodriver Selenium container in docker-compose selenium: image: selenium/standalone-firefox:latest hostname: firefox ports: - "4444:4444/tcp" shm_size: "2gb" restart: unless-stopped I'm getting an error when I init my scrapper class from selenium import webdriver from selenium.webdriver import DesiredCapabilities class Scrapper: WEBDRIVER_TIMEOUT = 2 WEBDRIVER_ARGUMENTS = ( "--disable-dev-shm-usage", "--ignore-certificate-errors", "--headless", ) def __init__(self, useragent=None): self.options = webdriver.FirefoxOptions() for argument in self.WEBDRIVER_ARGUMENTS: self.options.add_argument(argument) self.driver = webdriver.Remote( command_executor="http://127.0.0.1:4444/wd/hub", desired_capabilities=DesiredCapabilities.FIREFOX, options=self.options, ) self.driver.set_page_load_timeout(self.WEBDRIVER_TIMEOUT) Error raise MaxRetryError(_pool, url, error or ResponseError(cause)) | urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=4444): Max retries exceeded with url: /wd/hub/session (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2c4df553c0>: Failed to establish a new connection: [Errno 111] Connection refused')) Selenium successfully is on http://localhost:4444/ui I don't know how to fix it. -
nginx not serving static files for django, searching in an other folder
I am deploying my django project to server using Nginx and Gunicorn static files are not loading. 2023/11/07 05:17:42 [error] 68970#68970: *40 open() "/home/pau/perp2.0/perp/staticfiles/static/admin/js/core.js" failed (2: No such file or directory) The nginx is searching the file in /home/pau/perp2.0/perp/staticfiles/static/ but the directory for the static files is just /home/pau/perp2.0/perp/staticfiles without the last static my file configuration for nginx is this server { listen 80; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/pau/perp2.0/perp/staticfiles; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } and just in case my settings.py for the static files part is this: `# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, '../static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = "whitenoise.storage.CompressedStaticFilesStorage" )` I just one to serve the static files in the correct directory, thanks. If you can explain, the solution, will be great. -
No module named 'rng_base'
It's error when I run python manage.py runserver. I google but no answer can fix my error please help. File "/Users/ahkomu/Documents/myproject/account/models.py", line 21, in <module> from utils.encryption import AESCipher File "/Users/ahkomu/Documents/myproject/utils/encryption.py", line 4, in <module> from Crypto import Random File "/Users/ahkomu/Documents/myproject/venv/lib/python3.9/site-packages/Crypto/Random/__init__.py", line 28, in <module> from Crypto.Random import OSRNG File "/Users/ahkomu/Documents/myproject/venv/lib/python3.9/site-packages/Crypto/Random/OSRNG/__init__.py", line 32, in <module> from Crypto.Random.OSRNG.posix import new File "/Users/ahkomu/Documents/myproject/venv/lib/python3.9/site-packages/Crypto/Random/OSRNG/posix.py", line 32, in <module> from rng_base import BaseRNG ModuleNotFoundError: No module named 'rng_base' -
Bootstrap modal not sending a request to django view for rendering model form
I'm currently working on a django project that manages inventory of biological samples. I have a specimen details page that renders four tables with data associated with the selected specimen. In each of these tables I have an Edit button where the user can update a record associated with the specimen. Right now, when the button is clicked, a new page is opened and the update form is rendered. I'd like to use a bootstrap modal to create a popup of the form instead of having to go to a whole new page. I already created something similar on the home page for adding a new specimen record and it works great. For some reason tryin the same thing on the details page will not work. The modal does pop up, but the form does not render and it seems like the issue is that there is no request being sent to the edit_specimen url/view even though it is specified. Im wondering if it has to do with urls and the pk being in the url for this operation. I've tried several things and I can't get it to work. Any advice is appreciated as I am relatively new to … -
i get a form validation error when i want to create lisitng in django
i want to create a listing based on my model with django form but i get a validation probleme when i try to submit my new listing with the price field (foreinkey to bid class), Select a valid choice. That choice is not one of the available choices., i dont want how i can fix it model.py class Bid(models.Model): bid = models.PositiveIntegerField(default="", blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid") def __str__(self) -> str: return f" {self.bid}" class Listing(models.Model): title = models.CharField(max_length=64) descreption = models.TextField() price = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid") image = models.URLField(max_length=200) active = models.BooleanField(default= True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True, related_name="category") user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") watch = models.ManyToManyField(User, null=True, blank=True, related_name="watch") def __str__(self) -> str: return f"{self.title} By {self.user}"` form.py from django import forms from django.forms import ModelForm, Textarea from auctions.models import Listing class Listing(ModelForm): class Meta: model = Listing fields = [ 'title','descreption','image', 'category', 'price', 'active'] widgets = { 'price': forms.NumberInput } views.py def create(request): if request.method == "POST": form = Listing(request.POST) user = request.user price = request.POST["price"] bid = Bid(bid=int(price), user=user) bid.save() if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: error = form.errors return render(request, "auctions/create.html", { "error" : error }) … -
Check if Django is able to connect with given parameters or return an error message, instead of causing an internal server error (500)
I'm trying to build dynamic connections to databases. This because I just now and then have to query them to get some data. The sources change over time, so I'm not in favor of adding them to settings. Currently I have the following code: DBTYPE = ( ('postgres', ('PostgreSQL')), ('mysql', ('MySQL')), ('mysql', ('MariaDB')), ('oracle', ('Oracle')), ('mssql', ('MSSQL')), ('sqlite', ('SQLite')), ) URLTEMPLATES = ( ('postgres', ('postgres://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('mysql', ('mysql://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('oracle', ('oracle://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('mssql', ('mssql://{USER}:{PASSWORD}@{HOST}:{PORT}/{NAME}')), ('sqlite', ('sqlite:///{HOST}')), ) dburl = [item for item in URLTEMPLATES if item[0] == self.engine] self.db_url = dburl.format(**template_values) dbsetting = dj_database_url.parse(self.db_url,conn_max_age=600,conn_health_checks=True,) database_id = self.name newDatabase = {} for conn in connections.all(): print(conn) try: newDatabase["id"] = database_id newDatabase['ENGINE'] = dbsetting['ENGINE'] newDatabase['NAME'] = dbsetting['NAME'] newDatabase['USER'] = dbsetting['USER'] newDatabase['PASSWORD'] = dbsetting['PASSWORD'] newDatabase['HOST'] = dbsetting['HOST'] newDatabase['PORT'] = dbsetting['PORT'] newDatabase['ATOMIC_REQUESTS'] = True newDatabase['TIME_ZONE'] = 'Europe/Paris' newDatabase['CONN_HEALTH_CHECKS'] = False newDatabase['CONN_MAX_AGE'] = 600 newDatabase['OPTIONS'] = {} newDatabase['AUTOCOMMIT'] = False connections.databases[database_id] = newDatabase cursor = connections[database_id].cursor() cursor.close() What I would like to achieve is, that when Django is unable to connect, it just responds with a message that connection could not be established. Now I get, for example: Exception Type: OperationalError Exception Value: (1045, "Access denied for user 'test'@'localhost' (using password: YES)") In those case I would just … -
celery beat ExpressionDescriptor.py get_full_description
I hope your day is going well. I've hit a bit of a snag with a Django project I’m working on. I'm relatively new to Django and would deeply appreciate it if you could spare a moment to help me troubleshoot an issue. I'm using Celery Beat for scheduling periodic tasks. I have a view in the admin where I check and set periodic tasks, but recently a strange error has appeared, and I can't locate the issue. Whenever I try to open any admin view with periodic tasks, I get this type of error: It indicates a problem with resolving the names of the crontabs: During handling of the above exception (invalid literal for int() with base 10: '0DAY'), another exception occurred: But I haven't changed anything in the database or modified anything with settings. Do you know how I can resolve this issue, or where to look for a solution? It's probably a default setup and nothing there is set or modified, and I also couldn't find any solution to my problem on the internet :( I'm using : django-celery-beat==2.5.0 Django==4.2.2 I do not have any external settings to celery beat in django project :( -
Password change form URL in Django admin cannot find user with correct ID
I'm having some trouble with my admin settings. I am using a custom user model (called Org, for context), and everything works perfectly in the admin except for the password change form. For clarity, I'm talking about the little form that says "Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form." However, when I click on "this form", I'm redirected back to the admin homepage, with the warning "Org with ID '40/password (40 being the ID)' doesn’t exist. Perhaps it was deleted?" Examples of inline and admin # all inlines look like this: class OrgContactInfoInline(admin.TabularInline): model = OrgContactInfo @admin.register(Org) class OrgAdmin(admin.ModelAdmin): inlines = [OrgContactInfoInline, OrgInfoInline, OrgLocationInline, ItemInline] add_form = CustomUserCreationForm form = CustomUserChangeForm model = Org ordering = ("-org_name",)``` Important forms class CustomUserCreationForm(UserCreationForm): password = forms.CharField( widget=forms.PasswordInput(), label=mark_safe( "Your password must:<br />-Be longer than 8 characters<br />-Have an uppercase and lowercase characters<br />-Use a special character/number" ), ) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Org fields = ["org_name"] class CustomUserChangeForm(UserChangeForm): class Meta: model = Org fields = ["org_name"] URLs urlpatterns = [ #my urls path('', include('apps.homepage.urls')), path('accounts/', include('apps.accounts.urls')), path('mynonprofit/', include('apps.dashboard.urls')), #django urls path('accounts/', include('django.contrib.auth.urls')), … -
How to syncronize the elimination of two components
Lets say I have two componentes that display a common component when I make a delete request to the api inside one of the componentes the other component does not get deleted until I refresh the browser how can I fix that such that the common component gets eliminated at the same time here are the components: import React, { useEffect, useState } from "react"; import { getTasks } from "../api/task.api"; import { TaskCard } from "./TaskCard"; export function TaskLists() { const [tasks, setTasks] = useState([]); useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data); setTasks(res.data); } loadTasks(); }, []); const removeTask = (id) => { setTasks(tasks.filter((task) => task.id !== id)); }; return ( <div> {tasks.map((task) => ( <TaskCard key={task.id} task={task} onDelete={removeTask} /> ))} </div> ); } and import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { getTasks } from "../api/task.api"; import { TaskCard } from "./TaskCard"; export function Daycard({ hashv }) { let b = 0; const [tasks, setTasks] = useState([]); useEffect(() => { async function loadTasks() { const res = await getTasks(); console.log(res.data); setTasks(res.data); } loadTasks(); }, []); const removeTask = (id) => { setTasks(tasks.filter((task) => task.id … -
Couldn't import Django after updating to windows 11
When I run "python manage.py runserver" the following error occurs: Traceback (most recent call last): File "F:\blear\manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\blear\manage.py", line 21, in <module> main() File "F:\blear\manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? how can I solve. ps: this error occurred after updating to windows 11 image i hope solve this problem -
'CustomUser' object is not iterable
serializers.py class UserprofileSerializer(ModelSerializer): class Meta: model = Profile fields = ['id','mobile','pincode', 'address','profileimage','coverImg'] class UserSerializer(ModelSerializer): profile = UserprofileSerializer(required=True,) class Meta: model = CustomUser fields = ['email', 'first_name', 'created_at','profile'] views.py class profiledata(mixins.RetrieveModelMixin, mixins.ListModelMixin, generics.GenericAPIView): serializer_class = UserSerializer lookup_field = 'id' authentication_classes = [ JWTAuthentication, TokenAuthentication, SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated, ] def get_queryset(self): user = CustomUser.objects.get(email=self.request.user) return user def get(self, request, id=None): if id: return self.retrieve(request) else: item = self.list(request) return item when i try to get single data and serializers them, this time generated the error 'CustomUser' object is not iterable -
calling a view without passing request
I have a view that is called like this. def device_check(request, d, i): # A bunch of stuff the view does When i call this view by default it works perfect no issues, then i have another function that generates some data and tries to call that function to check and i keep getting the error that its not passing enough arguments, since i am trying to use it like this def test_function(request): test = device_check("test", "i-1799") And i understand the error is being caused because i am not passing it the request parameter like so device_check(request, "test", "i-1799") But i have no idea how i would pass it the request parameter from within another function. Is there a better way of doing this, or a way around that? -
Cannot Grab request.get_host() from Django Request to get real domain name
I use docker and nginx to run my system but I am hitting an issue now to where I would like to redirect client users of my system automatically to a subdomain. i.e. something like prod.example.com. This already works in my nginx config to duplicate access to the page, but I would like to map specific client urls to the subdomain, not the main one. Normally this would be simple in Django using something like: if not 'app.' in request.get_host(): redirect(f'app.{request.get_host()}') # example # get_host()=app | get_absolute_ur()=http://app/, meta: app But my nginx proxy pass uses an upstream variable, and it appears that is all that is posted through with the variables tried above. How can I get this done? upstream app { server web:8000; # appserver_ip:ws_port } server { server_name prod.example.com; listen 80; client_max_body_size 250M; # enforces HSTS or only content from https can be served. We do this in CloudFlare add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; add_header Permissions-Policy "autoplay=(), encrypted-media=(), fullscreen=(), geolocation=(), microphone=(), browsing-topics=(), midi=()" always; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://app; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; } } -
Django CreateView within Navbar
I have a base_page.html which includes navbar (utilizing {% include %} tag). The idea is to place trigger (a tag in my case) within navbar which calls a CreateView globally (where the navbar displays) around a project. So far I managed to place an a tag which triggers CreateView displays a modal window with form. But problem is a View renders designed to render a single page that makes hard to use that CreateView within a project globally. Wondering if there is a way to use CreateView within a navbar everywhere it displays. {% load static %} <div class="logo_pic"><a href=""><img src={% static "img/navbar_icons/temp_logo.svg" %} alt="logo_pic"></a></div> <div class="nav_menu"> <div class="nav_menu_top"> <a href=""><img src={% static "img/navbar_icons/home_icon.svg" %} alt="home-button-icon"></a> <a href=""><img src={% static "img/navbar_icons/transaction_icon.svg" %} alt="transaction-icon-button"></a> </div> <div class="nav_menu_bottom"> <a id="openModalBtn"><img src={% static "img/navbar_icons/add_new_transaction_icon.svg" %} alt="new_transaction"></a> </div> <!-- Modal window --> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close" id="closeModalBtn">&times;</span> <h2>Create new transaction</h2> <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </div> </div> </div> -
manage.py migrate on Amazon Linux 2023
I am trying to deploy my django environment on aws linux 2023 and I have a file with command for migration: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true Then I get an error in cfn-init.log 2023-11-06 19:01:44,570 [ERROR] Command 01_migrate (source /var/app/venv/*/bin/activate && python3 manage.py migrate) failed 2023-11-06 19:01:44,570 [ERROR] Error encountered during build of postbuild_0_hq_app: Command 01_migrate failed Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 277, in build changes['commands'] = CommandTool().apply( File "/usr/lib/python3.9/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed 2023-11-06 19:01:44,571 [ERROR] -----------------------BUILD FAILED!------------------------ 2023-11-06 19:01:44,571 [ERROR] Unhandled exception during build: Command 01_migrate failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 181, in <module> worklog.build(metadata, configSets, strict_mode) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 137, in build Contractor(metadata, strict_mode).build(configSets, self) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 567, in build self.run_config(config, worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 277, in build changes['commands'] = CommandTool().apply( File "/usr/lib/python3.9/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 01_migrate failed Is command changed from linux2 to linux 2023? Thank you for your help -
getting error while trying to open websocket connection
This is the error I am getting while trying to start the websocket. I am not able Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.10/dist-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.10/dist-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) File "/usr/local/lib/python3.10/dist-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/yana/Desktop/learn/code-executor/server/./codeexec/asgi.py", line 7, in <module> from collaborate.routing import websocket_urlpatterns File "/home/yana/Desktop/learn/code-executor/server/./collaborate/routing.py", line 2, in <module> from collaborate import consumers File "/home/yana/Desktop/learn/code-executor/server/./collaborate/consumers.py", line 2, in <module> from collaborate.models import CollaborateRoom File "/home/yana/Desktop/learn/code-executor/server/./collaborate/models.py", line 2, in <module> from authentication.models import CustomUser File "/home/yana/Desktop/learn/code-executor/server/./authentication/models.py", line 2, in <module> from .manager import UserManager File "/home/yana/Desktop/learn/code-executor/server/./authentication/manager.py", line 1, in <module> from django.contrib.auth.base_user import BaseUserManager File "/usr/local/lib/python3.10/dist-packages/django/contrib/auth/base_user.py", line 57, in <module> class AbstractBaseUser(models.Model): File "/usr/local/lib/python3.10/dist-packages/django/db/models/base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.10/dist-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.10/dist-packages/django/apps/registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded … -
Please am trying to pip install mysqlclient in windows and am always getting this error even in cmd
enter image description here This is the error that always pops up Actually am trying to configure mysql database with django on Windows and this step is required but anytime i try to pip install the mysqlclient this error keeps on showing up,please can somone show me how to solve this issue -
Error Assigning Foreign Key in Django CreateView, can't get an instance
Issue: Cannot Assign "38" to "Pusinex2.seccion" - Must Be a "Seccion" Instance Models: The models Seccion and Pusinex2 are related in a ForeignKey manner. Seccion holds the primary key field and other details related to a section. Pusinex2 has a foreign key relationship with Seccion along with fields for date, file, and user traceability. Views: A PUSINEXForm is defined in the forms.py, linking various form fields to the respective model fields. The CreatePUSINEX view handles the form submission, using PUSINEXForm and Pusinex2. Error: The error is encountered during form submission: ValueError at /creation/. Specifically: "Cannot assign '38' to 'Pusinex2.seccion' - Must Be a 'Seccion' instance." The issue arises in the CreatePUSINEX view's form_valid method. Here's my models: class Seccion(models.Model): distrito = models.ForeignKey(Distrito, on_delete=models.CASCADE) municipio = models.ForeignKey(Municipio, on_delete=models.CASCADE) seccion = models.PositiveSmallIntegerField(primary_key=True) tipo = models.PositiveSmallIntegerField(choices=CAT_TIPO) activa = models.BooleanField(default=True) class Pusinex2(models.Model): seccion = models.ForeignKey(Seccion, on_delete=models.CASCADE) f_act = models.DateField() hojas = models.PositiveSmallIntegerField() observaciones = models.TextField(blank=True, null=True) archivo = models.FileField(upload_to=pusinex_file, blank=True, null=True) # Trazabilidad user = models.ForeignKey(User, editable=False, on_delete=models.CASCADE) a FormView: class PUSINEXForm(forms.ModelForm): seccion = forms.IntegerField() f_act = forms.DateField() hojas = forms.IntegerField() archivo = forms.FileField() observaciones = forms.CharField(widget=forms.Textarea, required=False) And a related CreateView: class CreatePUSINEX(LoginRequiredMixin, CreateView): template_name = 'control/pusinex_form.html' form_class = PUSINEXForm model = Pusinex2 … -
Swagger not working correctly through Nginx
We are developing web application in our class, and one of the tasks is to configure swagger for documentation. I did it, and it works perfectly. However, next we had to configure nginx and now when sending request with swagger through nginx it isn't requesting correct url (it requests http://127.0.0.1/api/v1/albums/ instead of http://127.0.0.1:82/api/v1/albums/) This is my config for swagger location /api/v1/swagger/ { proxy_pass http://127.0.0.1:8000/swagger/; 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; } (I am developing web app with django, for swagger i'm using drf_yasg) I tried adding 'API_URL': 'http://127.0.0.1:82/api/v1/', in my SWAGGER SETTINGS in Django but it didn't fix anything -
How do I copy the values of a HTML table column to the clipboard using a Django template and JavaScript?
I need to copy the values of a HTML table column to the clipboard. I'm using Django templates. Here is my HTML table: <table> <tr> <th>Name</th> <th>DOB</th> <th>ID</th> <th>Guardian</th> <th>Email</th> <th>Telephone</th> <th>NIF</th> <th>Notes</th> </tr> {% for a in sessao.first %} <tr> <td>{{ a.nome }}</td> <td>{{ a.dtnasc }}</td> <td>{{ a.alunoid }}</td> <td>{{ a.educaid }}</td> <td id="a.id">{{ a.educaid.email }}</td> <td>{{ a.educaid.telefonea }}</td> <td>{{ a.nif }}</td> <td>{{ a.notas }}</td> <td><button class="btn btn-outline-success btn-sm" onclick="CopyText({{ a.id }})" data-toggle="tooltip" data-placement="top" title="Copy"> copy </button> </td> </tr> {% endfor %} </table> I'm trying this script but I get an error message: // Copy to ClipBoard function CopyText(el) { // Get the Selected Data By ID var copyText = document.getElementById(`${el}`) var str = copyText.innerHTML // Get All HTML Data and Copy to Clipboard function listener(e) { e.clipboardData.setData("text/plain", str); e.preventDefault(); } document.addEventListener("copy", listener); document.execCommand("copy"); document.removeEventListener("copy", listener); }; The error message is: Uncaught TypeError: Cannot read properties of null (reading 'innerHTML') at CopyText (lu.js:11:22) at HTMLButtonElement.onclick (2/:80:159) Any help would be much appreciated. Thanks in advance. -
My form in django is not saving data to db model
The data of form is not being saved to the db checkout table. In this code I want to give to field cart_information the value from another model that is related to user with session. The post request: [06/Nov/2023 18:44:49] "POST /order/checkout-info/ HTTP/1.1" 302 0 This is code: models.py: class Checkout(models.Model): cart_information = models.OneToOneField(Cart, on_delete=models.PROTECT) first_name = models.CharField(max_length=155) last_name = models.CharField(max_length=255) company_name = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255) street_address_1 = models.TextField() street_address_2 = models.TextField(null=True) city = models.CharField(max_length=155) state = models.CharField(max_length=155) zip_code = models.CharField(max_length=155) phone = models.CharField(max_length=255) email = models.EmailField() order_notes = models.TextField(null=True, blank=True) STATUS_LIST = ( ('pending', 'Pending'), ('processing', 'Processing'), ('cancel', 'Cancel'), ('delivered', 'Delivered') ) status = models.CharField(max_length=255, choices=STATUS_LIST, default=STATUS_LIST[0][0]) html: <form method="post"> {% csrf_token %} <div class="client-info"> <div class="part1-of"> <label for="first_name">First Name:</label> <input type="text" id="first_name" name="first_name" required /> <label for="last_name">Last Name:</label> <input type="text" id="last_name" name="last_name" required /> <label for="company_name">Company Name:</label> <input type="text" id="company_name" name="company_name" /> <label for="country">Country:</label> <input type="text" id="country" name="country" required /> <label for="street_address_1">Street Address 1:</label> <textarea id="street_address_1" name="street_address_1" required></textarea> <label for="street_address_2">Street Address 2:</label> <textarea id="street_address_2" name="street_address_2"></textarea> </div> <div class="part2-of"> <label for="city">City:</label> <input type="text" id="city" name="city" required /> <label for="state">State:</label> <input type="text" id="state" name="state" required /> <label for="zip_code">Zip Code:</label> <input type="text" id="zip_code" name="zip_code" required /> <label for="phone">Phone:</label> <input … -
Cannot write to sqlite3 in docker container
I am starting to get my feet wet attempting to deploy a django/react app up on an EC2 instance. Everything is running fine on my personal Windows computer but when I pulled the code into the Ubuntu 22.04.3 container I got the following error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (attempt to write a readonly database) As I said this worked fine on my Windows laptop but is not working in Linux. Is this an issue with Linux or my Dockerfile? I plan to eventually use a postgres instance once I am feeling confident, but maybe I should just do it? Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python # Stage1: Create Wheels FROM python as python-build-stage ARG BUILD_ENVIRONMENT=local # required for make and setup for postgres (not used yet) RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev COPY Backend/requirements . RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt # Stage 2: Setup Django FROM python as python-run-stage ARG BUILD_ENVIRONMENT=local ARG APP_HOME=/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} RUN addgroup --system django \ && adduser --system --ingroup django django RUN apt-get update && apt-get install --no-install-recommends -y \ libpq-dev \ netcat … -
When i open my admin panel in django they show me the error
Please anyone tell me what I can do. whenever I save my project and open the admin-panel they show the error " raceback (most recent call last): File "C:\Program Files\Python311\Lib\site-packages\django\db\models\fields_init_.py", line 2053, in get_prep_value return int(value=0) ^^^^^^^^^^^^ TypeError: 'value' is an invalid keyword argument for int() The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\contrib\admin\sites.py", line 441, in login return LoginView.as_view(**defaults)(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\decorators\debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\utils\decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\views\decorators\cache.py", line 62, in wrapper_view_func response = view_func(request, … -
Django Admin Panel Customization, Custom method for generating student fee vocuher in School Management System Admin panel
@admin.register(Student) class StudentAdmin(admin.ModelAdmin): actions = ['generate_fee_vouchers',] def generate_fee_vouchers(self, request, queryset): rule = VoucherGenerationRule.objects.latest('created') try: with transaction.atomic(): for student in queryset: if student.student_status not in ["LEFT", "FREEZE"]: if student.student_fee_structure: fee_structure = student.student_fee_structure # Generate the voucher number based on your logic voucher_no = student.roll_no + str(rule.issue_date.year)[-2:] + str( rule.issue_date.month).zfill(2) total_fee = ( fee_structure.total + student.arrears + rule.extra_charges + fee_structure.fine) - student.advance # Try to get an existing voucher for the student with the same voucher number total_fee_after_due_date = total_fee + rule.late_payment_fine student_fee_voucher = StudentFeeVoucher.objects.filter( voucher_number=voucher_no, student=student, fee_structure=fee_structure ).first() if student_fee_voucher: # # If the voucher already exists, update its attributes voucher_url = reverse('admin:student_management_studentfeevoucher_change', args=[student_fee_voucher.id]) student_fee_voucher.due_date = rule.due_date student_fee_voucher.issue_date = rule.issue_date student_fee_voucher.arrears = student.arrears student_fee_voucher.advance = student.advance student_fee_voucher.tuition_fee = fee_structure.tuition_fee student_fee_voucher.dev_fund = fee_structure.development_fund student_fee_voucher.misc_fee = fee_structure.misc student_fee_voucher.late_payment_fine = rule.late_payment_fine student_fee_voucher.extra_charges = rule.extra_charges student_fee_voucher.extra_charges_note = rule.extra_charges_note # Set the calculated total_fee student_fee_voucher.total_fee = int(total_fee) student_fee_voucher.total_fee_after_due_date = int(total_fee_after_due_date) student_fee_voucher.save() message = mark_safe( f"Updated fee voucher to <strong>Rs.{student_fee_voucher.total_fee:,}/-</strong> for <strong>{student.student_name}</strong> ({student.roll_no}, {student.student_section}) already exists <a href='{voucher_url}' target='_blank'>View Voucher</a> .") messages.warning(request, message) else: # If no voucher was found, create a new one student_fee_voucher = StudentFeeVoucher.objects.create( voucher_number=voucher_no, student=student, fee_structure=fee_structure, due_date=rule.due_date, issue_date=rule.issue_date, arrears=student.arrears, advance=student.advance, tuition_fee=fee_structure.tuition_fee, dev_fund=fee_structure.development_fund, misc_fee=fee_structure.misc, late_payment_fine=rule.late_payment_fine, extra_charges=rule.extra_charges, extra_charges_note=rule.extra_charges_note, total_fee=int(total_fee), total_fee_after_due_date=int(total_fee_after_due_date) ) student_fee_voucher.save() voucher_url = reverse('admin:student_management_studentfeevoucher_change', … -
Customizing Django Form based on model from 2 different models
I have the following 3 models in django. models.py ============= class Customer(models.Model): name = models.CharField(max_length=255, null=False, unique=True) class Service(models.Model): name = models.CharField(max_length=255, null=False) architecture = models.NameField() class customer_services(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, related_name='customer_service_entries') service = models.ForeignKey(Service, on_delete=models.SET_NULL, null=True, related_name='customer_service_entries') start = models.DateField() end = models.DateField() I have the following forms forms.py ============== class CustomerForm(ModelForm): class Meta: model = Customer fields = ["name"] class CustomerServiceForm(ModelForm): class Meta: model = customer_services fields = ["service", "start", "end"] class ServiceForm(ModelForm): class Meta: model = Service fields = ["name", "architecture"] I am trying to have a form that i can add services to customers, and the issue i am running into is that the form will display only the fields from the CustomerServiceForm. The problem i am running into is that in the services table, i can have multiple services with the same name, but different architectures, but i don't have a way of displaying that in the form. So lets say i have the following values in the Service table. services table ============== id || name || architecture 1 || Test || 32Bit 2 || Test || 64Bit 3 || AnotherTest || 32Bit 4 || AnotherTest || 64bit 5 || TestTwo || 32Bit …