Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello! I have a problem. When deleting a comment, the error Post matching query does not exist appears
I have a problem. When deleting a comment, the error Post matching query does not exist appears. And I do not know what to do with it. Thank you in advance! Error: Does Not Exist at /news/post/6 Post matching query does not exist. Note! I use the django framework Here is the code: views.py: from django.shortcuts import render from django.urls import reverse_lazy from .forms import PostForm, CommentForm from .models import Post, Comment from django.views import View from django.views.generic.edit import UpdateView, DeleteView class PostListView(View): def get(self, request, *args, **kwargs): posts = Post.objects.all().order_by('-created_on') form = PostForm() context = { 'post_list': posts, 'form': form, } return render(request, 'news/post_list.html', context) def post(self, request, *args, **kwargs): posts = Post.objects.all().order_by('-created_on') form = PostForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() context = { 'post_list': posts, 'form': form, } return render(request, 'news/post_list.html', context) class PostDetailView(View): def get(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'post': post, 'form': form, 'comments': comments, } return render(request, 'news/details_view.html', context) def post(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'post': … -
How i can show gis_models map in django templates?
models.py: ADDRESS_WIDGETS = { # ... 'point': gis_forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}), } srid = 4326 class Address(UUIDMixin, models.Model): city = models.ForeignKey(...) street = models.CharField(...) house_number = models.CharField(...) entrance_number = models.SmallIntegerField(...) floor = models.SmallIntegerField(...) flat_number = models.SmallIntegerField(...) point = gismodels.PointField( _('address geopoint'), srid=srid, ) tours = models.ManyToManyField(...) class Meta: # db_table, verbose_name, unique_together forms.py: class SettingsAddressForm(forms.ModelForm): def __init__(self, request: HttpRequest = None, *args, **kwargs) -> None: super(SettingsAddressForm, self).__init__(*args, **kwargs) if request and isinstance(request, HttpRequest): user = Account.objects.get(account=request.user.id) self.fields['city'].initial = user.agency.address.city self.fields['street'].initial = user.agency.address.street self.fields['house_number'].initial = user.agency.address.house_number self.fields['entrance_number'].initial = user.agency.address.entrance_number self.fields['floor'].initial = user.agency.address.floor self.fields['flat_number'].initial = user.agency.address.flat_number self.fields['point'].initial = user.agency.address.point class Meta: model = Address fields = ['city', 'street', 'house_number', 'entrance_number', 'floor', 'flat_number', 'point'] widgets = ADDRESS_WIDGETS views.py: def settings(request: HttpRequest) -> HttpResponse: request_user = request.user user = Account.objects.get(account=request_user.id) address_form = SettingsAddressForm(request) # ... return render( request, 'pages/settings.html', { 'request_user': request_user, 'user': user, 'address_form': address_form, 'style_files': [ 'css/header.css', 'css/body.css', 'css/tours.css', 'css/profile.css', ], }, ) pages/settings.html: {% extends 'base.html' %} {% load static %} {% block content %} <section class="home"> <div class="container"> {% if user.account.is_active %} <div class="left"> <!-- ... --> {% if user.agency %} <div class="agency_info"> <h3>Турагенство</h3> <form method="post"> {% csrf_token %} {{ agency_form.as_p }} <!-- ↓↓↓ here ↓↓↓ --> {{ address_form.as_p }} … -
'django' is not recognized as an internal or external command
I had installed django at C:\Users\05554F744 Now, to create a Django project, I'm doing C:\Users\05554F744\Box\Nupur\Learning\Python\Django>django -admin startproject djangoprojects I get the message "'django' is not recognized as an internal or external command,operable program or batch file." What should I do to fix this? I want my "djangoprojects" folder inside C:\Users\05554F744\Box\Nupur\Learning\Python\Django -
Sending GET request from front-end app to the back-end app does not contain cookies ( front nextJS + back Django )
So basically from what I read across the internet, Django cookies are stored in the sessions I guess, and when we try to access them what so ever, there will be sessionid in the cookies and it makes the cookies (like accessing the user stored in the request and stuff) achievable. My problem is that I have a front-end, and in that I try to get the data of a 'Post'. The problem is that in my GET request, from what I invested, there are no cookies sent to the back-end, and because of that, the sessionid is gone and my user that is stored (or better to say must be stored) in the request is gone (AnonymousUser it is). The fun fact is there is another view in my Django app for logout, which works prefect and the request does have the sessionid and access to the user in the request. My question is, is this a problem with my views ?! Is it general ?! What is causing this to happen ?! I really need this to be fixed, cause all my project is actually getting collapsed because of this problem I have with fetching data. How do … -
How to get the body from the POST request correctly in the Django Rest Framework
All I want is to get the body from my request, but I don't understand how to do it, I tried request.data but it returns a string, after I tried using json.loads(request.data), but it just refused to work. I just want to parse the nested json, why is it so difficult in Django. My code class TestCheckView(views.APIView): def post(self, request, pk): result = Result() test_id = request.data.get("id") data = dict(request.data) for question in data["questions"]: print(type(question)) for answer in question["answers"]: result.total += 1 if Answer.objects.get(id=answer["id"],question_id=question["id"]): result.score += 1 result.test = Test.objects.get(id=test_id) result.save() what i want get "id":1, "title":"Тест по теме тестов", "questions":[ { "id":1, "title":"Вопрос 1", "answers":[ { "id":1, "title":"Ответ 1", "is_right":true }, { "id":2, "title":"Ответ 2" } ] }, { "id":2, "title":"Вопрос 2", "answers":[ { "id":3, "title":"Ответ 1", "is_right":true } ] } ] } -
Vue + Vuetify with Dhango, not all styles are loading
I am working on a SPA application (my first work with frontend frameworks) that needs to show in a spreadsheet the patients and their studies, I have connected vue and vuetify to my project but after build/dev command not all styles are loading. package.json file I have configured that generated vue files are going to my statics folder vue config static folder settings py Аfter that I load them in my html file index html But on an actual page it seems like some styles are missing, like there is not vuetify icons and fonts result result console How do i fix this issue @vue/cli 5.0.8 vuetify - 3.6.7 Tried to reinstall vue, tried to reconfigure static and etc. -
Again on Django template inheritance
The difficulty I have is precisely described in Django Accessing Parent Data in templates from child data but the answer given there, accepted by the OP, is given in the “recipe” spirit, as are an incredible number of others I found, concerning the same issue. Even the django official documentation, having to document an enormously vast field, suffers from this disease. So, since I would like not the fish but the fishing rod, please let me restate the question in my terms: I have a father template and children templates, the latter all filling one block defined in the father template, one at a time. The father template is shown by calling a father-view in father.py, with a father-context, and the view-template relation for the father is given by a line in some urls.py file. This fills the upper part of the browser screen with some type of “summary data”. When this is done, it is time to fill up the lower part, with different types of detail information, one at a time of course. I do this with different children views, using in the father-template idioms like {% url ‘djangoapp:details1’ param1_a %} or {% url ‘djangoapp:details2’ param2_a param2_b param2_c … -
Django -> ModuleNotFoundError: No module named 'google'
I have installed google-cloud-translate both on my localhost and on my production environment. pip install google-cloud-translate When I import it in my Django app with from google.cloud import translate_v2 as translate then It works fine on my localhost but on my production environment I get this error: ModuleNotFoundError: No module named 'google' Although the package is installed in the correct folder: /home/mysuer/.local/lib/python3.9/site-packages I also created a small test script: try: #import google from google.cloud import translate_v2 as translate print("Module 'google' found!") except ImportError as e: print("Module 'google' not found:", e) When I execute this script then the output is: Module 'google' found! So with the test script the package was found and with my Django app the package was not found!? Anybody who can help me on this? I tried debugging, reinstalling the package, checking my Python version, creating a test script, ... but I cannot find a solution... -
Django: Two indepent searchable dropdown with select2 and ajax does not work
I would like to have two searchable dropdowns which are linked to two different modals (Dog & Service). The first dropdown for the products (services modal) works fine (expect, that i dont have a preview), but the second dropdown which should be linked the to the dog modal doesn't work as expected. The searchfunction only shows results which are in the other modal (service). However if I select one of the results, the actual selection in the dropdown equals the value from the correct dog modal. I already tried to find the same problem online, but could not. .html <!-- Searchbox_dog linked to Dog Modal --> <form method='post' action='' class="mb-3"></form> <label for="dog" class="form-label">Dog:</label> <select class="form-select select2" name="searchbox_dog" id="searchbox_dog"> {% for dog in dogs %} <option value='{{dog.id}}'>{{ dog.dog_name }}</option> {% endfor %} </select> </form> <!-- Searchbox_service linked to Service Modal --> <form method='post' action='' class="mb-3"> <label class="mb-1">Search service:</label> <select class="form-select select2" name="searchbox_service" id="searchbox_service"> {% for service in services %} <option value='{{service.id}}'>{{ service.name }}</option> {% endfor %} </select> </form> javascript let csrftoken = '{{ csrf_token }}' $('#searchbox_dog').select2({ dealy: 250, placeholder: 'Search dog', minimumInputLength: 1, allowClear: true, templateResult: template_dog_searchbox, ajax:{ type: "POST", headers:{'X-CSRFToken':csrftoken}, url: "{% url 'get_dogs' %}", data: function (params) { var … -
I have created a CustomUser model and it shows up in base app and not under Authorization and Authentication
I have created a custom user model which is inside the base app and the custom user model shows up in base app in the admin site instead of authorization and authentication. Why is it coming under it? Here is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import CustomManager # Create your models here. class CustomUser(AbstractBaseUser): name = models.CharField(max_length=50,default='Yet to be updated...') email = models.EmailField('email_address', unique=True) USN = models.CharField(max_length=10, default='Yet to be updated...') is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) # updated = models.DateTimeField(auto_now=True) # created = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomManager() def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser def __str__(self): return self.email Here is my managers.py from django.contrib.auth.base_user import BaseUserManager class CustomManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError("Email is must") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(email, password, **extra_fields) Here is my admin.py from django.contrib import admin from .models import CustomUser # Register your models here. admin.site.register(CustomUser) why is the custom user not under Authorization and Authentication and how can I add … -
Django multi-selection in the form with CBV django
I have 2 models: Group and Post. Group is ManyToManyField to Post models.py class Group(models.Model): group_name = models.CharField( verbose_name="Group Name", max_length=4000, blank=False, ) class Post(models.Model): id = models.CharField(verbose_name="Post ID", max_length=1200, primary_key=True) group = models.ManyToManyField( Group, verbose_name="Group", related_name="post_group", ) How can i select 2 groups for one post in the form? Thanks a lot I tried somethings but without any success -
how to prevent sql injection in snowflake filter function
Im using input from the user to query snowflake within DRF view, how to prevent in the below code sql injection possibility? entity_id = kwargs['pk'] table = session.table("my_table").filter(col(ID_COL)==entity_id ) -
Django loads static files from a whole diff project
I have two folders, each one containing a Django project, each project has a templates folder and a static folder, for the sake of simplicity lets just call them project A and B, the static folder has a sub folder called CSS for both of them now in project A i use STATIC_URL = "static/" STATICFILES_DIRS = \[ BASE_DIR / "static", \] and i easily load my static files in my html no issue now in project B i write the same thing but instead of loading static files from B/static/css it loads them from A/static/css which is so weird and i've no clue how to fix it, why is this happening ? So far I haven't tried anything specific as I expected the BASE_DIR to handle the project path effectively, I have been reading the docs, to no avail, and the only thing I can think of is moving the project folder, but why do I have to do that? Surely there is a better way so I can keep my folder organized -
Django not loading CSS (static files)
I'm a beginner to Django trying to apply a CSS file (stored in base/static/css) to the base page of a web app. For some reason the file is not applying to the page, and I'm getting an output of "GET /social/ HTTP/1.1" 200 29461 when I refresh the page. I've tried to apply other answers to the same issue, such as making sure django.contrib.staticfiles and my base folder socialnetwork are in INSTALLED_APPS, using STATICFILES_DIRS instead of STATIC_ROOT (in conjunction with using python manage.py collectstatic in terminal) or having them point in different folders, and putting urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) in my urls.py file, which worked once and then immediately went back to the same error (I also tried using staticfiles_urlpatterns() instead of this). After looking through the docs I tried disabling and clearing recent cache using Developer Tools in my browser, as well as manually restarting the server using Ctrl+C and python manage.py runserver, both not seeming to have an effect (although after deleting cache I did get a 404 error for some media files which cleared up quickly). I did have a similar issue with loading in media files earlier, but this was fixed easily with urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) which … -
Django Template - Issues accessing child models / running conditional tests
I am trying to run a conditioanl test in a Django Template based on a count of child objects. I have passed a varible to the Template called "productcodes" and I can successfully iterate through the each item within it. Models class Productcode(models.Model): product_code = models.CharField(max_length=50) def __str__(self): return self.product_code class Test(models.Model): worksorder = models.ForeignKey(Worksorder, blank=True, null=True, on_delete=models.CASCADE,) productcode = models.ForeignKey(Productcode, blank=True, null=True,on_delete=models.CASCADE) tester = models.ForeignKey(Tester, blank=True, null=True,on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return self.date {% if productcodes %} {% for code in productcodes %} <tr> <th scope="row"><a href="show_productcode/{{ code.id }}"> {{ code }} </a></th> {% if code.test_set.all.count < 1 %} <td> 0 </td> {% elif %} <td>{{ code.test_set.all.count }}</td> {% endif %} <td>Future Dev WO</td> </tr> {% endfor %} {% endif %} The issue I am having is this if statement is failing with the error: Unexpected end of expression in if tag. {% if code.test_set.all.count < 1 %} I've tested the expression on the shell ok, am I missing something obvious? Best Regards Colin. I am expecting a count of child objects to br printed in the table. -
Google Authentication with Django and Flutter
I created a mobile app called Dermalens, which tests whether a skin lesion is benign or not. The app is developed using Flutter for the frontend and Django for the backend. When a user signs in from the Flutter app, they are requesting a JWT token. During sign-up, a new object is created from the Account model, which is a customized built-in user model in Django. Whenever a user uploads an image for testing, an object from the SkinImage model is created, which has a many-to-one relationship with the Account model. My problem is that I want to add Google authentication to the mobile app. How can I achieve that? -
timedata does not match format even though they are identical
Issue: ValueError: time data '2024-05-26 18:00' does not match format 'YYYY-MM-DD HH:mm' I use DRF to fetch POST for api/reservations/. But Django complained that str cannot be passed to DateTimeField. So I tried to format str into proper datetime. But even though the string and format are exactly identical, various method still complain about something unknown by me. Code: def create(self, validated_data): validated_data.update({ 'reservation_time': datetime.datetime.strptime(validated_data.get('reservation_time'), 'YYYY-MM-DD HH:mm').date() }) return self.Meta.model(**validated_data) I was trying to change datetime format via JS to "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." (point a the end is a part of format and not a typo) and do so in Python, no progress. Tried django.utils.dateparse.parse_date as well, as datetime.datetime.strptime. parse_date returned None, meaning, something is wrong with format and strptime raises ValueError above. What am I missing? -
Django app 404 error not recognizing new apps url and views
Hi I am trying to create my first Django project and having issues getting an app to work inside my Django project. I simply am trying to map the url code 8000/home1/hello/ to display the basic text "hello world" but failing to do so. I keep getting this error code: Using the URLconf defined in web3.urls, Django tried these URL patterns, in this order: admin/ The current path, home1/hello, didn’t match any of these. but still can not figure out why my code is not working.... Here is what I have done: created a django project named web3 created an app called home1 and added a urls.py file to this app updated the settings.py folder INSTALLE_APPS to have 'home1.apps.Home1Config', home1 > urls.py includes this code: from django.urls import path from . import views `urlpatterns = [ path('hello/', views.hello_world, name="hello_world"), ] ` home1>views.py includes this code: ` from django.shortcuts import render from django.http import HttpResponse def hello_world(request): return HttpResponse("you finally did it justin")` 6.web3> urls.py includes this code: `from django.contrib import admin from django.urls import path, include from home1.views import hello_world # Import the hello_world view function urlpatterns = [ path('admin/', admin.site.urls), path('', include('home1.urls')), ] ` I am pretty confident my … -
No DATABASE_URL environment variable set, and so no databases setup
While Deploying Django website on AWS EC2 server i am getting error No DATABASE_URL environment variable set, and so no databases setup. I Created a gunicon.service file on my server location /home/ubuntu/lighthousemedia/LightHouseMediaAgency and set EnvironmentFile=/home/ubuntu/lighthousemedia/LightHouseMediaAgency/.env to get the environment variables and in the same location i created a .env file which contain the DATABASE_URL = postgresql://postgres:password@lighthousemediadb.crte3456.ap-south-1.rds.amazonaws.com:5432/dbname. I believe that .env file is in the correct location. Also check my DATABASE is set correctly. production.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lighthousemediadb', 'USER': "postgres", 'PASSWORD': os.environ.get('DB_PASSWORD'), # dont keep it hardcoded in production 'HOST': os.environ.get('DB_HOST'), 'PORT': '5432', # add these too it improve performance slightly 'client_encoding': 'UTF8', 'default_transaction_isolation': 'read committed', 'timezone': 'UTC' } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) DATABASES['default']['CONN_MAX_AGE'] = 500 gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data EnvironmentFile=/home/ubuntu/lighthousemedia/LightHouseMediaAgency/.env WorkingDirectory=/home/ubuntu/lighthousemedia/LightHouseMediaAgency ExecStart=/home/ubuntu/lighthousemedia/.venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ BE.wsgi:application [Install] WantedBy=multi-user.target .env SECRET_KEY = 'epmxxxxxxxxxxxxu$0' DEBUG = True ALLOWED_HOSTS = '3.196.58.181', 'abc.com', 'localhost', '127.0.0.1' DB_PASSWORD = 'password' DB_HOST = 'lighthousemediadb.crte3456.ap-south-1.rds.amazonaws.com' DATABASE_URL = postgresql://postgres:password@lighthousemediadb.crte3456.ap-south-1.rds.amazonaws.com:5432/dbname -
Order Django QuerySet by where a term appears in results
I'm trying to implement an autocomplete for an input field using Django and jQuery (user searches for a food from a menu). The problem is figuring out how to order the results. If, for example, the user types "Fish", I want the autocomplete to be ordered like this: "Fish and Chips" "Fish fry" "Fried fish" "Fried catfish" So results would be ordered primarily by where the search term appears in the name, then in alphabetical order after that. My QuerySet is currently retrieved in Django with views.py def load_menu(request): term = request.GET['term'] # the search term typed by user menu = Menu.objects.filter(item__icontains=term).order_by('item', 'id') # item = name of food # constructing JSON response data = [] for item in menu: item = { 'label': item.item, 'value': item.id, } data.append(item) return JsonResponse({'data': data}) # received by jQuery function to display autocomplete menu but that orders results alphabetically only, which I don't want. How can I order like I specified in the example above? -
Error while digitally Singing on multiple pages in a pdf using python endesive
I'm trying to digitally sign the pdf document using Class 3 USB token by searching a specific text 'Authorised Signatory' in the page, it works perfectly fine when i have to sign a pdf once. But in one of my scenario i came across multiple page document and in which i have to sign each page, After signing the pdf when i tried to validate the signatures in the Adobe pdf reader it has only validated my first signature as shown in the below screenshot And I was not able to see the annotations of the second and third page. Here is my code, def post(self, request): serializer = PDFSignSerializer(data=request.data) if serializer.is_valid(): data = serializer.validated_data.get('pdf_base64') try: pdf_data = base64.b64decode(data) except Exception as e: return Response({'error': f'Failed to decode base64 PDF data: {e}'}, status=status.HTTP_400_BAD_REQUEST) # Search for text in the PDF and retrieve coordinates text_to_find = 'Authorised Signatory' # Text to search for (modify as needed) text_positions = self.find_text_in_pdf(pdf_data, text_to_find) if not text_positions: return Response({'error': 'No position found for signature'}, status=status.HTTP_400_BAD_REQUEST) # Get the current UTC time using timezone-aware objects current_utc_time = datetime.datetime.now(datetime.timezone.utc) # Calculate the Indian time by adding the UTC offset of +5:30 indian_time = current_utc_time + datetime.timedelta(hours=5, minutes=30) … -
Adding a 24-hour timer for each item added to a cart
I'm trying to add a 24-hour time limit for each item added to a cart. I want the items removed from the cart after the time expires. const isExpired = (timestamp) => { const now = new Date().getTime(); const oneDay = 24 * 60 * 60 * 1000; return now - timestamp > oneDay; }; const removeExpiredItems = () => { for (let productId in cart) { if (isExpired(cart[productId].addedAt)) { delete cart[productId]; } } }; -
Conditional Caching when Looping Through Blocks in Django
On our site, we are looping through wagtail blocks for many of our webpages. Some of those blocks contain webforms or dynamic/personalized data, and thus cannot be cached. We want to provide maximum flexibility for the editors to update webpages without needing to touch the code, but also to provide good performance and load times. In the below code, the field page.body is a wagtail streamfield where the editors can add any number of content blocks and in any order. Here is the desired solution, with simplified code, which fails: {% load cache wagtailcore_tags %} <!-- Start the page cache --> {% cache timeout url_path %} {% for block in page.body %} <!-- disable the cache before an excluded block --> {% if block.disable_cache %} {% endcache %} <!-- template engine throws an error at this "endcache" tag --> {% endif %} {% include_block block %} <!-- reenable the cache after an excluded block is rendered --> {% if block.disable_cache %} {% cache timeout block.uuid %} {% endif %} {% endfor %} <!-- end the page cache --> {% endcache %} Let's say a page has 15 blocks, with a single block in the middle having a form that should … -
DRF test user sign-in, error inactive user
I have view for authentfication: class UserViewSet(viewsets.ViewSet): @method_decorator(sensitive_variables("password")) @action(url_path="sign-in", detail=False, methods=["POST"]) def sign_in(self, request: HttpRequest) -> Response: if not request.user.is_anonymous: return Response({"status": "forbidden"}, status=403) form = AuthenticationForm(data=request.data) print(form.data) if form.is_valid(): user = authenticate(request, **form.cleaned_data) login(request, user) return Response({"status": "ok"}, status=200) print(form.error_messages) raise ValidationError(form.errors) I write the test: class UserTest(TestCase): @classmethod def setUpClass(cls): User.objects.create(username="admin", password="Qwerty1234", is_active=True) super().setUpClass() cls.client = Client() @classmethod def tearDownClass(cls): return super().tearDownClass() def test_sign_in(self): url = "/api/sign-in/" print(User.objects.get(username="admin").is_active) response = self.client.post( url, data={"username": "admin", "password": "Qwerty1234"}, content_type="application/json", ) But, I receive the errors from form form_validator: {'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'} What can be a problem? P.S. At that case, is there any sense to use sensitive_variables? Thx! -
Reading query string in Wagtail
I am new to Wagtail and I am trying to work out how to extract the query string as part of the FormPage model. In models.py I tried: def get_context(self, request): context = super().get_context(request) context['embed'] = request.GET.get('embed') return context But I'm not 100% how to call this in my FormPage model to include this in the email that will be sent when a form is submitted. I've tried to add the following to the FormPage model: def get_context(self, request): context = super().get_context(request) context['embed'] = request.GET.get('embed') return context