Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save form data in Django on each http request
I’m new to web programming and Python. I’m having a Django app with multiple questions, each of which has a form (a text field) placed on a separate page. On top there’s a ribbon with buttons - one for every single question, as well as “save and go to next question” button. The problem: form data is lost when other than “save and go next” button is used. I don’t want to lose form data, I want to save on each page change. What I did: I’m about to finish my prototype where I did a small url scheme change: Before: UID/question_ID_to_be_opened After: UID/question_ID_to_be_opened/previous_question_ID The modified view function shall handle the save of “previous_question_ID”, but this don’t look quite elegant. Shall I use signals, or redirects, or something else? There is an autosave script too, it is based on a timer - perhaps I can trigger it manually? Best regards, Ivan -
Python Django - images not showing in templates
My images won't show up in my templates, but it does display a little 'frame' where the image should be displayed. I've tried several things but won't work. I have the exact same settings in my other project and it works fine there. This is what I'm seeing: result on localhost:8000 My settings.py: from pathlib import Path import os import mimetypes BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-xxxx' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cvapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'collabcenter.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'collabcenter.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATICFILES_DIR = … -
Django project. creat new file
when typing in the command line:>django startproject myfirstproject, Gives this error: "Django" is not inside or outside command, executable program, or batch file. how to fix or what can i do? I wanted to create a Django project but it didn't work for me -
Running a .jrxml file using django .Error fill report: Erro fill internal: java.lang.NullPointerException
I am trying to run a .jrxml file to turn it into a .pdf file using a django app that is connected to the database, I keep getting this error: Running a .jrxml file using django .Error fill report: Erro fill internal: java.lang.NullPointerException from pyreportjasper import PyReportJasper from platform import python_version def advanced_example_using_database(): try: input_file = 'C:/Users/m.mostafa/Desktop/loan_data.jrxml' output_file = 'output.pdf' pyreportj=PyReportJasper() con={ 'driver': 'oracle.jdbc.driver.OracleDriver', 'username': 'xxxx', 'password': 'xxxx', 'database':'PREE', } pyreportj.config( input_file, output_file, db_connection=con, output_formats=["pdf", "rtf"], parameters={'python_version': python_version()}, ) pyreportj.process_report() except Exception as e: print(e) -
How to redirect old url to new url while migrating to new site in react and django?
I have an old website and new website built with React and django. I'm in the process of migrating from the old site to the new one and need to implement SEO-friendly URL redirects. There are more that 500 old url that needs to be redirected to new ones. I came to know about redirect apps in django (https://docs.djangoproject.com/en/4.1/ref/contrib/redirects/) but dont get how to achieve it on the frontend. I'm not sure how to properly set up SEO-friendly URL redirects from my old url to the new ones while preserving SEO attributes. If I add all those urls in react and call an API to find where i have to redirect will it affect seo? or is there any better way to do this? -
Issue with Rendering Checkboxes and Labels in Django Template
I'm facing issues in my Django template while trying to create checkboxes for food options. I created a form titled cuisine_choices, and I am able to successfully loop through the selection of food from my template, but its not allowing me to properly display it. When I use the following code: {% for food in cuisine.choices %} <input type="checkbox" name="food">{{ food }} {% endfor %} I encounter an unexpected behavior where I get the correct amount of checkboxes but with no label attached to it. However, when I write the code like this: {% for food in cuisine.choices %} <input type="checkbox" name={{ food }}> {% endfor %} I get the properly labeled checkboxes, except each label ends in ">. For example: Mexican"> Chinese"> Italian"> Indian"> Japanese"> French"> Thai"> Mediterranean"> American"> While trying to figure out what was wrong I tried the following code: {% for food in cuisine.choices %} <input type="checkbox" name="Food">Test {% endfor %} And I got the correct amount of checkboxes, each labeled as "Test". Can someone please explain why this is happening and how I can correctly render checkboxes with their labels in my template? -
Django istartswith performance
I have a model with column "name" and I am running query with istartswith and I am using postgresql. I have added django.db.models.Index with Postgresql opclass Index(fields=('name',), name="partial_name_pat_idx", opclasses=("varchar_pattern_ops",), condition=Q(published=True)) But I can't figure out how do make I make use of index for case insensitive search, I have tried with django model function Upper('name') but it is not supported in fields argument. If I pass Upper(F('name')) in expressions django is restricting me to use opclasses=("varchar_pattern_ops",). Is there any way I can create index for queries with LIKE operator and UPPER function on field name? -
Page not found (404) No Product matches the given query
Page not found (404) “C:\Users\TOSHIBA\Desktop\Miniproject\cake_studio\add_to_cart\1” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/add_to_cart/1 Raised by: django.views.static.serve trying to add product in to the cart, getting this error and not get correct data for my website -
Django Restrict the Parent Foreign key to be set as Itself
I am new to Django, I am trying to create a project where a WBS can have other WBS as their parent. My Problem is that when I open the form for edit, I want to simply not display the self in the WBS drop-down so that it can't be set as self parent to avoid strange recursive relationship. def validate_not_self(value): if value and value == value.parent_wbs: raise ValidationError("A WBS cannot be its own parent.") class WBS(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, on_delete=models.CASCADE) num = models.IntegerField(default=0) parent_wbs = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='child_wbs', validators=[validate_not_self]) created_on = models.DateTimeField(auto_now_add=True) created_by = models.IntegerField(blank=True, default=0) modified_on = models.DateTimeField(auto_now=True) # This field will be automatically updated on each save modified_by = models.IntegerField(blank=True, default=0) # You can specify your own logic for updating this field def __str__(self): return self.name -
Urgent !! Django web server has a sqlite3 problem and can't run! Help~~
Web server is Django4.2.1 with nginx1.18.0. The original Ubuntu20.4 venv(python3.8.10,gcc 9.4.0) directory inside web directory PycharmProjects/WebProjects. It may be due to the installation of python 3.11 in other environments. I do not know why the venv of Python3.8 is affected. An error occurred while running python3 manage.py runserver XXXX: `(venv) dave@dave-X299-WU8:~/PycharmProjects/WebProject$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/utils /autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Can't add to head in Django Template
I have the following: bootstrap.html: {% extends 'django_bootstrap5/bootstrap5.html' %} {% block bootstrap5_title %}{% block title %}{% endblock %}{% endblock %} sm/base.html: {% extends 'sm/bootstrap.html' %} {% load django_bootstrap5 %} {% block head %} <meta name="robots" content="all, index, follow" /> {% endblock %} {% block bootstrap5_content %} <div class="container"> <h1>{% block title %}(no title){% endblock %}</h1> {% autoescape off %}{% bootstrap_messages %}{% endautoescape %} {% block content %}(no content){% endblock %} </div> {% endblock %} sm/home.html: {% extends 'sm/base.html' %} {% load django_bootstrap5 %} {% block title %}My title{% endblock %} {% block head %} <meta name="robots" content="all, index, follow" /> {% endblock %} {% block content %} <br/> {% endblock %} When I view the output, I don't see the robot meta in the head. What am I doing wrong? <!DOCTYPE html> <!DOCTYPE html> <html lang="en-ie"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>My title</title> <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" rel="stylesheet"> </head> <body> ... -
Compare created_at to an hours_old integer in JsonField in Django
I'm trying to create a django query that compares my models created_at date to see if they are at least x hours old where x is defined in a nested JsonField hours_old. So for example: # This creates a timedelta ("Duration" natively, I think) hours_past = ExpressionWrapper( timestamp.now() - F('created_at'), output_field=DateTimeField() ) Person.objects.annotate( hours_old=F('settings__json__data__hours_old') # Let's say this is an int of 3 hours_past=hours_past # Let's say this is a timedelta of 2 days ).filter( hours_old__lt=hours_past # I want 3 < 48 ) But I can't compare a time duration to a random int obviously. What's the play here? -
Query in django orm to get all users in a list from django authentication group returns empty list
In my code below, the list is empty, it does not contain user name in list. from django.contrib.auth.models import Group, User def first(request): from django.contrib.auth import models groups = Group.objects.all() # Create an empty list to store users all_users = [] # Iterate through the groups and get users for each grou for group in groups: users = group.user_set.all() all_users.extend(users) print(all_users) return render(request,'first.html') I expected to get users details but got an empty list. Why is that and how can I fix it? -
Non atomic transaction inside transaction.atomic() block in Django
I would like to insert in db some objects directly inside transaction.atomic() block, not waiting that block finish. Why do I need this? I need atomic block because of a business logic and without it, I could get invalid state. But, I would like to track process. Process need to be updated inside block, because if executed after atomic block is finished, I only get 100% inserted. Example for example, I would need something like this def my_function(my_list, id): t = Task.objects.get(id) percent = int(100 / len(my_list)) with transaction.atomic(): for i in my_list: MyObject.objects.create(**i) t.progress = t.progress + percent t.save # This should not be atomic!!!! Not a solution I can't move the t.save outside the atomic block because it need to be updated along the code to track process. Directly inserting into database with code with connection.cursor() as cursor: cursor.execute(".... my update statement...") I try and it doesn't work - it still insert after atomic block is finished. -
Making multiple Multiselect forms dynamically in Django admin for the same M2M linked model
Is it possible to have dynamically multiple "Multi-Select" Form in Admin panel that is related to same model based on a certain rule? Like: A separate multi-select form for each category flagged as main/parent category with it's children only as selection options. Details: I have Posts Model and Categories Model, linked to each other via ManyToManyField on POSTS, the plan for categories model to be hierarchal where the top level are main groups of categories and leaf categories are linked to them as parents. In POSTS admin page, I'm doing normal Multi-select Forms, it shows normally as below: The Top level Categories will grow to maybe 6 with 10-15 options in each one.. it will make this form difficult to navigate or manage. So I want Cat and cat2 to have their own multi-select form, where the listed categories in each will be their children only. So even later when I add a third cat3 parent, i'll show in a separate multi-select form as well. I'm trying to avoid building a separate html page for adding Posts for this only, as all other things are ok and i thought there might be a solution for it. Note: checked different Django … -
Why the User data are not updated? in Django?
I have a Model called UserAccount, I have tried several ways to update the data for an existing user, it responds that changes are successful without any error but still nothing is reflecting in Database Here is the Model class UserAccount(AbstractBaseUser,PermissionsMixin): first_name = models.CharField( max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(_("email"),validators=[EmailValidator()],unique=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=20, validators=[RegexValidator(r'^\d{12}$', 'Enter a valid phone number.')]) profile_picture = models.ImageField(upload_to='media/users_photos/%Y/%m',null=True,blank=True) employee_id = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(999)], null=True,blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now_add=True , null=True) objects = CustomUserAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name","phone"] EMAIL_FIELD = "email" class Role(models.TextChoices): ADMIN = "Admin", "Admin" MANAGER = "Manager", "manager" NORMALUSER = "Normal", "normaluser" base_role = Role.NORMALUSER role = models.CharField(max_length=50, choices=Role.choices) def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): if self.first_name and self.last_name: fullname = f'{self.first_name} {self.last_name}' elif self.first_name: fullname = self.first_name elif self.last_name: fullname = self.last_name else: fullname = "Unnamed User" return fullname # Add related_name to avoid clashes groups = models.ManyToManyField( 'auth.Group', related_name='user_accounts', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='user_accounts', blank=True, help_text='Specific permissions for this user.', verbose_name='user … -
Cannot resolve keyword '-name' into field. Choices are: name, account, account_id
Why am I getting this error and is there any alternative way to achieve the result of the below query? Cannot resolve keyword '-name' into field. Choices are: name, account, account_id. self.queryset = Model.objects.order_by( Case( When(status='pending', then=0), When(status='rejected', then=1), When(status='accepted', then=2), default=3 ), Case( When(status='pending', then='-name'), default='-account' ) ) -
ways to make my chatbot project embeddable?
I have build a chatbot using openai' s api and the django framework. I hosted this chatbot online using railway' s platform, it works just fine. Now, i want to make it embeddable on other web sites. I want to share the bot to other websites, like botpress does, just using tags and just a few lines of code. This is the link to the github repo where my project is hosted : text. I tried using but it' s just ugly, i takes space on the web site even when it doesn' t have to. -
Using you model defined 'choices' with a ModelMultipleChoiceField widget
I have a model : class Features(models.Model): EVCHARGING = "EVC" # Parking space has electric charging capabaility DISABLEDACCESS = "DBA" #Parking space has disabled access HEIGHTRESTRICTION ="HRS" # Parking space has height restrictions NOHEIGHTRESTRICTION = "NHR" # Parking space has NO height restrictions LIGHTING = "LIT" # Parking space is in lighted area SECUREGATE = "SGE" # Parking space is securely gated COVEREDPARKING ="CVP" # Parking space is covered from weather VIDEOSURVEILLANCE = "CTV" # Parking space has CCTV FEATURE_NAME_CHOICES = [ (EVCHARGING,"EV Charging"), (DISABLEDACCESS,"Disabled Access"), (HEIGHTRESTRICTION,"Height Restriction"), (NOHEIGHTRESTRICTION,"No Height Restriction"), (LIGHTING,"Lighting"), (SECUREGATE,"Securely Gated"), (COVEREDPARKING,"Covered Parking"), (VIDEOSURVEILLANCE,"CCTV") ] feature_name = models.CharField(max_length=3,choices=FEATURE_NAME_CHOICES,blank=False,null=True) I have a field in my form: features = forms.ModelMultipleChoiceField(queryset=Features.objects.all(),widget=forms.CheckboxSelectMultiple()) This field is part of a form with that is taking information to create a parking space object. The features is a many to many relationship with parking space, hence why I use ModelMultipleChoiceField. How is it possible for me to use my already defined choices and not have to use queryset? I want a solution where as much as possible Django handles the database like it does with the current situation - ie saving the 3 letters into features table, no duplication in features table, number is stored … -
Forbidden You don't have permission to access this resource. Django Apache AWS
on running 'python manage.py 0.0.0.0:8000' its working good but now after shifting on apache its showing permission error. sudo tail -100 /var/log/apache2/error.log Python path configuration: PYTHONHOME = '/home/ubuntu/env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/ubuntu/env' sys.base_exec_prefix = '/home/ubuntu/env' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/ubuntu/env' sys.exec_prefix = '/home/ubuntu/env' sys.path = [ '/home/ubuntu/env/lib/python310.zip', '/home/ubuntu/env/lib/python3.10', '/home/ubuntu/env/lib/python3.10/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f45674e6780 (most recent call first): <no Python frame> [Wed Sep 06 17:41:35.663206 2023] [wsgi:warn] [pid 21214:tid 139936062662528] (13)Permission denied: mod_wsgi (pid=21214): Unable to stat Python home /home/ubuntu/env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. sudo nano /etc/apache2/sites-available/000-default.conf Alias /static /home/ubuntu/proj/static <Directory /home/ubuntu/proj/static> Require all granted </Directory> Alias /media /home/ubuntu/proj/media <Directory /home/ubuntu/proj/media> Require all granted </Directory> <Directory /home/user/proj/proj> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess proj python-path=/home/ubuntu/proj python-home=/home/ubuntu/env WSGIProcessGroup proj WSGIScriptAlias / /home/ubuntu/proj/proj/wsgi.py -
LOG [TypeError: Network request failed] react native
I've been trying to fetch data from Django , so I can create a react native app, I wrote the same method using useEffect,and it worked with me when I created web app, and now when I use it with react native, I still got [TypeError :Network request failed ], is it because the Token? useEffect(()=>{ fetch('http://127.0.0.1:8000/api/movie/',{ method:'GET', headers:{ 'Authorization':`Token f4136c8a15e73530edf6660d0062813362f6a02b`, } }).then(resp=>resp.json()) .then(resp=>console.log(resp)) .catch(error=>console.log(error)) },[]) -
Django-templates: how to make list in templates
The part of my template: {% if True %} <div class="container" id="timeline-block"> <div class="row"> <div class="panel-timeline"> {% for player in room.player.all %} {% for level in player.leavel.all %} <div class="timeline"> <div class="timeline-content"> <span class="date"> <span class="month">{{ level.create.time }}</span> <span class="year">{{ level.create.date|date:"d.m" }}</span> </span> <h2 class="title" style="background: #02a2dd;"><span class="fa fa-chevron-up" aria-hidden="true"></span> {{ player.player.email }} теперь {{ level.leavel }} уровня </h2> <p class="description">Игрок {{ player.player.email }} изменил уровень</p> </div> </div> {% endfor %} {% endfor %} </div> </div> </div> {% endif %} I wanna make a list for the level of all players from the room.player.all. So I need these two cycles to end and after their ending I gotta have a list with all levels of all players for my timelines -
issue with find combinations
I have a list in a mysql data table This table has 3 fields. number (INT), price (FLOAT) and name On the other hand I have another table that gives me three sets of values Set 1: (x)number - (y)price Set 2: (x1)number - (y1)price Set 3: (x2)number - (y2)price There are several things I know for sure: All three sets exist within the combinations of the data table. no row can be used in more than one set There are no unused rows in the table. That said, I try to find the combinations within the table that result in set 1, set 2, and set 3 All 3 must occur. I have tried different approaches, approximations to avoid searching in 25 billion combinations. Pruning system.... But I'm out of ideas... The data table changes values and the sets do too. And there may be more than one set, or two, or three... We are working with less than 100 rows per table. But whatever I do it always takes a lot of time, and the script does not throw results because of this... The idea is that sets must be composite. That is, the number and price must … -
Celery task type error says there is extra arguments at runnig tasks
I have two celery tasks: @shared_task def start_scrapy(book_id, link, site, end_page=None, start_page=1): book = Book.objects.get(id=book_id) process = CrawlerProcess(get_project_settings()) process.crawl(MainSpider, book=book, link=link, site=site, end_page=end_page, start_page=start_page) process.start() @sahred_task def find(): ... the problem is with the first task I'm calling the first task two times in my serializer create method The first time it's working fine but in the second call I get a TypeError the create method: def create(self, validated_data): book_id = validated_data.get('book_id') site = validated_data.get('site') feghahat_link = validated_data.get('feghahat_link') maktabeh_link = validated_data.get('maktabeh_link') start = validated_data.get('start') book = Book.objects.get(id=book_id) validated_data.update({'title': book.title, 'volume_number': book.volume_number}) task_chain = chain( start_scrapy.s(book_id=book_id, link=feghahat_link, site='es', start_page=start), start_scrapy.s(book_id=book_id, link=maktabeh_link, site='is', start_page=start), find.s(book_id, site) ) task_chain() return validated_data and the traceback: [2023-09-06 19:53:55,762: ERROR/ForkPoolWorker-4] Task extractor.crawler.start_scrapy[f918e091-f30c-48e3-8da5-ef4c43448559] raised unexpected: TypeError('start_scrapy() takes from 3 to 5 positional arguments but 6 were given') Traceback (most recent call last): File "/home/mostafa/Projects/BookExtractor/venv/lib/python3.10/site-packages/celery/app/trace.py", line 539, in trace_task _chsig.apply_async( File "/home/mostafa/Projects/BookExtractor/venv/lib/python3.10/site-packages/celery/canvas.py", line 400, in apply_async return _apply(args, kwargs, **options) File "/home/mostafa/Projects/BookExtractor/venv/lib/python3.10/site-packages/celery/app/task.py", line 559, in apply_async check_arguments(*(args or ()), **(kwargs or {})) TypeError: start_scrapy() takes from 3 to 5 positional arguments but 6 were given I'm calling the same function for the second time with the same argument count but the error says something different! thanks for any … -
How to create a DjangoModel Form with a model that contains FKs and M2M relationships
I have seen posts that talk about this scenario separately but they seem to be very old, using old documentation. I am here wondering if there is a new fix. Also I'm relatively new to django and they have been quite confusing. I would like to create a Form that takes in the relevant information to be able to create a parking space object. This is the Forms.py class AddParkingSpace(forms.ModelForm): class Meta: model = ParkingSpace fields = [ "__all__"] exclude = ["reviews","seller_account"] # widgets to include all the fields like fields not in the specified model above (explained below) widgets = { } I have excluded the reviews because these will be added to the parking space object as and when a review is submitted. The seller_account will be added to the parking space in the view(backend). Using this form I would like to be able to access each field separately using the Django syntax {{formname.fieldname}} in the template. So I can style/position it how I desire I Models.py class ParkingSpace(models.Model): name = models.CharField(max_length=50,blank=False) # name of a parking space description = models.TextField(blank=False)# the description of a parking space image = models.ImageField(null=True,upload_to="images/parking_spaces") #The image of a parking space price = …