Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i cant show the image in detail page
views.py title = request.POST.get('Title') description = request.POST.get('Description') image = request.FILES.get('image') Course.objects.create(title=title, description=description, image=image) .html <form action="" class="form-control" method="post"> {% csrf_token %} <input class="form-control" name="Title" placeholder="Enter Title"> <input name="Description" class="form-control" placeholder="Enter Description"> <input name="image" class="form-control" type="file" formenctype="multipart/form-data" placeholder="Upload the image"> <button type="submit" class="btn btn-primary" style="margin-top: 10px">Submit</button> </form> detail page <img src="{{course.image.url }}" alt=""> I create the object but the image does not show in detail page how i can show the image of the object -
How to use a variable as character length parameter inside a regular expression [duplicate]
I have a regular expression pattern to find words longer than a certain amount of characters: pattern = r"\w{14,}" where i want the 14 to be dynamic. How can i insert a variable as a character length parameter inside a regular expression? I tried with no success: length = 14 pattern = re.compile(r"\w{" + str(length) + ",}") The pattern is then used as a query in a Django model as: module_list = Contentmodule.objects.filter( # Q(json__text__iregex = r"\w{14,}") Q(json__text__iregex = pattern) ) and i get the error: sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. -
why doesn't the clean method see field in forms?
I'm facing an issue with my forms in Django. I've created something like this: class EventForm(forms.ModelForm): class Meta: model = Event fields = [ "name", "start_date", "end_date" ] def clean(self): start_date = self.cleaned_data["start_date"] end_date = self.cleaned_data["end_date"] if start_date > end_date: raise ValidationError("Start Date cannot be great than End Date") elif start_date == end_date: raise ValidationError("The dates must be different.") def clean_start_date(self): start_date = self.cleaned_data["start_date"] if timezone.now() > start_date: raise ValidationError("The start date of the event must be after today.") return start_date When I tried to test it, something weird is happening. So, when I tried to input a start_date that is after today, I get the following message: start_date = self.cleaned_data["start_date"] KeyError: 'start_date' It looks like clean() doesn't see the start_date. But why? -
I want to build a new whatsapp utility app in django
I'm new in django, want to build a whatsapp utility app , which can use API endpoints provided by the API provider to send text and media files. functionality should be like. Create a Instance ID using access token(provided by the API provider) Generate a qr_code : with the help of created instance ID and known access token. Scan generated qr_code to login to whatsapp web and send the text and media files using API endpoints provided the API provider. Any help would be appreciated. I wrote a views.py file: ` from django.http import HttpResponseimport requestsfrom django.views.decorators.csrf import csrf_exemptfrom django.http import JsonResponseWAPI_URL="https://wapicloud.in/"@csrf_exemptdef whatsapp_create_instance(request):if request.method == 'POST':api_provider = request.POST.get('api_provider', '')phone_number = request.POST.get('phone_number', '')access_token = request.POST.get('token', '') if api_provider == '' or api_provider == '1': url = WAPI_URL + 'api/create_instance?access_token=' + access_token response = hit_curl_get(url) response_data = {} # 2nd API if response\['status'\] == "success":\`your text\` instance_id = response\['instance_id'\] url_qr = WAPI_URL + 'api/get_qrcode?instance_id=' + instance_id + '&access_token=' + access_token response_qr = hit_curl_get(url_qr) # 3rd API if response_qr\['status'\] == "success": hookurl = "https://webhook.site/XXXXXXXX.com/web/123" enable = "true" url_webhook = WAPI_URL + 'api/set_webhook?webhook_url=' + hookurl + '&enable=' + enable + '&instance_id=' + instance_id + '&access_token=' + access_token response_webhook = hit_curl_get(url_webhook) response_data\['webhook_status'\] = response_webhook\['status'\] response_data\['webhook_message'\] … -
PostgreSQL + Django update large table taking ages to run a simple update
I have a table with around 47millions entries. I need to update this table for around 3mil entries very fast, for this I use type_id and an int inside a range to select records and then update the value on another field, while excluding another record. UPDATE "table_name" SET "changes" = 12 WHERE ("table_name". "type_id" = 78 AND "table_name"."rank" BETWEEN 2 AND 2238079 AND NOT ("table_name"."id" = 55423921)) This query was automatically generated by Django using the update method on a QuerySet, but it follows the bahavior described above and can be changed to what ever is more efficient. The reason I store all those records in the same table is to dynamically add new type_id inside without having to create a new table for each (assuming doing so would improve the speed). Currently the table has multiple indexes, but let's list the fields first: id (PK); type (foreign key containing ID + type name); score (BigInt); score_data (jsonb fr metadatas); changes (IntField); rank (IntField, used for range selection); user (foreign key for the user related to this record); There are different indexes : BTree for field score and rank type for it's PK, probably a BTree (it's the default … -
Optimal model structure for a Django-driven spare parts website
I am developing a website on Django for a spare parts distributor. Besides several additional tables (brands, models, countries, etc.), the main subject are spare parts themselves. My question is what would be the proper database structure for spare parts. The matter is that some characteristics are common between all spare parts (id, article, price, brand, compatibility or car model, etc.) while some other are specific for a category. For example, for a leaf spring, the number of plates is important, and for a petrol tank it is the volume in litres. I can see three options with different pro and contra: One table for all spare parts. The table has all fields and all categories, but many of them are empty. Multi-table inheritance. There is one common model "Part" and many models inherited from it, one table for each category (PetrolTank, Radiator, etc.). This is most logical, but the number of tables can potentially be great (~ no. of categories). The great number of models in one application is not recommended (for example by the nice book "Two scoops of Django"). Proxy models. All parts are kept in one table, which has all fields, many of them inevitably empty. … -
Issue whith testing django view that execute asynchrnous task (celery): unexpected tests results
I try to implement tests in Django (DJango/Docker/django-celery/PostgreSQL) but have 2 issues with tests results when view execute celery asynchronous task. The upload_file ajax view works fine 'in live'. But in tests, I face 2 issues I can not figure out: self.assertEqual(1, RCountry.objects.count()) failed whereas self.assertEqual(1, ListRandomization.objects.count()) succeed. self.assertEqual(1, ListRandomization.objects.count()) succeed even if file_upload file contain more than one record: if file contain 5 rows with differents ran_ide (FK), should create 5 records in Randomization model and self.assertEqual(1, ListRandomization.objects.count()) should failed If self.assertEqual(1, ListRandomization.objects.count()) succeed that mean that task succeed and as upadte_or_create of the 2 models are in the same atomic transaction, success of one should imply success of the other. When I look celery logs container, logs confirm task succeed. #tests.py def test_upload_file_ajax_post_valid(self): ... with tempfile.NamedTemporaryFile(mode='w+', suffix='.csv', delete=False) as temp_file: csv_writer = csv.writer(temp_file) ... with open(temp_file.name, 'rb') as file_upload: response = self.client.post( reverse('randomization_settings:upload_file'), data={'file': file_upload}, HTTP_X_REQUESTED_WITH='XMLHttpRequest', ) # tests self.assertEqual(response.status_code, 200) self.assertEqual(1, RCountry.objects.count()) self.assertEqual(1, ListRandomization.objects.count()) os.remove(temp_file.name) views.py def upload_file(request): if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == "POST": form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): ... # Update of Country (adm_pay) Randomization (tbl_ran) task = upload_list.delay(request.user.username) # asynchronous task ... return JsonResponse({"response": "success"}, status=200) else: return JsonResponse({"response": "form_invalid"}, status=200) else: … -
How to deploy Django app with nginx on non-root url?
I have some boxed solutions written on Django inside with docker-compose. I want to deploy it on the same server and specify different root url. But if I do it Django can't find static files, because it requests this files from root url, instead of specified url. How can I say to Django that root is another url? I was trying different examples for deploy Django with Nginx and nothing works. -
how to use redis in cpanel for python (django) module celery for sending email asynchrnously
I have used celery for sending email asynchronous task I use Redis in localhost for change password but when I want use it for send email asynchronous task in server Cpanel it gives error like :- CELERY_BROKER_URL = 'rediss://myvcci.com:6379/0?ssl_cert_reqs=CERT_NONE' error= A rediss:// URL must have parameter Ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE in views.py from home.task import email_send def email(request): a=email_send.delay(email,tokenxyz) return render(request,"send_email.html") in settings.py import redis CELERY_BROKER_URL = 'rediss://myvcci.com:6379/0' CELERY_TIMEZONE="Asia/Kolkata" TIME_ZONE = 'Asia/Kolkata' CELERY_RESULT_BACKEND = 'rediss://myvcci.com:6379/0' CELERY_RESULT_EXTENDED = True in celery.py import os from time import sleep from celery import Celery from datetime import timedelta from celery.schedules import crontab # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alone.settings') app = Celery('alone') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.broker_connection_retry_on_startup = True in __init__.py from .celery import app as celery_app __all__ = ('celery_app',) task.py from django.core.mail import send_mail from celery import shared_task from time import sleep @shared_task def email_send(email,tokenxyz): subject = 'Email verification From KartikShop' message = f'Hello\nThanks for visiting our site ,Your verification link is "https://myvcci.com/password/{tokenxyz}" \n\nNote:-this link will be valid for 5 minutes long only after that if you want to change password you … -
Django model.save() doing inconsistent updates
I am using django ORM to communicate with MySQL database inside the callback functions of my RabbitMQ consumers. These consumers are running on a separate threads and each consumer has established its own connection to its queue. Here is the code for two of my consumer callbacks: TasksExecutorService # imports from pika.spec import Basic from pika.channel import Channel from pika import BasicProperties import uuid from jobs.models import Task from exceptions import MasterConsumerServiceError as ServiceError from .master_service import MasterConsumerSerivce class TaskExecutorService(MasterConsumerSerivce): queue = 'master_tasks' @classmethod def callback(cls, ch: Channel, method: Basic.Deliver, properties: BasicProperties, message: dict): # get task task_id_str = message.get('task_id') task_id = uuid.UUID(task_id_str) task_qs = Task.objects.filter(pk=task_id) if not task_qs.exists(): raise ServiceError(message=f'Task {task_id_str} does not exist') task = task_qs.first() # check if task is stopped if task.status == cls.Status.TASK_STOPPED: raise ServiceError(message=f'Task {task_id_str} is stopped') # send task to results queue publisher = cls.get_publisher(queue=cls.Queues.results_queue) published, error = publisher.publish(message=message | {'status': True, 'error': None}) if not published: raise ServiceError(message=str(error)) # update task status task.status = cls.Status.TASK_PROCESSING task.save() return ResultsHandlerService # imports from pika.spec import Basic from pika.channel import Channel from pika import BasicProperties import uuid from jobs.models import Task from exceptions import MasterConsumerServiceError as ServiceError from .master_service import MasterConsumerSerivce class ResultHandlerService(MasterConsumerSerivce): queue = … -
Can't connect to mysql with Django inside docker
I am trying to start django project using MySQL and Docker to containerize it. But get an error. Here is it's traceback: testcasebooks-backend-1 | Traceback (most recent call last): testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection testcasebooks-backend-1 | self.connect() testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner testcasebooks-backend-1 | return func(*args, **kwargs) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/base.py", line 270, in connect testcasebooks-backend-1 | self.connection = self.get_new_connection(conn_params) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner testcasebooks-backend-1 | return func(*args, **kwargs) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection testcasebooks-backend-1 | connection = Database.connect(**conn_params) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/MySQLdb/__init__.py", line 121, in Connect testcasebooks-backend-1 | return Connection(*args, **kwargs) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/MySQLdb/connections.py", line 193, in __init__ testcasebooks-backend-1 | super().__init__(*args, **kwargs2) testcasebooks-backend-1 | MySQLdb.OperationalError: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)") testcasebooks-backend-1 | testcasebooks-backend-1 | The above exception was the direct cause of the following exception: testcasebooks-backend-1 | testcasebooks-backend-1 | Traceback (most recent call last): testcasebooks-backend-1 | File "/service/./manage.py", line 22, in <module> testcasebooks-backend-1 | main() testcasebooks-backend-1 | File "/service/./manage.py", line 18, in main testcasebooks-backend-1 | execute_from_command_line(sys.argv) testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line … -
Out of two Django forms and two urls only shown up with one form
One Django form is handling Excel file, while another one is handling video file. But the video file form never shown up... Would like to get any help if anyone gets an idea on what's happening around my code settings.py # Media uploading MEDIA_ROOT= os.path.join(BASE_DIR, '') MEDIA_URL= "/" it happens to claim that my media not available when I run local host and set url to media, so I have no choice but to root it on the root file urls.py from django.urls import path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static import hello.views urlpatterns = [ path("", hello.views.upload_file, name="index"), path("upVideo", hello.views.showVideo, name="videoUpload"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Document(models.Model): docfile = models.FileField() class Video(models.Model): name= models.CharField(max_length=500) videoFile= models.FileField(upload_to='videos/', null=True, verbose_name="") videoFile= models.FileField(upload_to='somewhere/') def __str__(self): return self.name + ": " + str(self.videoFile) forms.py from django import forms from .models import Video class UploadFileForm(forms.Form): file = forms.FileField() class VideoForm(forms.ModelForm): class Meta: model= Video fields= ["name", "videoFile"] views.py from django.shortcuts import render from django import forms from .models import Video from .forms import UploadFileForm,VideoForm #**************File Upload View****************# def upload_file(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): extract = handle_uploaded_file(request.FILES['file'].file) return … -
Docker compose up problem in fresh win10 machine
I have problem in run command: docker compose up -d failed to solve: archive/tar: unknown file mode ?rwxr-xr-x on win 10 machine, docker version is 4.25.2 perhaps, when I run the command: docker build --no-cache --rm=false . it run successfully without errors ! P.S: I have include image of the error and this is my docker-compose.yml for further assistance, and DockerFile version: "3" services: web: # the application's web service (container) will use an image based on our Dockerfile build: . # map the internal port 80 to port 8000 on the host ports: - "8000:80" # map the host directory to app (which allows us to see and edit files inside the container) volumes: - ".:/app:rw" - "./data:/data:rw" # the default command to run whenever the container is launched command: python manage.py runserver 0.0.0.0:80 # the URL 'postgres' or 'mysql' will point to the application's db service networks: - default depends_on: - db - cache - search env_file: .env-local db: # Select one of the following db configurations for the database image: mysql:5.7 command: --max_allowed_packet=32505856 --character-set-server=utf8 --collation-server=utf8_general_ci ports: - "3360:3306" # allow your local dev env to connect to the db environment: MYSQL_DATABASE: "nnuh" volumes: - ".:/app:rw" - "./data/db:/var/lib/mysql" … -
Django not findind tests within my monorepo
Alright, this seems like a noob question, but here I go: On my current company, we use a monorepo that stores several projects. Django is among one of them. Here's the basic structure: ├── README.md ├── code │ ├── __init__.py │ ├── gunicorn.conf.py │ ├── manage.py │ ├── non-django-project │ │ ├── ... │ ├── django_project │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── apps │ │ │ ├── django_app_1 │ │ │ │ ├── ... │ │ │ │ ├── tests │ │ │ │ │ ├── test_something.py │ │ │ ├── django_app_2 │ │ │ │ ├── ... │ │ │ │ ├── tests │ │ │ │ │ ├── test_something.py │ │ │ ├── django_app_3 │ │ │ │ ├── ... │ │ │ │ ├── tests │ │ │ │ │ ├── test_something.py │ │ │ │ ├── ... │ │ ├── libs │ │ │ ├── lib1.py │ │ │ ├── lib2.py │ │ │ ├── lib1.py │ │ │ ├── tests.py Now, my github workflow is simple, and baiscally setups python and run the django tests: name: django defaults: run: working-directory: ./code on: workflow_dispatch: pull_request: paths: ["code/django_project/**", ".github/workflows/django.yml"] branches: - develop … -
threading issue in django python
i make a thread for multiple user login and click on button called start timer, when its clicked thread is start whats inside start timer is i am placing stock market order, if single user login and cliked that button single order is placed and saved in database but when user login and click that button total 2 trade save in user 1 and user 2 means total 4. timer.py def start_timers(self): timer_thread = threading.Thread(target=self.run_timer,args=(self.user_id,)) timer_thread.start() views.py def start_timer(request): if request.method == 'POST': # Get the user's ID from the request user = request.user id = user.id # print(id) print('userrrrrrrrrrr',User.objects.get(pk=id)) # Start the timer logic from timer.py and save to the database timer_manager = TimerManager(User.objects.get(pk=id)) timer_manager.start_timers() # start_timers(User.objects.get(pk=id)) # For demonstration purposes, return a JSON response response_data = { 'message': 'Timer started!' } return JsonResponse(response_data) # Handle other HTTP methods if needed return JsonResponse({'message': 'Invalid request method'}) i tried threading and as well as concurrent.futures def start_timers(self): with concurrent.futures.ThreadPoolExecutor() as executor: executor.submit(self.run_timer, self.user_id) -
I have django form that is initialized with request, args and kwargs, now I want to create formset from it, how to do it?
class SpecialDateHJRTableEntryForm(forms.ModelForm): class Meta: model = HJRTableEntry fields = ['job_template', 'date'] widgets = {'is_special_date': forms.HiddenInput(attrs={'value': True}),'date': forms.DateInput(attrs={'type': 'date'})} def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) This is my form, now I want to create a formset for this form, how to do it? Solution to the above issue. -
Apache 2.4 mod_wsgi windows server multiple hosting - not running more than two Django projects
httpd.conf file ServerName 172.31.4.38 Listen 8001 Listen 8002 Listen 8003 LoadFile "C:/Users/Administrator/AppData/Local/Programs/Python/Python311/python311.dll" LoadModule wsgi_module "C:/Users/Administrator/AppData/Local/Programs/Python/Python311/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp311-win_amd64.pyd" WSGIPythonHome "C:/Users/Administrator/AppData/Local/Programs/Python/Python311" WSGIPythonPath "D:/adhocvenv/Lib/site-packages" **virtual host configuration ** <VirtualHost *:8001> ServerName 172.31.4.38 WSGIScriptAlias / "D:\adhocvenv\adhocpayroll\adhocpayroll\wsgi.py" application-group=site1 <Directory "D:\adhocvenv\adhocpayroll"> Require all granted </Directory> </VirtualHost> <VirtualHost *:8002> ServerName 172.31.4.38 #DocumentRoot "D:/StoreManagementSystem" WSGIScriptAlias / "D:/StoreManagementSystem/StoreManagementSystem/wsgi.py" application-group=site2 <Directory "D:/StoreManagementSystem"> Require all granted </Directory> </VirtualHost> <VirtualHost *:8003> ServerName 172.31.4.38 DocumentRoot "D:/HealthCenter" WSGIScriptAlias / "D:/HealthCenter/HealthCenter/wsgi.py" application-group=site3 <Directory "D:/HealthCenter"> Require all granted </Directory> </VirtualHost> ** First two projects are running successfully. For the third projects its showing internal server misconfiguration. What is the wrong with the above configurations? Why misconfiguration? I've verified that each site works individually.** -
Django 4.2.7 & django-allauth 0.58.2 "next" parameter issue
I am trying to redirect my user after login to page he refered, using login_required decorator. If I do not provide {{ redirect_field_name }} in login template it does not work at all (redirects to LOGIN_REDIRECT_URL, even "next" parameter in url exists). But when I provide {{ redirect_field_name }} it firstly redirects to "/accounts/login/next" (with 404 error) and when I press back button it goes to desired page. Could somebody help me to solve this issue? -
how to use redis in cpanel for python (django)
I have used Redis for sending email in localhost for change password but now i want use it for send email in server in Cpanel but when I use it error comes like "connection refuse" please any one help me I am trying to solve it since two days the solution should be a to z step by step -
Python Django ConnectionRefusedError: [Errno 111] Connection refused
When using SMTP from Brevo, it works fine on localhost. However, after deploying the project to PythonAnywhere, I encountered a connection refusal error. EMAIL_HOST = 'smtp-relay.brevo.com' EMAIL_PORT = '587' EMAIL_HOST_USER = env.str('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env.str('EMAIL_HOST_PASSWORD') I found an article on Brevo (article) how to check port availability. After following the steps, I attempted to connect by entering "telnet smtp-relay.brevo.com 587" but received an error message stating "Trying 1.179.118.1... telnet: Unable to connect to remote host: Connection refused" -
Not able to update Django model with HTMX button click
I am using Django, Tailwind CSS, and HTMX. I am trying to update my Django model (Item) which starts as None to use a dropdown select to change the color then use a button to Save and update the Item.color on the Django model. The HTML shows up, and I am able to make the request (the url shows up: "https://localhost/detail-view/my-item-2/?id=my-item-2&color=YELLOW"), but the model is not being updated and I can't get the JsonResponses to show up. I'm not sure if there is something wrong with how I am using my POST request? Can anyone help? models.py class Item(models.Model): id = models.AutoField(primary_key=True) color = models.CharField( "Color", blank=True, null=True, choices=MyConstants.Color.choices, ) constants.py class Color(models.TextChoices): RED = "RED" YELLOW = "YELLOW" GREEN = "GREEN" views.py @require_POST def update_color(request): if request.method == "POST": new_status = request.POST.get("color") item_id = request.POST.get("item_id") item = Items.objects.filter(id=item_id) item.update_or_create( color=new_color ) item.save() return JsonResponse({"message": "Color updated successfully"}) return JsonResponse({"message": "Not a post request: failed to update color"}) color_picker.html {% block main_content %} <div class="p-5"> <div class="mb-6"> <h1 class="text-2xl">Overview</h1> <p class="text-sm">{{ item.id }}</p> </div> <div class="pb-4"> <label for="color" class="text-lg ">Color</label> <form hx-post="{% url "update_color" %}" hx-swap="outerHTML" > <input type="hidden" name="item_id" value="{{ item.id }}"/> <div class="flex"> <select id="color" name="color" class="w-1/4 p-2" … -
Installed django in virtual env, but I can't import
I installed Django in virtual env. But I got error. 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? I use python 3.12.0 and tried reinstall all venv and packages, but got same error. After installing django in virtual environment, still can't import module is not helpful. -
Django Form: Filter and display options based on objects created by user in a form
The current problem is that my form shows the logged-in user all 'decks' ever created. The form should only show 'decks' that the logged-in user created. I can filter the decks from the given user, but I can't get that information passed as the only options a user can select from. models.py class Profile(models.Model): profile_pic = models.ImageField(null=True, blank=True, default='Default.png', upload_to='images/') user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.user) class Deck(models.Model): deck = models.CharField(max_length=150) is_cedh = models.BooleanField(default=False) user = models.ForeignKey(User, max_length=10, on_delete=models.CASCADE, null=True) def __str__(self): return self.deck class Game(models.Model): deck = models.ForeignKey(Deck, on_delete=models.CASCADE, null=True) wincon = models.ForeignKey(Wincon, on_delete=models.CASCADE, null=True, blank=True) tournament = models.BooleanField(default=False) num_players = models.IntegerField(choices=NUM_PLAYERS_CHOICE, default=4) start_pos = models.CharField(max_length=20, choices=START_POS_CHOICE, default=1) mull = models.CharField(max_length=20, choices=MULL_CHOICE, default='1st 7') outcome = models.CharField(max_length=10, choices=OUTCOME_CHOICE, default='Win') medium = models.CharField(max_length=10, choices=MEDIUM_CHOICE, default='Paper') date = models.DateField(auto_now=True) time = models.TimeField(auto_now=True) views.py def game_tracker(request): user_decks = Deck.objects.filter(user=request.user) if request.method == "POST": form = GameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/track') else: form = GameForm() context = {'form': form, } return render(request, 'gametracker_app/gametracker.html', context=context) forms.py class GameForm(forms.ModelForm): class Meta: model = Game exclude = {'date', 'time', } labels = { 'deck': 'What deck', 'num_players': '# of Players', 'start_pos': 'Starting position', 'mull': 'Starting hand', 'outcome': 'Outcome', 'wincon': 'Wincon', 'medium': 'Paper … -
Updating html for specific model instance Django
I have a Django template that generates a HTML 'card-like' element for each model instance. Each instance (ie 'post') have a button, when on click, I would like to update a value within that SAME instance. I have been able to do this within the database, but am struggling with updating the HTML to match. Currently, my solution is updating ALL instances/posts. However, I only want to update it on the instance that had the button click. Does this make sense? Let me know if it doesn't. I will attach my code below along with an image demonstration. I did try passing through the event ID and making sure they align up for both the button and paragraph tag, but this seemed to not work. JS: function signUp(user, event, btn, eventID) { var csrftoken = Cookies.get("csrftoken"); var user_id = user var event_id = event attendance_count = document.querySelectorAll("#attendance"); if (btn.classList.contains("event-btn")){ request_info = "register"; } else if (btn.classList.contains("signUpBtnActive")){ request_info = "unregister"; } $.ajax({ type: "POST", url: "/event/update-attendance/", data: { user_id: user_id, event_id: event_id, request_info: request_info, "csrfmiddlewaretoken": csrftoken }, }).done(function(response){ if (attendance_count){ attendance_count.forEach(element => { event_id = element.getAttribute("event-instance"); if (event_id == eventID){ element.innerHTML = response; } }) } }); } My view: def … -
Django app working locally anyhow when I push it to Heroke it will display a 500 error (H10)
I started my Django app with the sqlite default data base and later on I proceeded the steps (shown below) since I wanted to host it in Pythonanywhere since it was a cheaper alternative (it did not work), I sadly could not successfully deploy to Heroku as well. My project Repository looks like this: RECIPE-APP/ |-include/ |-Lib/ |-Scripts/ |-src/ |-media/recipes/ |-recipe_app/ |-settings.py |-wsgi.py |-recipes/ |-.env |-data.json |-db.sqlite3 |-manage.py |-.gitatributes |-.gitignore |-Procfile |-pyvenv.cfg |-requirements.txt I have a .env set up containing all keys for the DATABASES, in which case I copied all the required keys to heroku config vars. I reviewed the Procfile and it should be ok. Procfile: web: gunicorn src.recipe_app.wsgi --log-file - settings.py: """ Django settings for recipe_app project. Generated by 'django-admin startproject' using Django 4.2.6. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os import dotenv from decouple import config # import environ # from dotenv import load_dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # initialize environment variable # env = environ.Env() …