Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up Postgres for Django on github actions
I have been trying to setup a workflow to test my Django applications however, I am having trouble setting up the workflow: I have so far created: name: Django CI on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: db: [postgres] python-version: [3.7, 3.8] include: - db: postgres db_port: 5432 services: postgres: image: postgres:13 env: POSTGRES_USER: postgres POSTGRES_PASSWORD: password options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests env: SECRET_KEY: vz@h6kziphf$m&xxu4$dfe4bt6h8_a_!^54yup$rk*_93d1x+h DEV_ENV: dev DB_NAME: ${{ matrix.db }} DB_HOST: 127.0.0.1 DB_USER: postgres DB_PASSWORD: password DB_PORT: ${{ matrix.db_port }} run: | python manage.py test test user.tests.test_models And inside my settings file I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST', default='localhost'), 'PORT':config('DB_PORT') } } When running this pipeline it takes around 20 minutes and it fails with a thread error. I was wondering what's the correct way of settings this up … -
Run a new shell process for django runserver command on AWS CodeDeploy
I have an AWS CodeDeploy script for bootstrapping/running a Django instance. However I reach a problem in that the python manage.py runserver command consumes the current shell process, so the CodeDeploy script never technically completes. Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. How would one run this command in a way that doesn't block the shell script? I have tried appending the command with an & to no avail . -
Why is the function in my hooks.py file not being called? django-paypal
I'm following this tutorial: https://django-paypal.readthedocs.io/en/stable/standard/ipn.html Go to step 5. That's where I'm at. Here's my code: from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received, invalid_ipn_received from django.views.decorators.csrf import csrf_exempt from datetime import datetime from django.conf import settings from engine.models import Invoice from engine.models import PaypalError if settings.PAYPAL_TEST: business_email = "redacted" else: business_email = "redacted" def show_me_the_money(sender, **kwargs): ipn_obj = sender invoice_id = ipn_obj.invoice invoice = Invoice.objects.get(inv_id=invoice_id) amount = invoice.price if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != business_email: # Not a valid payment return # ALSO: for the same reason, you need to check the amount # received, `custom` etc. are all what you expect or what # is allowed. if ipn_obj.mc_gross == amount and ipn_obj.mc_currency == 'USD': invoice.is_paid = True invoice.date_paid = datetime.now() invoice.save() else: pass def invalid_ipn(sender, **kwargs): inv_id = sender.invoice invoice = Invoice.objects.get(inv_id=inv_id) err = PayPalError.objects.create(invoice=invoice) valid_ipn_received.connect(show_me_the_money) invalid_ipn_received.connect(invalid_ipn) I know it's not being called because the is_paid field of each invoice never gets set to True after paying (in the Paypal … -
Why can only some Django Rest Framework serializers be imported?
I have a mid-size Django project using Django Rest Framework with dozens of serializers in a serializers.py file per convention. There's been no trouble with them until today when I tried to add a new one. Strangely, I am unable to import the new serializer -- let's call it SerializerC, to sanitize real project names -- into my views.py file, and keep getting an error: ImportError: cannot import name 'SerializerC' from 'app.serializers' (/code/project/app/serializers.py) This is pretty strange to me, as I've got plenty of other serializer classes in use and imported from the same serializers.py file into the same views.py file. I've tried a few things to diagnose the issue, and none of them have worked: Clearing and recompiling all *.pyc files across the project Verifying that SerializerC is even getting executed by the Django code-checker (if I try to reference, for instance, a made-up class inside SerializerC, Django logs an error, so it seems this code is being accessed Eliminating the chance of SerializerC having code issues by creating, let's say, SerializerD which is a carbon-copy of a SerializerB that is already in use in production and functioning well. This would eliminate any chance of some careless code error … -
How to use same Choices for all Questions in Django's Polls app
Sub: Django Poll Project. There can anyone please help me understand to use same set of choices against all questions. I don't want to add choices every time for each question, instead I want to add question with date- time stamp and want that choices which are already added should reflect for my questions and I select any of those choices and vote. 2nd Option I want to work is if I want to add another choice it should allow but it should show all other choices against my question. Thank You Rishipal -
How to use a Bootstrap 5 class (form-check) with Django 3.2.2?
I am learning Django and I want to use the form-check Bootstrap class for a checkbox but it isn't working correctly. This is the code of my file vaccines_form.html: {{ form.vacuna }} This code of my file forms.py works fine: widgets = { 'vacuna': forms.CheckboxSelectMultiple(), } But this doesn't work well: widgets = { 'vacuna': forms.CheckboxSelectMultiple(attrs={'class': 'form-check'}), } I am using Django 3.2.2 with Bootstrap v5.0.0 but I am not sure if Bootstrap 5 is compatible with Django 3.2.2. Maybe I don't have to use Bootstrap classes in forms.py and use only in vaccines_form.html. -
static vs dynamic machine learning web applications django vs tensorFlow.js
I am new to web development and would like to have a better understanding on what is better for machine learning applications from small projects or microservices to larger projects, and what would you say the job market trend looks like for Python/Django and Reacj.js. The information I gathered is that Python is good for backend development because you have the built in admin app and manage app that facilitate adding elements to the database, and it is compatible with common database services like MySQL. This is my understanding, if it is wrong please correct this statement. On the other hand, Javascript/react.js is just a library that is used to render user interface components, which makes it useful only for the front-end. This brings me to the first question: I am not completely sure whats the difference between front-end and back-end Is, some rough definitions you find around are that front-end is just the user interface, and the back-end is the functionality. But in principle, you can also implement the functionality in javascript, and part of the UI can also be the functionality of the website. For example if you have a calculator web app, the rendering can go along … -
How to pass function as an argument to a celery task?
I want to pass a function as a parameter to a celery task. I found two similar questions in stackoverflow (1 and 2). I tried the solutions mentioned in the answers, and this is what I'm currently doing: Inside caller module: import marshal def function_to_be_passed: # ... serialized_func_code = marshal.dumps(function_to_be_passed.__code__) celery_task.delay(serialized_func_code) And inside the celery task, I'm deserializing and calling the function: import marshal, types from celery.task import task @task() def celery_task(serialized_func_code): code = marshal.loads(serialized_func_code) func = types.FunctionType(code, globals(), "some_func_name") # calling the deserialized function func() However, upon calling celery_task.delay(serialized_func_code), I get an error: kombu.exceptions.EncodeError: 'utf-8' codec can't decode byte 0xe3 in position 0: invalid continuation byte Sharing stack trace below: File “...caller.py", celery_task.delay( File "/python3.8/site-packages/celery/app/task.py", line 426, in delay return self.apply_async(args, kwargs) File "/python3.8/site-packages/celery/app/task.py", line 555, in apply_async content_type, content_encoding, data = serialization.dumps( File "/python3.8/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/python3.8/contextlib.py", line 131, in __exit__ self.gen.throw(type, value, traceback) File "/python3.8/site-packages/kombu/serialization.py", line 54, in _reraise_errors reraise(wrapper, wrapper(exc), sys.exc_info()[2]) File "/python3.8/site-packages/vine/five.py", line 194, in reraise raise value.with_traceback(tb) File "/python3.8/site-packages/kombu/serialization.py", line 50, in _reraise_errors yield File "/python3.8/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/python3.8/site-packages/kombu/utils/json.py", line 69, in dumps return _dumps(s, cls=cls or _default_encoder, File "/python3.8/site-packages/simplejson/__init__.py", line 398, … -
using swiper with Django
I am using this html with django to make a slider but the images appear over each other <div class="simple-slider" style="margin-top: 60px;"> <div class="swiper-container container"> <div class="swiper-wrapper"> <div class="swiper-slide" style="background-image:url(../../static/img/slideshow/60569646_286544018967833_1111229634294317056_n.jpg);"></div> <div class="swiper-slide" style="background-image:url(../../static/img/slideshow/72575348_432725740713857_2057685820394962944_n.jpg);"></div> <div class="swiper-slide" style="background-image:url(../../static/img/slideshow/82024372_524613851475852_6637436459169087488_n.jpg);"></div> </div> <div class="swiper-pagination"></div> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> </div> </div> I also include in base.html this <script src="https://unpkg.com/swiper/js/swiper.js"></script> <script src="https://unpkg.com/swiper/js/swiper.min.js"></script> and this on header <link rel="stylesheet" href="https://unpkg.com/swiper/css/swiper.min.css"> -
The host 127.0.0.1:8000 does not belong to the domain example.com, unable to identify the subdomain for this request
I am new to Django. I was trying to launch "NewsBlur" (Django based) to my local PC , when everything is set. I ran "python3 manage.py runserver" . Whenever I tried to click btn or manually trigger http request I got error below on my server: The host 127.0.0.1:8000 does not belong to the domain example.com, unable to identify the subdomain for this request Anything I incorrectly configured in django ? -
Django Zoho SMTPAuthenticationError (535, b'Authentication Failed')
I'm using Django's email backend to send account verification emails. This is what my setup looks like: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.zoho.in' EMAIL_PORT = 587 EMAIL_HOST_USER = 'someone@example.com' DEFAULT_FROM_EMAIL = 'someone@example.com' EMAIL_HOST_PASSWORD = 'somepassword' EMAIL_USE_TLS = True This configuration worked fine for till a few hours ago when it suddenly stopped working, throwing this error: Traceback (most recent call last): File "/home/ubuntu/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/venv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/ubuntu/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/ubuntu/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/ubuntu/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/ubuntu/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/home/ubuntu/venv/lib/python3.8/site-packages/djoser/views.py", line 144, in perform_create settings.EMAIL.activation(self.request, context).send(to) File "/home/ubuntu/venv/lib/python3.8/site-packages/templated_mail/mail.py", line 78, in send super(BaseEmailMessage, self).send(*args, **kwargs) File "/home/ubuntu/venv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/ubuntu/venv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/usr/lib/python3.8/smtplib.py", line 723, in login (code, resp) … -
Django parallel functions in views.py or step-by-step template rendering
Good afternoon. I'm a beginner super coder. Every day there are a lot of problems. Here I am close to releasing the Alpha version of my first project on django. But I ran into another problem that took me 3 days, and I didn't find an answer exactly how to solve the problem. in my views.py there is a request that calls 5 more functions - 'multi'. In the template, I use the result (list of 100 values) of the main request and the total result of 5 additional functions. (the whole point is that I can only send 20 values from the list of the main request to the 'multi' function). It turns out that I have to go through the multi function 5 times to collect the entire final list. The total time from start to finish is more than 150 seconds. It's a very long time. I really need some help. The first main request is processed in 5-10 seconds. The first request + the first 'multi' function is processed in 15-25 seconds. but when this company is running all (request + 5 functions) = 150 + seconds. I know that this can be solved by several … -
Accessing the id of the django admin items in the views
Is there a way of accessing Django admin listed id items e.g items from a model into the views.oy section ? -
Python requests.put cannot update object
I'm trying to request put into my API built using Django. When I'm requesting from IDLE I'm not getting my objects updated, but when I use postman and I make request on the same url with the same JSON it works. I don't get the point because the url and JSON are the same. from tkinter import * import requests import json url = "http://127.0.0.1:8000/rentals/35/" custom_json = {"client": "dsa", "bike_id_number": ["483KIS5O4D", "473JDS93DF", "837JFIE945"]} myobj = json.dumps(custom_json) print(myobj) requests.put(url, data = myobj) Screen from Postman with copied url and JSON from my Python Code: https://ibb.co/rmPRtPj -
MultiValueDictKeyError at /search
I'm trying to add an object to my user's profile but when I post the form I get the error: MultiValueDictKeyError at /search Why is this happening and how can I fix it? I am not sure if the issue is related to me having two functions posting a form in the same view or if something else is going on but either way I would like to fix it. These are the views related to it and the one that I'm trying to get to work is the 'anime' view: def search(request): animes = [] if request.method == 'POST': animes_url = 'https://api.jikan.moe/v3/search/anime?q={}&limit=6&page=1' search_params = { 'animes' : 'title', 'q' : request.POST['search'] } r = requests.get(animes_url, params=search_params) results = r.json() results = results['results'] if len(results): for result in results: animes_data = { 'Id' : result["mal_id"], 'Title' : result["title"], 'Episodes' : result["episodes"], 'Image' : result["image_url"] } animes.append(animes_data) else: message = print("No results found") for item in animes: print(item) context = { 'animes' : animes } return render(request,'search.html', context) def anime(request): if request.method == "POST": anime_id = request.POST.get("anime_id") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('/search') animes = Anime.objects.all() return render(request = request, template_name="search.html") This is the … -
django remove unwanted user fields in models using AbstractUser
I'm a beginner in django and I'm working on user authentication. I'm using Abstractuser and default User model to create the users. However, there a lot of unnecessary information being gathered that is of no use to my project. This is my models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass These are the fields that are generated: ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), The … -
can I get a backend developer job without knowing front-end
-I'm a second year software engineering student, I work with django and I master python and other programming languages, but when it comes to front-end I struggle with it I don't master css. so can I get my first job without knwoing front-end. -
How can I add an element to a profile in django without getting 'Page not found at /post'?
I'm trying to add a 'favorite' anime to my profile in django but when I post my form it says 'Page not found at /post'. The code does get the anime's id but then it doesn't add it to my profile and instead takes me to /post. How can I fix this? This is my view of the 'anime': @login_required def anime(request): if request.method == "POST": anime_id = request.POST.get("anime_id") anime = Anime.objects.get(id = anime_id) request.user.profile.animes.add(anime) messages.success(request,(f'{anime} added to wishlist.')) return redirect ('search:anime') animes = Anime.objects.all() return render(request = request, template_name="search.html") This is the part of html related to this: {% if animes %} {% for anime in animes %} <form action="post"> <section> <div class="col-md-4 col-sm-6 col-lg-3"> <div class="card"> <div class="card-body text-center"> <p class="card-title"> <b>{{anime.Title}}</b></p> <hr> <p class="card-text">Episodes: <b>{{anime.Episodes}}</b></p> <img src = {{anime.Image}} /> </div> </section> <input type="hidden" value="{{anime.Id}}" name="anime_id"> <button type="submit" class="btn btn-outline-primary" style="font-size:18px; border-radius: 50%">★</button> </form> {% endfor %} {% endif %} This is the url it goes to after I post the form: /post?anime_id=18507 It should just add it to the profile and redirects me to the search page but it doesn't. -
Django model order by model method or calculation on model fields
I have a Django Model, OrderItem class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_line') quantity = models.PositiveIntegerField(default=1) title = models.CharField(max_length=100) order_number = models.CharField(max_length=25, null=True, blank=True, verbose_name='Order Number') order_date = models.DateField(auto_now_add=True) dispatch_date = models.DateField(auto_now_add=True) cancel_date = models.DateField(auto_now_add=True) I have a model function that calculates the days between today and the OrderItem order_date or dispatch_date and order_date def get_aging(self): today = datetime.today().date() if self.dispatch_date is not None: aging = self.dispatch_date - self.order_date return aging.days elif self.cancel_date is not None: return 0 else: aging = today - self.order_date return aging.days I want to order the OrderItems by the same calc. I have tried to use the python sort but I can't apply the django FilterSet on the list created by the python sorted method. This is the code in my view, I am using a custom template as I allow for inline editing of the data. order_qs = OrderItem.objects.all() sorted_qs sorted(order_qs, key= lambda a: a.get_aging()) user_filter_orders = OrderItemsFilter(request.GET, queryset=order_qs) The error because of the sorted method returning a list: 'list' object has no attribute 'model' Any suggestions, please? -
Integrating django-cms into an existing project - Error: Reverse for 'pages-root' not found. 'pages-root' is not a valid view function or pattern name
I am trying to add news functionality to an existing django project. I decided to use django-cms to provide the functionality. The documentation is lacking and what little there is, is next to useless, in terms of integrating django-cms into an existing project. I have looked at this question and this one but the offered answers only take me so far. What I want to do is to be able to have pages with static data, and use django-cms to allow users with the right permissions to create new pages and/or update existing pages. At the moment, when I run python manage.py runserver and I navigate to http://127.0.0.1:8000/news/1/, I get the following error message: NoReverseMatch at /news/1/ Reverse for 'pages-root' not found. 'pages-root' is not a valid view function or pattern name. Here is the relevant versioning information for my software components: Django 3.2.2 django-classy-tags 2.0.0 django-cms 3.8.0 django-formtools 2.3 django-sekizai 2.0.0 django-treebeard 4.5.1 djangocms-admin-style 2.0.2 settings.py (relevant section) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'cms', 'menus', 'treebeard', 'sekizai', 'news', ] SITE_ID = 1 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', 'django.middleware.locale.LocaleMiddleware', 'cms.middleware.user.CurrentUserMiddleware', 'cms.middleware.page.CurrentPageMiddleware', 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] LANGUAGES = [ ('en', 'English'), ] … -
how to redirect in django through select option in forms.py
I need help. I am makig a sign up page in django In my forms.py I have two select optins. option 1) free trial & option 2)monthly subscription I want user to go to login page if he selects option1 and to checkout page if he selects option2. here is my code. forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() CHOICES = (('Option 1', 'Free 30 days trial'),('Option 2', '$9.99 Monthly subscription')) plan = forms.ChoiceField(choices=CHOICES) class Meta: model = User fields = ['username', 'email', "plan", "password1", "password2" views.py def signupUser(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): if plan == 'Free 30 days trial': form.save() return redirect("/main/login/") else: form.save() return redirect("/main/checkout/") else: form = RegisterForm() return render(request, 'signup.html', {"form":form}) but this gives error: plan is not defined Need help please. -
Django REST Framework field serializer validation is not being called
After some hours of research, I still can't find the answer to the issue I am facing. I am trying to add some simple validation to a field in one of my models. In serializers.py: class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = '__all__' def validate_name(self, value): """ Check that the brand name has at least 20 characters """ if len(value) < 20: raise serializers.ValidationError( "The name of the brand should be longer than 20 characters") return value I am using function based views: @api_view(['POST']) def brandCreate(request): data = request.data try: brand = Brand.objects.create( name=data['name'], ) serializer = BrandSerializer(brand, many=False) return Response(serializer.data) except: message = {'detail': 'Brand is not created'} return Response(message, status=status.HTTP_400_BAD_REQUEST) And this is my model: class Brand(models.Model): name = models.CharField(max_length=80) logo = models.ImageField(null=True, blank=True) def __str__(self): return str(self.name) After sending a POST request with postman, the record is successfully created, even though the name is shorter than 20 characters! Any hints on what I am missing here? Thank you! -
Bootstrap exception thrown when overriding PasswordResetConfirmView in Django
I am getting a bootstrap exception when trying to override the PasswordResetConfirmView in Django. Parameter "form" should contain a valid Django Form. Request Method: GET Request URL: http://127.0.0.1:8000/SL_webapp/reset/MQ/amcfbe-81074d0d92c35e3b6c9eeb50bc141582/ Django Version: 3.1.7 Exception Type: BootstrapError Exception Value: Parameter "form" should contain a valid Django Form. Exception Location: /Users/arnasastapkavicius/opt/anaconda3/envs/TM470/lib/python3.9/site-packages/bootstrap5/renderers.py, line 144, in __init__ Python Executable: /Users/arnasastapkavicius/opt/anaconda3/envs/TM470/bin/python Python Version: 3.9.1 My code is as follows: my URL patterns in urls.py urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), ] my password_reset_form.html file: {% extends "base.html" %} {% load bootstrap5 %} {% block content %} <div class="container"> <div class="col-lg-6 p-5"> <h1>Enter new password.</h1> <p>Please enter your new password twice so we can verify you typed it in correctly.</p> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" class="btn btn-warning btn-lg" value="Update password"> </form> </div> </div> {% endblock %} I cannot understand why this is happening, as another form using bootstrap that I have overriding PasswordResetView with password_reset.html renders correctly. Any ideas? Thank you in advance. -
Send data from Jquery to Django html template
how can I get a list of data from JQuery (Ajax) into the the Django HTML templates, forexample in my file : transitions.js, I have this : window.addEventListener("load", function() { (function ($) { 'use strict'; const transition_id = $(".trans_id").get(0).id; cooperationPartnerTransitions(transition_id) function cooperationPartnerTransitions(id) { $.ajax({ url: `/api/v1/accounts/cp_transitions/${id}`, type:'get', dataType: 'json', headers: {}, success: function (data) { console.log("--->", data) } }); } })(django.jQuery); }); then, in my plan.html I have this : {% extends 'admin/custominlines/change_form.html' %} {% load static %} {%block extrahead %} <script src='{% static "admin/js/transitions.js" %}'></script> {% endblock %} {% load i18n %} {% block submit_buttons_bottom %} {{ block.super }} {% if request.GET.edit %} <div class="submit-row"> <div class="trans_id" id="{{ original.pk }}"></div> <input type="submit" value="custom" name="_transition-states"> </div> {% endif %} {% endblock %} I want to access the data from Jquery so that I can loop the button, how can I do this -
how to migrate django database after model change?
I have model M1. it had a field F1 of type IntegerField. I created a number of items and filled their F1 with numbers. Then I created new model M2 and changed F1 to be ForeignKey to M2. makemigrations worked fine. But migrate doesn't work - since it can't find M2 items corresponding to old F1 int values. Moreover I can't delete M1 items through shell - attempt to get Objects.all() result in same error. How can I delete "problematic" items of M1 without flushing database?