Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Python){MCQ} Select which is not true about python web development?
More then 1 option can be correct! Select the statement which is not true about python web development? Need to configure your web server to announce its version access-control-allow-origin header value should be set to "*" firewall address the vulnerability issue such as sql injection, xss,etc. So,i its not required to handle in python code Python code needs to address only the vulnerability that are not addressed by firewall -
Django: ValidationError ['ManagementForm data is missing or has been tampered with']
Django: ValidationError ['ManagementForm data is missing or has been tampered with'] i have been getting this error when i use the forminline factory module, im sorry if my question isnt placed properly, this is my first time here. my form template is this: {% extends 'accounts/main-form.html'%} {% load static %} {% block title %} <title>CRM | Form</title> {% endblock %} {% block link %} <link rel="stylesheet" type="text/css" href="{% static 'css/style1.css'%}"> {% endblock %} {% block content %} <div class="container"> <form action="" method="POST"> {{formset.management_form}} {% for i in formset %} {{i}} {% endfor %} <input type="submit" class="btn" value="submit"> </form> </div> {% endblock%} this is the form code in views.py def order_form(request, pk): customers = Customer.objects.get(id=pk) OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status',)) formset = OrderFormSet(request.POST) if request.method == 'POST': formset = OrderFormSet(request.POST, instance=customers) if formset.is_valid(): formset.save() return redirect('/') context = {'formset': formset} return render(request, 'accounts/order_form.html', context) my models from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('OutDoor', 'Outdoor') ) name = models.CharField(max_length=200, null=True) … -
How to write URL For multiple Slug
here is my path path('<slug:category_slug>/<slug:city_slug>/<slug:slug_text>/', views.category_view_detail, name='post_detail'), how to write URL for this example {% url 'post_delete' posts.slug %} but i want to add all three slug inside the URL how to do something like this... ({% url 'post_detail' posts.category posts.city posts.slug %}) but this not work.. -
Django error by adding Channels to settings.py INSTALLED_APPS
I'm trying to learn Django channels, so for the beginning, I simply installed and added "channels" to the Django project, INSTALLED_APPS in the settings.py, as showing below. Installed channels with pip: pip install channels Installed versions: channels 3.0.3 daphne 3.0.1 Django 2.2.13 settings.py > INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ... 'django_ace', 'channels', # added this ] I just installed one package and added one line to the settings.py so this shouldn't be an error, but when I try to run the server python .\source\manage.py runserver I got an error as showing below. > python .\source\manage.py runserver --noreload Traceback (most recent call last): File ".\source\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "c:\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File … -
Cannot assign "OrderedDict()...: "..." must be a "..." instance
Im using Django Rest & React to make a web app. models.py RegoNumber = models.CharField(max_length=10) RegoExpiry = models.DateField(auto_now=False,auto_now_add=False) LastRentedDate = models.DateField(auto_now=False,auto_now_add=False) def __str__(self): return self.RegoNumber class Hire(models.Model): # StartRentDate = models.DateField(auto_now=False,auto_now_add=False,null=True) # EndRentDate = models.DateField(auto_now=False,auto_now_add=False,null=True) KMsLastShown = models.IntegerField() KMsToLastService = models.IntegerField() # ServiceHistory = models.FileField() LastService = models.IntegerField() RentalPrice = models.FloatField() Bike = models.OneToOneField(Bike,on_delete=models.CASCADE,null=True,related_name='Bike') def __str__(self): return f'Bikes hire data' serializers.py from rest_framework import serializers, fields from drf_writable_nested.serializers import WritableNestedModelSerializer from .models import Hire, Bike class BikeSerializer(serializers.ModelSerializer): class Meta: model = Bike fields = '__all__' class HireSerializer(WritableNestedModelSerializer): Bike = BikeSerializer(required=False) class Meta: model = Hire fields = '__all__' index.js (react) import ReactDOM from 'react-dom' import {useReducer} from 'react' import Cookies from 'js-cookie' ReactDOM.render( <React.StrictMode> <App/> </React.StrictMode>, document.getElementById('root') ) function App(){ function sendData(e) { e.preventDefault() const csrftoken = Cookies.get('csrftoken'); const dataToSend = { method: 'POST', headers: {'Content-Type':'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ KMsLastShown: 0, KMsToLastService: 50, LastService: 50, RentalPrice: 40, Bike: { RegoNumber: 'Hello', RegoExpiry: '2020-05-11', LastRentedDate: '2020-07-07' } }) } console.log('Working') fetch('/api/hire/',dataToSend) .then(response => response.json()) .then(json => console.log(json)) } return ( <> <button onClick={function(e){sendData(e)}}></button> </> ) } When I try making a Post request in my index.js of the Bike, it returns an error Cannot assign "OrderedDict([('RegoNumber', 'Hello'), … -
Django on Heroku. See all GET requests of a path
I have a Django 2.0 project hosted on Heroku. In the logs, this is what a GET request looks like: timestamp source[dyno]: message 2021-02-14T05:23:35.513467+00:00 heroku[router]: at=info method=GET path="/static/tag.gif"... I'd like to be able to access the full GET request message with python in the Django project. I'd preferably like to get this through the django-heroku library. If that's not possible, then I'd like some way to scrape the Heroku logs. I know they can be filtered by source and dyno via CLI, but I haven't seen anything about filtering by message. Maybe there's a way to add a listener of sorts? -
django.db.utils.ProgrammingError in Cpanel
when i migrate in Cpanel get this error : django.db.utils.ProgrammingError: (1146, "Table 'morvari2_morvarid_store_db.store_setting_setting' doesn't exist") -
Uploading multiple files using Django & React
I'm using Django Rest Framework and React for my recent project. I need to upload multiple images/files from my React frontend to the Django REST backend. I'm not sure which is the efficient way to do it. 1: Looping over each selected image/file using React and sending them one by one to the backend. 2: Accepting multiple images/files from the frontend, and looping through each image/file, and saving it in the backend. -
File not uploading in Django
I am trying to upload a file in Django to models: class Dealer(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT) profile = models.OneToOneField(UserProfile,on_delete=models.PROTECT) kyc_verified = models.BooleanField('kyc status',default=False) aadhar = models.FileField(upload_to='aadhar_images') pan = models.FileField(upload_to='pan_images') gts = models.FileField(upload_to='gts') registration = models.FileField(upload_to='registration') manager = models.CharField(max_length=75) manage_mobile = models.IntegerField() And in media, I have created the folders aadhar_images, pan_images,gts,registration. But when I am uploading a file using the form in html: <form method="post" action="{% url 'dealer:update' %}" enctype="multipart/form-data"> {% csrf_token %} <br><br> AAdhar upload : <input type="file" name="aadhar" id="aadhar" accept="*"><br><br> Pan upload : <input type="file" name="pan" id="pan" accept="*"><br><br> Gts upload : <input type="file" name="gts" id="gts" accept="*"><br><br> Registration upload : <input type="file" name="registration" id="regis" accept="*"><br><br> </form> and in views.py: def update(request): if request.method=='POST': user = User.objects.filter(username=request.user).values()[0]['id'] try: aadhar = request.FILES['aadhar'] print(aadhar) Dealer.objects.filter(user=user).update(aadhar=aadhar,kyc_verified=False) except: pass try: pan = request.FILES['pan'] Dealer.objects.filter(user=user).update(pan=pan,kyc_verified=False) except: pass try: gts = request.FILES['gts'] Dealer.objects.filter(user=user).update(pan=gts,kyc_verified=False) except: pass try: reg = request.FILES['registration'] Dealer.objects.filter(user=user).update(registration=reg,kyc_verified=False) except: pass After i submit the form, the files are not uploaded to their respective directories. Also the url in the database is showing as media/filename, but the files are not uploaded even in the media directory also. -
Display list of images with their name in Django model Form -Python , Django
The thing I am trying is a little bit tricky here. I want to display the thumbnail list of images in the model form. I am working with Django 3.1.2. Here are my models: models.py # This is the Product table which stores the basic detail of Product. class Packages(models.Model): package_ID = models.AutoField("Package ID", primary_key=True) package_Name = models.CharField("Package Name", max_length=30, null=False) attribute_values = models.CharField("Item Details JSON", max_length=200, null=False) package_Price = models.IntegerField("Package Price", null=False, default=0.00) prod_ID = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Product ID (FK)") # This will store the images path. class ImageTemplate(models.Model): temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True) temp_img = models.ImageField("Template Image", null=False) # This will store the image Product mapping means which images are related to which product cause there is number of images of single Product. class ImageTemplateProductMapping(models.Model): imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True) temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE, verbose_name="Image Template ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") Now this is my form which is working fine. Form.py class ImageTempProductMapForm(forms.ModelForm): class Meta: model = ImageTemplateProductMapping fields = ['temp_id', 'prod_id'] And this is my views which is also fine and I am not getting any error here. views.py @login_required(login_url="admin-login") @user_passes_test(check_role_admin_or_designer) def imageTempProductMap(request): form = ImageTempProductMapForm(request.POST, request.FILES) … -
Issues with serving Django application on Apache Server
I am getting the following error on my web server: mod_wsgi (pid=224890): Failed to exec Python script file '<path to Django project>/wsgi.py'. mod_wsgi (pid=224890): Exception occurred processing WSGI script '<path to Django project>/wsgi.py'. Traceback (most recent call last): File "<path to Django project>/wsgi.py", line 16, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' On similar problems it tells me to add python-path and python-home to my WSGIDaemonProcess in my VirtualHost, however if I do that, I get the following error: Current thread 0x00007fe0c4ecfc40 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/usr/local/lib/python3.8/dist-packages' 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 = '/usr/local/lib/python3.8/dist-packages' sys.base_exec_prefix = '/usr/local/lib/python3.8/dist-packages' sys.executable = '/usr/bin/python3' sys.prefix = '/usr/local/lib/python3.8/dist-packages' sys.exec_prefix = '/usr/local/lib/python3.8/dist-packages' sys.path = [ '/usr/local/lib/python3.8/dist-packages/lib/python38.zip', '/usr/local/lib/python3.8/dist-packages/lib/python3.8', '/usr/local/lib/python3.8/dist-packages/lib/python3.8/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' The site only works when I'm running python3 manage.py runserver <ip of server>:8000. -
CACHING IN DJANGO REST FRAMEWORK
I am using low level caching API I want to cache the queryset result in the django rest API, the problems i am facing is: Queryset result is dependent on input provided to the API. { "status": "Deactive", "location" : ["India","us"], "hashtagID": "1" } Suppose , I cache this result using some key, say Status_1 cache_key = "Status_1" query_set = ***query to filter the model using the above input*** cache.set(cache_key, query_set) Now, if again user gives the same input to the API, How would i come to know that query_set respected to that input is already cached?? Simply, i want to create such a caching system in Django rest framework, where we can cache queryset which vary according to input provided to rest API. -
Django + Celery + Flower seems to break RabbitMQ broker
I've working on a fresh headless Debian install of Django (3.1.6) + Celery (4.4.7) + RabbitMQ (3.7.8) + Flower (0.9.7). (I was running with Celery 5, but downgraded to 4.4.7, because of a bug.) Django, Celery, and Flower are Pip installed and RabbitMQ by Debian apt-get The code is all from demo examples of Celery First Steps with Django I'm able to get a basic Celery example to work and monitor it with the Django/admin and other monitor processes using ip:port, Django Site: http://192.168.1.102:8000/admin/django_celery_beat/ Flower: http://192.168.1.102:5555/dashboard RabbitMQ Management Console: http://192.168.1.102:15672/ Celery works without flower: > celery -A pyauto beat -l INFO celery beat v4.4.7 (cliffs) is starting. __ - ... __ - _ LocalTime -> 2021-02-13 19:55:19 Configuration -> . broker -> amqp://<user>:**@localhost:5672/<vhost> . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) [2021-02-13 19:55:19,862: INFO/MainProcess] beat: Starting... [2021-02-13 19:55:34,883: INFO/MainProcess] Scheduler: Sending due task Hello World (<myapp>.tasks.hello_world) [2021-02-13 19:55:49,874: INFO/MainProcess] Scheduler: Sending due task Hello World (<myapp>.tasks.hello_world) [...] As soon as I add the flower argument, it breaks > celery flower -A pyauto beat -l INFO [I 210213 20:59:53 command:135] Visit me at http://localhost:5555 [I 210213 20:59:53 command:142] Broker: amqp://<user>:**@localhost:5672/<vhost> [I … -
When I ssh into my django ElasticBeanstalk server and try to enter the shell I get the error: The SECRET_KEY setting must not be empty
I have a ElasticBeanstalk server that is running my Django Rest Framework. The server is working properly when I make requests with Postman. However when I ssh into the server and try to enter the shell with ./manage shell_plus I receive the error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. On the server /opt/python/current/env contains export DJANGO_SETTINGS_MODULE="myproject.settings.production" myproject/settings/production.py contains from myproject.settings.base import * which contains the secret_key settings. And like I said my endpoints are working properly. I can't figure out why I am only having this issue with the server when I ssh and try to do any ./manage commands. -
I am getting error "" when trying to generate an ERD image for my database models in django
I have already set-up my database models and for the sake of visualizing my data's, I would like to generate a structure for it. I have installed the required packages which were successful. List of installed packages for generating the graph using the pip command: pydot pyparsing Graphviz django-extensions I was able to generate the dot file successfully by running the command python manage.py graph_models -a > erd.dot which worked successfully but whenever I used the command python manage.py graph_models -a -g -o erd.png in order to generate an image for it I get the FileNotFoundError: [WinError 2] "dot" not found in path error. -
Django how to change a vallue of a field that received error
Thanks for your time. Basically, what i'm trying to do is to set a object from a database list (.csv) and if i get an ValueError i would like to set that field value and keep adding data ValueError: Field 'age' expected a number but got 'M'. i'm quite shure that's a doc for this, but i've been reading for some time and hasn't found. -
How can I bring in a json file locally from my media folder in Django into my javascript for my html?
So this has been killing me for a few days now. I have a file 'logbook.json' that is set in my media folder right now. Eventually I will need to hook up a AWS bucket to store my user uploaded files into, but in the meantime I am keeping my simple files in the media folder, and having my Django app store the url of those files in the meantime. A user uploads a .json file (GeoJSON) to the site, I store it in my media file. When a user opens a page, the map will be rendered with what I have below. As you can see, I have a 'data' : 'file:../media/1logbook.json' as my source to load the .json from. The desire is to have the path link to a json file which is stored in my media. How can I make that connection? map.on('load', function () { map.addSource('flights', { 'type': 'geojson', 'data': 'file:../media/1logbook.json' }); map.addLayer({ 'id': 'flights', 'type': 'line', 'source': 'flights', 'layout': { 'line-join': 'round', 'line-cap': 'round' }, 'paint': { 'line-color': '#03d3fc', 'line-width': 4 } }); map.addLayer({ 'id': 'airport', 'type': 'circle', 'source': 'flights', 'paint': { 'circle-radius': 8, 'circle-color': '#3d75ad' }, 'filter': ['==', '$type', 'Point'] }); }); -
How to refresh cart span or cart div after add product to cart AJAX / Django?
The product is successfully added to the cart but the div containing the cart value is not up to date. You will have to refresh the page so that the div is up to date. I tried the load() and html() methods. How to refresh cart container when I add the product to the cart ? Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Form Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> HTML Span <ul class="navbar-nav ml-auto d-block d-md-none"> <li class="nav-item"> <a class="btn btn-link" href="#"><i class="bx bxs-cart icon-single"></i> <span class="badge badge-danger" id="cartval">{{ cart | length }}</span></a> </li> </ul> JS Code $(".form-order").on('submit', function(e){ e.preventDefault(); var product_id = $(this).attr('data-id') var quantity = $(this).find("#id_quantite").val() console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id+'/' $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, type: 'POST', dataType: 'json', data: data, success: function(data){ $("cartval").load(); $("#cartval").load("#cartval "); } }) … -
Using get_next_by_FOO and get_previous_by_FOO in django
I am building off of the question listed here: How can I use get_next_by_FOO() in django? I have altered the code for my project (see below), but when I click on "next" to hyperlink to the next object in my Picture model the same page only reloads. Can someone tell me what I am doing wrong? Models.py class Picture(models.Model): name = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='photo/') def __str__(self): return self.name def get_absolute_url(self): return reverse('picture-detail', kwargs={ 'pk': self.pk }) views.py class PictureDetailView(DetailView): model = Picture def picture_detail(request, id=None): instance = get_object_or_404(Picture, id=id) the_next = instance.get_next_by_date_posted() context = { 'name': instance.name, 'instance': instance, 'the_next': the_next, } return render(request, 'gallery/picture_detail.html', context) urls.py urlpatterns = [ path('', views.home, name='gallery-home'), path('picture/', PictureListView.as_view(), name='gallery-picture'), path('picture/<int:pk>/', PictureDetailView.as_view(), name='picture-detail'), ] picture_detail.html <a href="{{ the_next }}"> Next </a> -
Attach string to url in django
I am a beginner at python and especially Django, I am trying to solve a problem where i want to get var_X in my URL like: www.website.com/search/var_X or something like, www.website.com/search/<df.item> -Views.py- def views_search(request): temp_dict = {} if request.method == 'POST': var_X = request.POST['var_X'] try: df = wsc.Summary(temp_dict, ticker) except Exception as e: df = "ERROR" return render(request,'search.html', {'df' : df}) else: return render(request,'home.html', {'var_X' : "Not Found"}) -- Urls -- from django.urls import path from . import views from requests import * urlpatterns = [ path('search', views.views_search, name="url-search"), ] -
Django complex partitioning & ordering for tree Table
I'm using Django with PostgreSQL as my Backend-Stack for an application of which the main feature is a complex, multilevel table displaying annotated time-series-data for different products. So basically I've got 2 models defined, one is Product and the other one Timestamp, while the Product Model is hierarchial and uses the MPTT library for implementing the tree-structure. Each product can have multiple children, with 4 levels of depth as maximum and has multiple Timestamps, describing data for how they performed on a certain date. Thus I'm basically annotating all time-series data for each product in a queryset and that works flawlessly. The Problem which I'm facing is that I need to order the products dynamically by their annotated values, without destroying their position in the hierarchy and/or parent-child relationships. When I use some basic order_by("tree_id", "level" ...) like method, the parent-child relationships get 'overwritten'. Also Important is that every Product-root is has it's own tree_id and is a separate tree. models.py class Product(MPTTModel): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) budget = models.FloatField(null=True) creation_date = models.CharField(max_length=35, null=True) product_type = models.CharField(max_length=35, null=True) last_updated = models.DateTimeField(null=True) name = models.CharField(max_length=35, null=True) parent = parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) class Report(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, … -
How do I use Django's naturaltime package in a React frontend?
I would like to use the Django naturaltime functionality from the humanize package, or something similar, in my React frontend. Here is my current code: <p> <b> {user.username} {post.created_at} </b> </p> Here is what I'm currently getting: And here is what I'd like to get: I appreciate any help - thank you in advance! -
Testing django redirects
I am noticing while trying to test redirects on a page that requires login I get this this outcome : Response redirected to '/profiles/login/?redirect_to=%2Fprofiles%2F1%2F', expected '/profiles/login/'Expected '/profiles/login/?redirect_to=%2Fprofiles%2F1%2F' to equal '/profiles/login/'. This is the test that I wrote for it: class ProfileDetailView(TestCase): def setUp(self): self.client = Client() create_user() def test_profile_detail_for_redirect_if_no_authentication(self): user = User.objects.get(email="youcantseeme@example.com") profile_detail_response = self.client.get(f'/profiles/{user.id}/', follow=True) self.assertRedirects(profile_detail_response, '/profiles/login/', status_code=302, target_status_code=200) I'm using a login mixin for the generic details page class DetailView(LoginRequiredMixin, generic.DetailView): model = Profile template_name = 'profiles/detail.html' login_url = '/profiles/login' redirect_field_name = 'redirect_to' def get_queryset(self): """ TODO Determine criteria for filtering """ return Profile.objects I've been trying to find a way to check that the redirect was successful and went to the right page but the matcher for redirects doesn't seem right, any ideas? -
DJango: filtering multiple fields and levels
I have some tables like below: Person: - id Test: - person_id (related: test_person) - question_id Question: - id Answer: - question_id (related: answers) - person_id I would like to list all people and their answers, so I did: People.objects.prefetch_related( Prefetch("test_person", queryset=Test.objects .select_related("question") .prefetch_related(Prefetch("question__answers")))) But this queryset brings me the answer of all people. Is there any way to filter the answers by person_id? -
Search by ordered username in Django
I want to filter users by their username and order them by pertinence. The users with username matching perfectly the query should be first, then usernames starting with the query and finally usernames containing the query. Admitting I have users with the following usernames : "Phoenix123", "Phoenix", "i_m_phoenix", "phoenix123", "ImPhoenix" and "phoenix" If I want to search for users whose username contains "Phoenix", I want to have a quesyset of users whose username are in this order : "Phoenix", "phoenix", "Phoenix123", "phoenix123", "ImPhoenix", "i_m_phoenix" I've tried this : How to chain Django querysets preserving individual order user_perfect = Q(username__exact=username) # get Phoenix if exists user_perfect_to_lower = Q(username__iexact=username) # get phoenix if exists users_starting_perfect = Q(username__startswith=username) # get Phoenix123 if exists users_starting_lower = Q(username__istartswith=username) # get phoenix123 if exists users_containing_perfect = Q(username__contains=username) # get ImPhoenix if exists users_containing_lower = Q(username__icontains=username) # get im_phoenix if exists result = ( User.objects.filter( user_perfect | user_perfect_to_lower | users_starting_perfect | users_starting_lower | users_containing_perfect | users_containing_lower).annotate( search_type_ordering=Case( When(user_perfect, then=Value(6)), When(user_perfect_to_lower, then=Value(5)), When(users_starting_perfect, then=Value(4)), When(users_starting_lower, then=Value(3)), When(users_containing_perfect, then=Value(2)), When(users_containing_lower, then=Value(1)), default=Value(-1), output_field=IntegerField(), ) ).order_by('-search_type_ordering').distinct()[:10] ) But If I print the result, the search_type_ordering field is wrong for the users_starting_lower and users_containing_lower : <QuerySet [{'username': 'Phoenix', 'search_type_ordering': 6}, {'username': …