Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csrf validation failed when i login
hello every body i have a view in my django backend called getUserInfo that will will return user's info as json format this is my view: @api_view(["POST"]) def getUserInfo(request): if request.user.username: serial = userInfoSerializer(request.user) return Response(serial.data) else: return Response({"notLoggedIn": True}) when i'm not logged in ajax request works but when i login to a user account I get an error "forbidden" and it says csrf validation failed. also i refresh the csrf token every time that user logs in or out so it should work but it is not working this is my ajax request: function login(){ getcsrf(); $.ajax({ url: '/api/login/', type: 'POST', headers: { "XCSRF_TOKEN": csrf }, data: { username: $("#l-username").val(), password: $("#l-password").val(), }, }) .done(function(data) { console.log(data) if(data.msg){ console.log(data.msg) $(`<div class="p-2 bg-danger">`+data.msg+`</div>`).prependTo('#message-box') }else{ getcsrf(); getUserInfo(); } console.log("success"); }) .fail(function() { console.log("error"); }) .always(function() { console.log("complete"); }); } the function "getcsrf" refreshes the global variable containing the csrf-token value called "csrf" and then i send my ajax request. After request i refresh it again. i'm sure the value of csrf token changes every time that i refresh it when user logs in or out but server always says "forbidden" i have inserted this code in my settings.py file: CSRF_HEADER_NAME … -
MySQL Error -phpMyAdmin tried to connect to the MySQL server
Error MySQL said: Documentation 2006 - MySQL server has gone away phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server. -
How to read csv file in django?
I am making app which will process one csv file and return me response but I am getting no such file exist error when running server Is there any other way to give path my csv file. views.py from django.http import HttpResponse import pandas as pd def CountryCheck(request, country_name): country = country_name file = pd.read_csv('./country_list.csv') if country in file['country']: print('ok') FileNotFoundError: [Errno 2] File b'./country_list.csv' does not exist: b'./country_list.csv' file present in current directory of views.py -
Change how GET url is displayed
Summary: If I search 'apple', the url will be http://127.0.0.1:8000/search_results?csrfmiddlewaretoken=rlUwb5Ju3Xr585FarH5eAGQJtpog83hqW4wRysbsMWM6eiO3prcKRONY28N118gR&query=apple&button= and I just want to know if there is a way to change this to something cleaner like 127.0.0.1:8000/search_results/apple? Here is my code: urls.py path('search_results', views.search_results, name = 'search_results'), html: <form action="{% url 'search_results' %}" method="GET"> {% csrf_token %} <input name = 'query' type = 'text'/> <button type="submit" name="button">Search</button> </form> and views.py: def search_results(request): query =request.GET.get('query') return HttpResponse(query) I had tried to change these 3 lines in their respective files: `path('search_results/<str:query>')`, # thought this would achieve /search_results/apple url <form action="{% url 'search_results' 'query' %}" method="GET"> def search_results(request, query): but this did not work. Does anyone know how I can achieve this? -
Django Constraints - Case Insensitivity
I have defined a unique constraint below. I am wondering if there is a way to make the firstname and lastname fields case insensitive without having to write raw SQL? I have looked in the documentation and can't find anything on how to do this. class Meta: constraints = [ models.UniqueConstraint(fields= ['firstname','lastname','dateofbirth'],name="unique_person"), ] -
How to get a name from Tempfriend object (1) in django?
my tempfriends/models.py class Tempfriend(core_models.TimeStampedModel): name = models.CharField(max_length=30) belongs_to = models.ForeignKey( user_models.User, on_delete=models.CASCADE, related_name="belongs_to") as you see, tempfriends have a relation with usermodels. so when user make a moneybook, user can choose there companion(tempfriends), but there is a problem. form.companion print out : Tempfriend object (1) these are the code. moneybook_form.html <div class="input {% if field.errors %}has_error{% endif %}"> <div class="flex"> <div class="w-1/4"> {{form.companion.label}} </div> <div class="w-3/4 flex inline border-b my-2 py-3"> <div class="w-3/4"> {{form.companion}} </div> <div class= "w-1/4 flex justify-center "> <a href="{% url 'tempfriends:create' %}"><i class="fas fa-plus-circle"></i></a> </div> </div> </div> {% if form.companion.errors %} {% for error in form.companion.errors %} ><span class="text-red-700 font-medium text-sm">{{error}}</span> {% endfor %} {% endif %} </div> how can I print object name instead of Tempfriend object (1)? -
opening an excel file without storing it any location
I have these excel sheets which i am getting from the queryset in django rest framework.I converted that to list and want to process the excel file . Do i need to store it somewhere in my app before reading it or will storing it a variable and reading work fine . What is the best method to accomplish this ? What i tried doing is this but it does not seem to be working . excel_data =list(ExcelFiles.objects.all()) print("excel_data", excel_data) for item in excel_data: print("item id ", item.id) print("item.company is ", item.company) print("item again", item.plan_type) print("item.excel is ", item.excelFile) print("item.status is" ,item.status) if item.status == False: if hasattr(item,'excelFile'): print(item.excelFile) excel_sheet=item.excelFile wb = xlrd.open_workbook(excel_sheet) sheet = wb.sheet_by_index(0) print("sheet", sheet) I am using xlrd. -
Hide and show div and buttons based on id pattern
I'm working on a bunch of django forms that I would like to show one after the other once the former one has been submitted. I had a look at the question: jQuery - Function to display next element on page and hide the current one on click But I couldn't manage to have it work with what I have. :( I put an example below of the html generated. What I am trying to achieve: Start by only displaying div="question_2" and button id="submit_2". => DONE Once I click on button id="submit_2" I want all div and button whose id ends with the following number (ie 3 here) to be displayed. In the below example I want "question_3" and "submit_3" to be displayed (and the following time: "description_4", "question_4" and "submit_4"). I want to hide button id="submit_2" so that at each step there is only one submit button at the very end of the webpage. Ideally, I would like to hide the forms that have already been submitted. But I still want them to be displayed on the same page. This is a dummy introduction text. <div id="question_2" class="card" style="display: block;"> <h5 class="card-header">Question 1</h5> <div class="card-body"> <h6 class="card-title">The first question … -
Pyhton3 Django problem with stattic files and javaScript
in this html code <button id="play" onclick="playOrPauseSong()"><img style = "height:160%; width: 160%" src="{% static 'img/play.png' %}"/></button> when user click on button the funcution playOrPauseSong() will change the button image as in the js code function playOrPauseSong() { var $ = django.jQuery if (song.paused) { song.src = "song1.mp3"; song.play(); $("#play img").attr("src", 'stop.png'); } else { song.pause(); $("#play img").attr("src", 'play.png'); } } but the button not changes img correctly in Django what is the problem -
Showing results in dialogue box upon button click
So I have a site where I want to add the functionality of showing output upon click. The user selects vendor and time duration, and currently the results are showed below the Submit button. I want to instead show the results in a dialogue box instead. Below is the html: {% extends "base.html" %} {% load bootstrap4 %} {% block content %} <div class="container" style="margin: auto; text-align: center;"> <br> <h1 style="background-color: #ede8e8;border-radius: 10px; opacity: 0.95;" > WELCOME TO YOUR PAGE, ADMIN!</h1> <br> <div style="margin: auto; text-align: center;background-color: #ede8e8;border-radius: 10px;opacity: 0.95;"> <h2>Check the boxes below to display records!</h2> <form method="POST" action="/profiles/adminKaLogin/"> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInline1" name="inlineDefaultRadiosExample" value="1"> <label class="custom-control-label" for="defaultInline1">Vendor 1</label> </div> <!-- Default inline 2--> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInline2" name="inlineDefaultRadiosExample" value="2"> <label class="custom-control-label" for="defaultInline2">Vendor 2</label> </div> <br> <h3> Select time period</h3> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInlines1" name="inlineDefaultRadiosExample1" value="1"> <label class="custom-control-label" for="defaultInlines1">1 Month</label> </div> <!-- Default inline 2--> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInlines2" name="inlineDefaultRadiosExample1" value="2"> <label class="custom-control-label" for="defaultInlines2">2 Months</label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" class="custom-control-input" id="defaultInlines3" name="inlineDefaultRadiosExample1" value="6"> <label class="custom-control-label" for="defaultInlines3">6 Months</label> </div> <br> <button type="submit" class="btn btn-primary" name="form1">Submit</button> {% if model %} <table> <thead> … -
How to customize filtering with Filter.method of django-filter
I'm building a website with Django and I'm using the app django-filter to build a filtering system for the products of my website. Basically, all the users of my website have a localisation attribute that represents their current location (this attribute is a PointField from GeoDjango). I would like the user to be able to filter products sold by users located near its location. To do that, I'm using the method argument of django_filters to customize the filtering. I think what I want is rather simple to do but I'm in trouble implementing it due to the lack of explicit examples on the documentation of django-filter. You can find below what I have tried so far, with the models used so you can understand what I did. The relationship structure between the models is a bit complicated but I don't think you need it to understand my question. Here is the complete explanation of the structure in case it's useful: the User model is linked to a UserAdvanced model providing advanced features for the user. This UserAdvanced model is optionnaly linked to a Chef model that represents the users that can sold products. Finally, the Chef model can be linked … -
Can't get a simply Django app to build on Docker (Must have Postgres + Mysql support)
Dockerfile: # pull official base image FROM alpine:edge RUN apk update && apk add build-base libzmq musl-dev python3 python3-dev zeromq-dev \ mariadb-dev postgresql-dev RUN pip3 install pyzmq # set work directory WORKDIR /usr/src/myproj COPY ./requirements.txt ./requirements.txt # install dependencies RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt COPY . /usr/src/myproj # reduce image size by cleaning up the build packages RUN apk del build-base musl-dev python3-dev zeromq-dev EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] My requirements.txt alive-progress==1.3.0 amqp==2.5.1 appnope==0.1.0 APScheduler==3.5.3 argh==0.26.2 astroid==2.2.4 attrs==19.1.0 awsebcli==3.14.4 Babel==2.6.0 backcall==0.1.0 billiard==3.6.1.0 bleach==3.1.0 blessed==1.15.0 botocore==1.10.84 bugsnag==3.6.0 cached-property==1.4.3 celery==4.3.0 cement==2.8.2 certifi==2018.8.24 chardet==3.0.4 colorama==0.3.9 decorator==4.3.2 defusedxml==0.5.0 dj-database-url==0.5.0 Django==2.2.4 django-cors-headers==3.0.2 django-enum-choices==2.1.1 django-enumchoicefield==2.0.0 django-extensions==2.2.1 django-redis==4.10.0 djangorestframework==3.9.4 dnspython==1.16.0 docker==3.5.0 docker-compose==1.21.2 docker-pycreds==0.3.0 dockerpty==0.4.1 docopt==0.6.2 docutils==0.14 entrypoints==0.3 flower==0.9.2 gunicorn==19.9.0 html2text==2019.9.26 idna==2.6 importlib-metadata==0.19 importlib-resources==1.0.2 ipykernel==5.1.0 ipython==7.3.0 ipython-genutils==0.2.0 ipywidgets==7.4.2 isodate==0.6.0 isort==4.3.10 jedi==0.13.3 Jinja2==2.10 jmespath==0.9.3 jsonfield==2.0.2 jsonschema==2.6.0 jupyter==1.0.0 jupyter-client==5.2.4 jupyter-console==6.0.0 jupyter-core==4.4.0 jwplatform==1.2.2 kombu==4.6.4 lazy-object-proxy==1.3.1 MarkupSafe==1.1.1 mccabe==0.6.1 mistune==0.8.4 more-itertools==7.2.0 mysql-connector==2.2.9 mysqlclient==1.4.6 nbconvert==5.4.1 nbformat==4.4.0 notebook==5.7.5 numpy==1.17.4 pandocfilters==1.4.2 parso==0.3.4 pathspec==0.5.5 pathtools==0.1.2 pexpect==4.6.0 pi==0.1.2 pickleshare==0.7.5 powerline-status==2.7 prometheus-client==0.6.0 prompt-toolkit==2.0.9 protobuf==3.6.1 psycopg2==2.7.5 psycopg2-binary==2.7.5 ptyprocess==0.6.0 Pygments==2.3.1 pylint==2.3.1 PyMySQL==0.9.3 pyrsistent==0.14.11 python-dateutil==2.7.3 python-slugify==3.0.3 pytz==2018.5 PyYAML==3.13 pyzmq==18.0.1 qtconsole==4.4.3 redis==3.3.8 requests==2.18.4 requests-toolbelt==0.9.1 semantic-version==2.5.0 Send2Trash==1.5.0 six==1.11.0 sqlparse==0.3.0 tabulate==0.7.5 termcolor==1.1.0 terminado==0.8.1 testpath==0.4.2 text-unidecode==1.2 texttable==0.9.1 timezonefinder==4.1.0 tornado==5.1 traitlets==4.3.2 typed-ast==1.3.1 tzlocal==1.5.1 Unidecode==1.1.1 urllib3==1.22 uWSGI==2.0.17.1 validators==0.14.0 vine==1.3.0 watchdog==0.9.0 wcwidth==0.1.7 … -
Deploy Django application with apache for using subdomain
I have apache setting like this. example.com -> /var/www/html/myhomepage/ now I want to add the subdomain for my django application named djangoapp I want to do like this below. djangoapp.example.com -> /var/www/html/djangoapp/current/ (current is made by capistrano so, djangoapp is deployed under current folder) So, I set up httpd.conf as below, but it's shows import error. Moreover I think it's a bit redundant. How is the best practice for apache 2.2, django 3 and wsgi using subdomain? <VirtualHost *:80> DocumentRoot "/var/www/html/djangoapp/current/" ServerName djangoapp.exmaple.com <Directory /var/www/html/djangoapp/current/> Order allow,deny Allow from all </Directory> ErrorLog "logs/djangoapp.exmaple.com-error_log" CustomLog "logs/djangoapp.exmaple.com-access_log" common </VirtualHost> LoadModule wsgi_module /home/app/anaconda3/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so WSGIScriptAlias /djangoapp /var/www/html/djangoapp/current/djangoapp/wsgi.py WSGIPythonHome /home/app/anaconda3/ WSGIPythonPath /var/www/html/djangoapp/current <Directory /var/www/html/djangoapp/current> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> Alias /static/ /var/www/html/djangoapp/current/static/ <Directory /var/www/html/djangoapp/current/static> Order allow,deny Allow from all </Directory> -
Using get method and get_context_data in detailview django
In views.py I have a view PageDetailView: class PageDetailView(DetailView): model = Page def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['photos'] = Photo.objects.all() return context def get(self, request,*args, **kwargs): return render(self.request, 'page/page_detail.html', context=context) def post(self, request, *args, **kwargs): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) So Here I am having the error that name 'context' is not defined. So what can I do? I want to access those contexts in my template. Any help will be much appreciated. Note: I just can't simply define those contexts inside get method because I have some other complicated context that is so easy accessing with get_context_data method. -
redirection fails when called after deleting application cookies from the browser
In my django application, HttpResponseRedirection failing When i do it for the first time it passes and redirects. if request.user.is_anonymous: request.session.flush() print(request.get_host()) sso_auth_url = 'https://' + request.get_host().split(',')[0] + reverse('dcmsisso:auth') windows_auth_url = os.path.join(API_BASE_URL, 'api', API_VERSION, 'windows/auth') redirect_url = windows_auth_url + '?redirecturl=' + sso_auth_url + '?next=' + next_url return HttpResponseRedirect(redirect_url) when i am in some page, and delete all the session cookies, there try to reload the page it enters this block and does not call the next function. But if i left click on the failed url and open it in new page, then it redirects to the home page. I have been trying to resolve this error from 3 days. can any one suggest. I can give more info, i dont know what is missing. -
How to dynamically inject values to forms in templates?
I'm trying to build a comment system in Django similar to one on Reddit, where users can reply to other comments. For every comment, I create a separate reply form: {% for comment in comments.all %} {# Displaying the coment here #} <form action="." method="POST"> {% csrf_token %} {{ comment_form.as_p }} <p><input type="submit" value="Comment"></p> </form> {% endfor %} How would I go about injecting a corresponding comment's ID into each form? Is there maybe a way to specify initial values on a template level? -
How to integrate django-private-chat in django project?
I am working on an application where I want to implement the django-private-chat in for one to one messaging feature after I did everything which is said in the documentation I ran the server and got to the link http://127.0.0.1:8000/dialogs/ I am getting this error please help me out I have included the error traceback also In this link I had included this code also please help me Getting an error when integrated django-private-chat in the django project? -
GET Body is not being sent with APIClient DRF
i want to send body data using get request in the django drf test case APITestCase for example data ={'hi':'bye'} self.client.get('media_list/', {'body': data}) and in the views i can able get the body using below code request.data.get('hi', None) but it is not working using {'body': data} my test method but it is working fine in the postman raw type -
How to display the children of a wagtail page
My requirement sounds simple, but I am struggling to make it work In my wagtail project I have a BlogListingPage which has many child pages. I am trying to create a list of the children in a web page. Here is my code: models.py class BlogListingPage(Page): ... def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context['blog_pages'] = BlogDetailPage.objects.live().child_of(self) return context class BlogDetailPage(Page): ... blog_listing = models.ForeignKey(BlogListingPage, on_delete=models.PROTECT, blank=True, null=True,) views.py def blog(request): url = 'blog/blog_listing_page.html' context = {'data': BlogListingPage.objects.all()} return render(request, url, context) blog_listing_page.html {% block content %} {% for blog_listing in data %} {% for post in blog_listing.blogdetailpage %} <a href="{% pageurl post %}">{{ post.blog_title }}</a> {% endfor %} {% endfor %} {% endblock content %} I am lost in the fog of the django/wagtail pages/objects/querysets/all()/specific Can someone please lead me to clear blue water? -
Nginx config problem when passing from http to https
I am creating a web app for a non profit org in my town. The app is composed of a backend with django-rest-framework, a frontend in vuejs and a reverse-proxy that serve the static files and medias: nginx. I wanted to test the app in a test env close to the prod env I will use. I had some difficulties passing from http to https on my test environement but I managed it thanks to this article: ssl on nginx with docker Now I have another problem I can't explain: each time I try to reach my backend, it seems that the requests take so much time that I get a 504 Gateway Timeout. I noticed at the start that the gunicorn worker got killed for each one of my request but I added a 120sec timeout to prevent this. I think that the problem is in my nginx config. I'm not familiar enough with it to find a proper solution to my problem so I am requesting your help (hoping it won't be another 504 LOL) Here is my nginx.conf: user nginx; worker_processes 1; events { worker_connections 1024; } http { include /etc/nginx/mime.types; client_max_body_size 100m; upstream backend { server … -
How to just limit the displaying of new message box in Django channels
I am trying to make a real-time message notification.The scenario I am having is user sends a message to user2 he gets a notification that you have a message from user2.In that inbox there are the recent 3 messages. I wanna make it like that the inbox messages should be limited to those 3 boxes.If he gets a new message.No box should be created instead the recent message box should be rewritten with that information.If he gets 3 new messages from 3 different users.Those 3 recent message box should be updated with those messages instead of creating new boxes.Think about it like a Facebook messaging hovered inbox.I hope that makes sense. -
How to handle Foriegnkey in the ModelForm and `Generic createiVew` in Django
I have always used normal Django views for years, it is my first time trying to use Django Generic Views and is facing this weird problem, For some reason, all fields work great, but the ForiegnKey field is not even showing, here is my code : models.py class Category(models.Model): # Fields name = models.CharField(max_length=500) class Meta: pass def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("Point_of_sale_Category_detail", args=(self.pk,)) def get_update_url(self): return reverse("Point_of_sale_Category_update", args=(self.pk,)) class Product(models.Model): # Relationships category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='product_category') # Fields name = models.CharField(max_length=500) sell_price = models.DecimalField(max_digits=8, decimal_places=4) class Meta: pass def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("Point_of_sale_Product_detail", args=(self.pk,)) def get_update_url(self): return reverse("Point_of_sale_Product_update", args=(self.pk,)) And my forms.py : class ProductForm(forms.ModelForm): class Meta: model = models.Product fields = [ "name", "sell_price", "category", ] my views.py class ProductCreateView(generic.CreateView): model = models.Product form_class = forms.ProductForm And finally here is I use it in my HTML : <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit"> </form> Fields are shown normally but not the Category Field -
Reverse for 'create' not found. 'create' is not a valid view function or pattern name
I want to create a tempfriends during creating Moneybook. So i write a code in a create moneybook template but error occur : NoReverseMatch at /moneybooks/create/ Reverse for 'create' not found. 'create' is not a valid view function or pattern name. I write a proper appname, write a urls.py, use single quote...ete but don't know how to achieve it. moneybook_form.html <div class="input {% if field.errors %}has_error{% endif %}"> <div class="flex"> <div class="w-1/4"> {{form.companion.label}} </div> <div class="w-3/4 flex inline border-b my-2 py-3"> <div class="w-3/4"> {{form.companion}} </div> <div class= "w-1/4 flex justify-center "> <a href="{% url 'tempfriends:create' %}"><i class="fas fa-plus-circle"></i></a> #this part error occured </div> </div> </div> {% if form.companion.errors %} {% for error in form.companion.errors %} ><span class="text-red-700 font-medium text-sm">{{error}}</span> {% endfor %} {% endif %} </div> config/urls.py urlpatterns = [ path("", include("cores.urls", namespace="cores")), path('admin/', admin.site.urls), path("users/", include("users.urls", namespace="users")), path("tempfriends/", include("tempfriends.urls", namespace="tempfriends")), path("moneybooks/", include("moneybooks.urls", namespace="moneybooks")), path("moneylogs/", include("moneylogs.urls", namespace="moneylogs")) ] moneybooks/urls.py app_name = "moneybooks" urlpatterns = [ path("create/", views.moneybook_create.as_view(), name="create"), path("update/<int:pk>/", views.moneybook_update.as_view(), name="update"), path("<int:pk>/", views.moneybook_detail, name="detail") ] tempfriends/urls.py from django.urls import path from . import views app_name = "tempfriends" urlpatterns = [ path("create/", views.tempfriend_create.as_view(), name="create"), ] tempfriends/views.py class tempfriend_create(FormView): form_class = forms.CreateTempfriendForm template_name = "tempfriends/create.html" def get_current_user(request): current_user = request.user def form_valid(self, … -
django How to use subtration in views.py
I just want to subtract the total SchoolFeesMasterList(Amount) to StudentsEnrollmentRecord ESC(amount) this is my code in views.py studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=1) total_paid = list(SchoolFeesMasterList.objects.aggregate(Sum('Amount')).values()) or 0 discount = studentenroll.ESC.amount - total_paid this is my models.py class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE,blank=True) Display_Sequence = models.IntegerField(blank=True, null=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, related_name='+', on_delete=models.CASCADE,blank=True) Amount = models.FloatField() Amount_Per_Unit = models.FloatField() Effectivity_Date_From = models.DateField(null=True,blank=True) Effectivity_Date_To = models.DateField(null=True,blank=True) Remark = models.TextField(max_length=500,blank=True) class esc(models.Model): Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Description = models.CharField(max_length=500, null=True,blank=True) amount = models.FloatField() class Meta: verbose_name_plural = "Grade Level With/without ESC" class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) strands = models.ForeignKey(strand, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True) Remarks = models.TextField(max_length=500,null=True,blank=True) -
Django_filters : how to customize the search fields with a function?
I'm using the app django_filters to enable the users of my website to filter the products available according to their needs. It works well for simple filtering like "attribute greater than ...", "attribute contains ..." but now I need a more complex filtering and so I need to define a custom search field. More specifically, the products of the website are sold by some user and bought by some other user. Each user has a location (corresponding to a PointField attribute using GeoDjango) and I need the user to be able to filter the products that are closer than a certain distance with respect to its location. So, instead of filtering on a specific attribute, I want to filter on the value returned by a distance function. Currently, my filters file looks like this : class PlatFilter(django_filters.FilterSet): titre = django_filters.CharFilter( field_name='titre', label='Mot clé :', lookup_expr='icontains', widget=forms.TextInput(attrs={'class': 'form-control'}), ) date_prep = django_filters.DateFilter( field_name='date_prep__date', label='Date de préparation (format JJ/MM/AAAA)', lookup_expr='exact', widget=forms.DateTimeInput(attrs={'class': 'form-control'}), ) SOME OTHER FILTERS class Meta: model = Plat fields = ['titre', 'nb_portions', 'date_prep'] And I would like to define a filter of that kind : distance = django_filters.NumberFilter( field_search=distance(location1, this.location) label='...', lookup_expr='lte', widget=..., ) I'm a bit lost about …