Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Another version of Voting
Just experimenting with homework. How to make polls like and dislike under every post automatically? Problem is - if I do it this way, I have to add it manually from admin under every single post and its highly inconvenient. Here is the code example and thank you for any comment my models.py class BugTable(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_posted = models.DateTimeField(default=timezone.now) bug_name = models.CharField(max_length=50, blank=False) bug_description = models.TextField() bug_solution = models.TextField(blank=True) fixing_in_process = models.BooleanField(blank=True, default=False) bug_fixed = models.BooleanField(blank=True, default=False) def __str__(self): return self.bug_name class Vote(models.Model): vote_text = models.CharField(max_length=10) vote = models.IntegerField(default=0) bug = models.ForeignKey(BugTable, on_delete=models.CASCADE, related_name='choice_set') def __str__(self): return self.vote_text views.py def detail(request, bug_id): bug = get_object_or_404(BugTable, pk=bug_id) return render(request, 'detail.html', {'bug': bug}) def vote(request, bug_id): bug = get_object_or_404(BugTable, pk=bug_id) try: selected_vote = bug.choice_set.get(pk=request.POST['choice']) except (KeyError, Vote.DoesNotExist): return render(request, 'detail.html', { 'bug': bug, }) else: selected_vote.vote += 1 selected_vote.save() return HttpResponseRedirect(reverse('results', args=(bug.id,))) def results(request, bug_id): bug = get_object_or_404(BugTable, pk=bug_id) return render(request, 'results.html', {'bug': bug}) detail.html: <form action="{% url 'vote' bug.id %}" method="post"> {% csrf_token %} {% for choice in bug.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.vote_text }} </label><br/> {% endfor %} <input type="submit" value="Vote" /> … -
How to called OneToOneFields without generating a pylint no-menber (E1101 )
I am working with django and, I am in trouble to called a OneToOneFields without generation a pylint. here is my code class A(models.Model): attr_1 = models.BooleanField(default=False) class B(models.Model): a = models.OneToOneField(A, models.CASCADE, null=False) other_attr = models.BooleanField(default=False) my_object = A.objects.first() print(my_object.b.other_attr) When I run my pylint, it generates a E1101 (no-member) on this line. As I do not want to make another called to the DB, I do not want to write something like this my_b_object = B.objects.get(a=my_object) Does someone as an idea on how to solve that? PS: the goal is to no put neither a # pylint: disable=E1101 at the end on my line :-) thanks by advance!!! -
Taking the time of a question made in django
I created a quiz in django, now create take the time the user took to answer an issue. Is it possible to calculate the time that the user entered one page until redirecting to another? -
Crispy Forms styling not showing up
Hi everyone I am trying to redesign a registration form using cripsy forms, however, I can't seem to get it to take. Here is my register.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Join the Club</legend> {{ form|crispy }} </fieldset> <div class="form-group"><button class="btn btn-outline-info" type="submit"> Join the Club!</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted">Already have an account? <a class="ml-2" href="#">Submit </a> </small> </div> </div> {% endblock content%} Here are my settings in the project folder INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... CRIPSY_TEMPLATE_PACK = 'bootstrap4' Here is my forms.py in the users folder from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=75) class Meta: model = User fields = ['first_name','last_name', 'email','username','password1','password2'] Here is my terminal NY-WM-3:dprsg jennifer.s$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). May 06, 2019 - 14:04:00 Django version 2.1.2, using settings 'dprsg.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [06/May/2019 14:04:08] "GET /register/ HTTP/1.1" 200 7108 I don't really … -
Is there a way to use 'and' in a django template to check 2 variables?
I am trying to check if two variables are equal to none and if so, display something, but I am not sure how to use an and in the template and check if both variables are None. HTML: {% if post.company_title and post.company_image %} <img class="company_image" src="{{ post.company_image.url }}" alt="{{ post.company.url }}"> {% elif post.company_title == "" %} <img class="company_image" src="{{ post.company_image.url }}" alt="{{ post.company.url }}"> {% elif post.company_image == "" %} <p>{{ post.company_title }}</p> {% elif not post.company_title and not post.company_image %} <!-- This does not work when both fields are false aside from that --> <!-- It all works --> <p>nooo</p> {% endif %} The first if checks if both have a value. The first else if checks if one doesn't have a value The second else if checks if one doesn't have a value The last else if should check if they both do not have values. If anyone knows how to check to variables if they are equal to none that would be great. -
My create view is neither saving the object nor redirecting to the next page?
I made a create view that should be able to save an object and then redirect bit form some reasons the form is not valid and it's not saving the object. If anybody knows the answer then please write the whole answer with code. My create view class Submit_Property(generic.CreateView): model = models.Property form_class = forms.Property_Form template_name = 'profile_details/submit-property.html' Here's the model for This class Property(models.Model): title = models.CharField(max_length = 210,default = 'None') STATUS_CHOICES = ( ('RENT','Rent'), ('SALE','Sale'), ) status = models.CharField(max_length = 210,choices = STATUS_CHOICES,default = 'Rent') price = models.IntegerField() area = models.CharField(max_length = 210,default = 'None') ROOM_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('MORE','More'), ) rooms = models.CharField(max_length = 210,choices = ROOM_CHOICES,default = '1') BATHROOM_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ) bathroom = models.CharField(max_length = 210,choices = BATHROOM_CHOICES,default = '2') address = models.CharField(max_length = 210,default = 'None') state = models.CharField(max_length = 210,default = 'None') code = models.CharField(max_length = 210,default = 'None') images = models.ImageField(upload_to = 'images',) info = models.TextField(max_length = 1000,default = 'None') parking = models.BooleanField(default = False,verbose_name = 'Parking') air = models.BooleanField(default = False) swimming = models.BooleanField(default = False) laundry = models.BooleanField(default = False) dealer_name = models.CharField(max_length = 210,default = 'None') dealer_email = models.EmailField(max_length = 210,default = … -
hide fields of model in Django
I want to hide some fields from my model, how can I do it? something like : class YourForm(forms.ModelForm): class Meta: model = YourModel exclude = ('check_out_time', ) this is my code: class MyModel(models.Model): class Meta: db_table = 'table' verbose_name_plural = "table1" name = models.CharField(max_length=255, null=False, blank=False, unique=True) description = models.TextField(null=True, blank=True) year = models.IntegerField(null=False, blank=False, choices=get_list()) how can I hide field 'year'? -
Django: register two models on admin.py
I tried this but it throws error. from django.contrib import admin from .models import Costs, Repository class CostsAdmin(admin.ModelAdmin): list_display = ('cost_title', 'amount', 'product', 'time',) list_per_page = 25 class RepositoryAdmin(admin.ModelAdmin): list_display = ('__str__', 'batch_no', 'time',) list_per_page = 25 admin.site.register(Costs, CostsAdmin) admin.site.register(Repository, RepositoryAdmin) It worked but can't pass the classes: admin.register(Costs, Repository)(admin.ModelAdmin) -
Try add to cart without refresh page Django/Ajax (Internal Server Error)
I have this error cart/create/?product_id=1 500 (Internal Server Error) I don't understand why:) I'm trying to use Ajax first. Try add product in the cart without refreshing page. Add product from this link <a href="#" data-id="{{ product.id }}" class="add_to_cart"><button>Add product</button></a> my url url(r'^cart/create/$', views.cart_create, name='cart_create'), my view def cart_create(request): cart = Cart(request) product_id = request.GET.get('product_id') product = Product.objects.get(id=product_id) cart.add(product=product) return JsonResponse('') js <script type="text/javascript"> $(document).ready(function(){ $('.add_to_cart').on('click', function(){ product_id = $(this).attr('data-id') data = { product_id: product_id } $.ajax({ type: 'GET', url: '{% url "cart:cart_create" %}', data: data, success: function(data){ console.log('success') } }) }) }); </script> This base.html file, here I try output my count in the cart, and this works but only with refreshing <header> {% with total_items=cart|length %} {% if cart|length > 0 %} Our cart: <a href="{% url 'cart:cart_show' %}" id="cart_count"> {{ total_items }} products {{ cart.get_total_price }} &#8381; </a> {% else %} <a href="{% url 'cart:cart_show' %}">Cart is empty</a> {% endif %} {% endwith %} <h1><a href="{% url 'shop:product_list' %}">Main</a ></h1> </header> Why I'm doing wrong guys? -
Django error on localhost, not reconizing f"Lote: {self.title}"
File "/home/lucas/Documents/back/user/models.py", line 6, in from coupon.models import Coupon File "/home/lucas/Documents/back/coupon/models.py", line 26 return f"Lote: {self.title}" ^ SyntaxError: invalid syntax I got this error running python manage.py of my Django Application. The same code works fine on the server machine. Is there something missing to run it local? I installed all dependencies and requirements. I try to search for what may cause this error but none of what I found worked. python -version: Python 3.5.2 python-dev installed pip installed build-essential installed python3 installed System: Distributor ID: Ubuntu Description: Ubuntu 16.04.6 LTS Release: 16.04 Codename: xenial Looking for any help to solve this. -
Django: Local Variable Referenced Before Assignment in Contact Form
I have a website contact form which autofills a blank PDF file using a Django views.py file. I am attempting to fill the blank inputs using Adobe Acrobat; however, Django is not allowing me to reference the variables in data_dict which I define in my def quote_req(request) function. I am successful with this code when using generic strings, so my issue is purely referencing the vars. I have used global declaration within each of the functions, but did not have any success. I am not sure if I am placing the declaration in the right spot, for I will receive the same error or it will say the variable is not defined. def quote_req(request): submitted = False if request.method == 'POST': form = QuoteForm(request.POST, request.FILES) company = request.POST['company'] contact_person = request.POST['contact_person'] if form.is_valid(): form.save() # assert false else: form = QuoteForm() if 'submitted' in request.GET: submitted = True My function that fills out the PDF using PDFRW. def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) annotations = template_pdf.pages[0][ANNOT_KEY] for annotation in annotations: if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY: if annotation[ANNOT_FIELD_KEY]: key = annotation[ANNOT_FIELD_KEY][1:-1] if key in data_dict.keys(): annotation.update( pdfrw.PdfDict(V='{}'.format(data_dict[key])) ) pdfrw.PdfWriter().write(output_pdf_path, template_pdf) My function that references the input cells on the PDF … -
Django - Select many instances/objects from a list and store them in a sessions to pay
i have built a simple ecommerce website where you can put many single items (one by one) in a session and then you can pay them. My plan is that i can select/choose many instances/objects from a listview at one time and display them all at once in a session (cart). I just want to kindly ask you how i can start that, not with code examples. How has to look the view ( it has to be an ajax view) ? no experience in ajax Are there any kind of django packes for that problem? I need to serialize my data for that ? I would love that you guys put my research in right direction, then I would try myself out to solve the problem. -
How to catch in jQuery Django ModelForm submission Save, Save and add new, Save and continue
I tried to override a Model Form submission in Django Admin. I basically needed to display a confirmation window (with some infos extracted from the db) and if Yes is clicked, then continue saving. It works. The javascript code looks like: django.jQuery(document).ready(function() { $('#assembly_form').on('submit', function(event) { event.preventDefault(); // Ajax get data from db // ... Confirm('Attention', msg, 'Yes', 'Cancel'); $('.doAction').click(function() { $(this).parents('.dialog-ovelay').fadeOut(500, function() { $(this).remove(); }); document.forms['assembly_form'].submit(); }); $('.cancelAction, .fa-close').click(function() { $(this).parents('.dialog-ovelay').fadeOut(500, function() { $(this).remove(); }); }); }); However, it does not work as expected. In Django Model Admin forms, there are three submit inputs: <input type="submit" value="Save" class="default" name="_save"> <input type="submit" value="Save and add new" name="_addanother"> <input type="submit" value="Save and continue modifications" name="_continue"> Le statements document.forms['assembly_form'].submit() triggers the default submission "Save". If Save & Continue or Save & Add New is clicked, I've no clue how to get this info in the ('#assembly_form').on('submit') . Any idea is welcome. Z. -
Django Creating Dynamic Form, with queryset's values as field
Let say I have a queryset with 3 records. What i want to create a form using this queryset and use the value of a field(say name field of model) as the field name of form. And there must be as many fields are many there are records in that queryset. Please HELP! -
How to make sure users only get to DetailView, Listview and UpdateView their own created objects (Django)
I've created a simple app where logged in users can can submit a session for a conference, view the results of their submission, view a list of their submissions, and edit their submissions (they should not have access to other users' submissions). I'm using django's class-based views (CreateView, DetailView, ListView, UpdateView). I'm struggling with the permissions however. All the views, except updateview, work but if I type in the url directly using a non-logged in username I can see their submissions. I also suspect that the permissions is the same reason I can't get the updateview to work. What am I missing? And is there a better way to avoid using usernames and slugs in the Url? I can't seem to find any examples or tips in how to do this type of thing. I'm a beginner so probably miss some understanding of the fundamentals here and there. I've tried to understand how the User model works because there I did manage to find a way to create, view and edit user details in a protected way. I relied on function views there though and can't seem to apply that approach to the submission app. models.py class Hsession(models.Model): submitter = … -
Use model property as a normal field in queryset filter
I want to use a property as a normal model field in a filter to reduce code duplication. What I want to get: class SomeModel(models.Model): # ... @property def is_active(self): # some query e.g.: return self.some_related.filter(some_complex_query).exists() SomeModel.objects.filter(is_active=True) Is it possible? I know that I can override manager and do it in a next way: SomeModel.objects.filter_active(True). But it is not so nice as the first example. -
Fetch Django models in list view to show both
I have this models: Article: class Article(models.Model): sku = models.CharField( max_length=5, primary_key=True, validators=[MinLengthValidator(5)] ) ean = models.CharField( max_length=13, unique=True, validators=[MinLengthValidator(13)] ) parent = models.ForeignKey( 'Article', related_name='children', null=True, blank=True, on_delete=models.PROTECT ) ... and ArticleTranslations: class ArticleTranslation(models.Model): LANGUAGE_CHOICES = ( (settings.ENGLISH, _("english")), (settings.FRENCH, _("french")), (settings.GERMAN, _("german")), (settings.ITALIAN, _("italian")), (settings.PORTUGUESE, _("portuguese")), (settings.SPANISH, _("spanish")), ) article = models.ForeignKey( 'Article', on_delete=models.CASCADE, related_name='translations', ) I need to return both, combined to show the 2 items in a Django Templates HTML for. Need to have the item and the foreign key and see it in the same iterations. I wanna do it with the methods of the class List View and django, and not doing something bad. I have this ListView: def get_queryset(self): queryset = (Article.objects .all() .prefetch_related('translations') .order_by('-sku')) print(queryset) return queryset And in my HTML, need to show the foreign key values: {% extends "base.html" %} {% block content %} {% for article in article_list %} <div class="container"> <h2>{{ article.translations.NEED_TO_SHOW_THAT_PARAMETER }}</h2> </div> {% endfor %} {% endblock content %} -
Voting in Django not displaying votes
Need a help with Django voting problem. Probably most of have done it as a beginner. For some reasons it does not want to display the number of votes. Idea is to have a like button and a number of likes each post got. After pressing vote page does refresh, but likes are not displayed nor changes on admin page. I assume it is a problem with this choice_set thing. My models.py: class BugTable(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_posted = models.DateTimeField(default=timezone.now) bug_name = models.CharField(max_length=50, blank=False) vote = models.IntegerField(default=0) def __str__(self): return self.bug_name views.py: def vote(request, bug_id): bug = get_object_or_404(BugTable, pk=bug_id) try: selected_vote = bug.choice_set.get(pk=request.POST['choice']) except (KeyError, BugTable.DoesNotExist): return render(request, 'detail.html', { 'bug': bug, }) else: selected_vote.vote += 1 selected_vote.save() return HttpResponseRedirect(reverse('results', args=(bug.id,))) def results(request, bug_id): bug = get_object_or_404(BugTable, pk=bug_id) return render(request, 'results.html', {'bug': bug}) my detail.html <form> {% csrf_token %} {% for choice in bug.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}"></label><br/> {% endfor %} <input type="submit" value="Vote" /> </form> my results.html {% for choice in bug.choice_set.all %} {{ choice.vote }} vote{{ choice.vote }} {% endfor %} Thanks a lot for your help! -
Error: TemplateDoesNotExist at / blog/home.html "GET / HTTP/1.1" 500
I'm going through a Youtube tutorial of someone showing how to create an online blog (to be more specific, his names Corey Schafer, if that helps in any way). I've written everything just as he has done, but I'm still getting a TemplateDoesNotExist / blog/home.html every time I run my terminal and pull up the link. I was looking through the comments and someone said: "Hey, great Tutorial but you didn't tell to add directory i.e. blog/template into the template section of settings.py file, without this, the browser is showing an error that your template doesn't exist." If he's right, I'm not sure where I would put that code specifically in the Templates sections under setting.py (I've added this code below). If he's not right, does anyone know why I am getting this error? Please let me know if you need to see more code. I tried to put everything in here that's relevant. My Views.py File: from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'blog/home.html') def about(request): return HttpResponse('<h1>Blog About</h1') I have a fold named templates, then in that folder is another fold named blog with two files in that: about.html and home.html with the … -
Django: Use 2nd argument given by url
I want to make a Django website where I can upload series with seasons and episodes. In the end it should look something like this: Seasons: [1] [2] [3] Episodes: [1] [2] [3] [4] [5] [6] The Episodes belong to the season given by the url. My code looks like this: models.py: class Serie(models.Model): title = models.CharField(max_length=120) thumbnail = models.ImageField(upload_to=serie_dir_path) ... class Season(models.Model): order = models.IntegerField() serie = models.ForeignKey(Serie, on_delete=models.CASCADE) ... class Episode(models.Model): title = models.CharField(max_length=120) order = models.IntegerField() episode = models.FileField(upload_to=episode_dir_path) season = models.ForeignKey(Season, on_delete=models.CASCADE) ... views.py: class SeriesDetailView(DetailView): model = Serie def get_context_data(self, **kwargs): context = super(SeriesDetailView, self).get_context_data(**kwargs) context.update({ 'seasons': Season.objects.all(), 'episodes': Episode.objects.all() }) return context urls.py: urlpatterns = [ path('library', LibListView.as_view(), name='library'), path('series/<int:pk>/season/<int:order>', SeriesDetailView.as_view(), name='serie-detail'), ] lib.html: <a href="{% url 'serie-detail' serie.id 1 %}"> (The 1 is because i want the first season) serie_detail.html: <section class="section mt-5"> <div class="container"> <h1>{{ serie.title }}</h1> <img class="card-img-top mb-2" src="{{ serie.thumbnail.url }}" style="height: 319px; width: 220px;"> <h6>Uploaded by: <h6 class="category text-warning"> {{serie.createdUser.username}}</h6></h6> <div class="row"> <h4 class="mb-0">Seasons:</h4> </div> <div class="row"> {% for season in serie.season_set.all %} <a href="" class="btn btn-default float-left">{{ season.order }}</a> {% endfor %} </div> <div class="row"> <h4 class="mb-0">Episodes:</h3> </div> <div class="row"> {% for season in serie.season_set.all %} {% for … -
How to return results when sending a post request to a website and then choose one of them?
I am trying to create a script which inputs text into www.citethisforme.com as a post request then chooses the first result. I am sending a post request to www.citethisforme.com which submits the text "albert einstein" to the form which i found information for after inspecting the page. When i run the scipt is seems to work but when i copy and past the response I do not see the results in the response. How do i see the results? and then what would I code to click the first result and return the response ? I have tried beautifulsoup and without beautiful soup but I am not getting the desired response or am i doing it wrong? my code: import requests from bs4 import BeautifulSoup body = {'jrQry': 'albert einstein'} with requests.Session() as s: con = requests.post("https://stackoverflow.com/", data=body) print (con.text) if you enter albert einstein into www.citethisforme.com you should see what is expected with respects to the results. -
Script is executed even though xss is enabled
I'm running my site on nginx server(1.12.2). I'm using django framework for my site. I have enabled X-XSS protection in settings.py in django by, SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = TRUE In nginx conf, I have added the headers to enable XSS protection. In network tab, I can see the header types in response headers. But when i type a script in form(say an alert), the script is getting executed even though xss is enabled. -
Django nested serializer with serializermethodfield
Context I have an API endpoint api/v1/checkin/ that returns the current DeviceGroup and the AppVersions for an App that have to be active. Problem The endpoint currently returns data along with the correctly filtered AppVersions like this: { "customer_device_uuid": "8d252b78-6785-42ea-9aee-b6f9e0f870b5", "device_group": { "group_uuid": "869b409d-f281-492e-bb62-d3168aea4394", "device_group_name": "Default", "color": "#0a2f45", "is_default": true, "app_versions": [ "2.0", "1.1" ] } } Goal I want the app_versions in the response to contain more data like this: { "customer_device_uuid": "8d252b78-6785-42ea-9aee-b6f9e0f870b5", "device_group": { "group_uuid": "869b409d-f281-492e-bb62-d3168aea4394", "device_group_name": "Default", "color": "#0a2f45", "is_default": true, "app_versions": [ { "app_version_uuid": "UUID here", "app_version_name": "1.1", "package_id": "package name here", "auto_start": false, "version_code": 1, "version_name": "0.1", "source": "link to file here" }, ... ] } } Serializers # serializers.py class AppVersionSerializer(serializers.ModelSerializer): auto_start = serializers.BooleanField(source='app_uuid.auto_start') class Meta: model = AppVersion fields = ('app_version_uuid', 'app_version_name', 'package_id', 'auto_start', 'version_code', 'version_name', 'source') class DeviceGroupSerializer(serializers.ModelSerializer): app_versions = serializers.SerializerMethodField(read_only=True) # filters the app versions per app def get_app_versions(self, model): qs = model.get_current_app_versions() return [o.app_version_name for o in qs] class Meta: model = DeviceGroup fields = ('group_uuid', 'device_group_name', 'color', 'is_default', 'app_versions') class CheckinSerializer(serializers.ModelSerializer): device_group = DeviceGroupSerializer(many=False, read_only=True, source='group_uuid') class Meta: model = CustomerDevice fields = ('customer_device_uuid', 'customer_uuid', 'device_id_android', 'device_group') extra_kwargs = { 'customer_uuid': {'write_only': True}, 'device_id_android': {'write_only': True} } I am … -
How to create two choices fields by using foreign key from another model?
I want to create a model which will hold the routes between two places, but I don't know how to handle choices fields in this model, also my choices should hold only places (village, city, and town) my Place model: class Place(CoreModel): TOWN = 'town' CITY = 'city' REGION = 'region' DISTRICT = 'district' VILLAGE = 'village' ROLE_CHOICES = ( (REGION, 'область'), (CITY, 'місто'), (DISTRICT, 'район'), (TOWN, 'село міського типу'), (VILLAGE, 'село') ) name = models.CharField(max_length=128, verbose_name='Place name', ) slug = models.SlugField(max_length=128, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) role = models.CharField(max_length=20, choices=ROLE_CHOICES, null=True, blank=True) my Route model: class Routes(CoreModel): start_point = models.ForeignKey(Place, on_delete=models.CASCADE) end_point = models.ForeignKey(Place, on_delete=models.CASCADE) but it doesn't work -
how to make Filter in Datatable using Dropdown in Django template
I am using Django. I have a data-table now want to know how to make a drop down filter.