Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pull new objects from Django view to implement endless scrolling?
I have a Django app for news articles. I want to first load 6 articles and when user scrolls through them, new 6 articles get automatically loaded (endless scrolling): This is the view: def index(request): context_dict = {} articles = Article.objects.order_by('-pub_date')[:6] context_dict['articles'] = articles context_dict['title'] = "title " context_dict['endless_scroll_token'] = '/home/' return render(request, 'obj_name/index.html', context_dict) This is the java-script / AJAX code: <script> function yHandler(){ var wrap = document.getElementById('body_panel'); var contentHeight = wrap.offsetHeight; var yOffset = window.pageYOffset; var y = yOffset + window.innerHeight; if(y >= contentHeight){ var ourRequest = new XMLHttpRequest(); var token = {{endless_scroll_token}}; if(token == "/home/") {token = '/';} ourRequest.open('GET', token); ourRequest.send(); ourRequest.onload = function(){ var ourData = ourRequest.responseText; wrap.innerHTML += ourData }; } } window.onscroll = yHandler; </script> The problem is that this way, the same 6 articles are loaded over and over. How do I pull 6 new articles each time ? Thanks! -
Django and ajax request Method Not Allowed (POST)
I am getting Method Not Allowed (POST) when I send an ajax post. It doesn't even get to the first request.method == 'POST' validation. I already checked everything I could think of and still I cannot figure out the error, probably something ridiculous. Already tried submitting the form directly through the 'action' attribute pointing to the same url, with the 'POST' method and I get the same error. Any thoughts/suggestions? My url: url(r'^crear_familiar/$', familiar_create, name='crear_familiar'), My ajax: var url = "{% url 'crear_familiar' %}"; $.ajax({ type: "POST", url: url, data: $("#familiarForm").serialize(), success: function (data) { console.log(data, 'SUCCESS'); location.reload(); }, error: function (data) { console.log('ERROR', data); } }); My view: def familiar_create(request): if request.method == 'POST': familiar_form = FamiliarForm(request.POST, prefix='familiar') if familiar_form.is_valid(): familiar = familiar_form.save(commit=False) familiar.save() message = 'Has creado un nuevo familiar' if request.POST['familiar_familia']: familia_id = request.POST['familiar_familia'] familia = Familia.objects.get(id=familia_id) tipo_familiar_id = request.POST['fhf-tipo_familiar'] tipo_familiar = TipoFamiliar.objects.get(id=tipo_familiar_id) familiar_assignment = FamiliaHasFamiliar( familia=familia, familiar=familiar, tipo_familiar=tipo_familiar ) familiar_assignment.save() message = 'Has creado un nuevo familiar y le has asignado una familia' status = 200 else: message = 'Ocurrió un error al crear al familiar' status = 500 return JsonResponse({'status': 'false', 'message': message}, status=status) else: print 'GET' return JsonResponse({'status': 'false', 'message': 'Wrong request'}, status=500) -
Unable to deploy Django on local with gunicorn and nginx
I am trying to deploy my first django web app. My knowledge in web servers is near by 0. After having configured everything, I get 502 Bad Gateway when trying to access my page. Gunicorn command sudo gunicorn website.wsgi --log-level debug -u root -group root. This allow me to access my app on localhost:8000, but the medias and static are not working. Nginx configuration: worker_processes 1; events { worker_connections 1024; } http { server{ listen 80; server_name localhost.kevin.lo; charset utf-8; access_log /var/log/nginx/oktomus.access.log; error_log /var/log/nginx/oktomus.error.log; location /media { alias /home/oktomus/workspace/code/web/website-prod/media; } location /static { alias /home/oktomus/workspace/code/web/website-prod/static; } location / { include fastcgi_params; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; fastcgi_pass localhost:8000; } } } Nginx error The error log when I try too access the app on port 80. 2017/07/05 21:06:20 [error] 9767#9767: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://[::1]:8000", host: "localhost" 2017/07/05 21:07:00 [error] 9767#9767: *7 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:8000", host: "localhost" 2017/07/05 21:07:31 [error] 9767#9767: *7 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: … -
Django + Rest Framework block content not working
So I'm trying to pass data from the rest framework to my main or included template html file. I can pass the data but for some reason django's block content stops working. How can I correctly pass data to any page or template? views.py: serializer_class = RackSerializer pagination_class = PostPageNumberPagination #PageNumberPagination renderer_classes = [TemplateHTMLRenderer] template_name = 'rack_project/main.html' def get(self, request): queryset = Rack.objects.all() return Response({'racks': queryset}) main.html: <div class="container-fluid" style="min-height:95%; "> <div class="row"> {% block content %} {% endblock %} </div> </div> header.html(included in main.html): {% block content %} <section class="content header"> <div class="row"> <div class="col-sm-8 rack_section"> <div class="div_title">RACKS</div> <div class="rack_section_content"> <ul> {% for rack in racks %} <li>{{ rack.location }}</li> {% endfor %} </ul> </div> </div> <div class="col-sm-4 rack_cpanel"> <div class="div_title">OPTIONS</div> <div class="rack_section_content"> asdasd </div> </div> </div> </section> {% endblock %} -
Full Text Search through specific column using django postgres's builtin full text search
I'd like to use full text search on my database and choose which columns to search through. Is there a way to search through a specific column (like only fruits) when I only I have one search_vector field in my Food model that contains all the columns (fruits, vegetables, dairy). I'd also like to search through all the columns so that's why I combined all the search vectors. Here's my model: class Food(models.Model): fruits = models.CharField(max_length=50) vegetables = models.CharField(max_length=50) dairy = models.CharField(max_length=50) search_vector = SearchVectorField(null=True) Here's how I store the vectors: vector= SearchVector('fruits', weight='A') + \ SearchVector('vegetables', weight='B') + \ SearchVector('dairy', weight='C') + \ Food.objects.annotate(document=vector).values_list('document', flat=True) for f in Food.objects.annotate(document=vector): f.search_vector = f.document f.save(update_fields=['search_vector']) Here's how I search: search_result = Food.objects\ .annotate(rank=SearchRank(F('search_vector'), "apple"))\ .filter(search_vector="apple")\ Is there an easy way of only searching in fruit column in the search_vector that I set up, or would I have to set up a separate search vector for each column? -
Django 1.11 upgrade - object has no attribute 'password'
I've been running fine on Django 1.7. I'm trying to upgrade to 1.11. I'm getting the following error on 1.11 and I can't seem to find the problem. Here's the code in question: class Profile(models.Model): profile_id = models.CharField(max_length=50, null=True, unique=True, db_index=True) pet_shop_customer_id = models.CharField(max_length=40) django_user = models.OneToOneField(User, to_field='username', parent_link=True, null=True, db_column="django_username", default=None, db_index=True, db_constraint=False) The problem is when I call: profile = Profile.objects.get(profile_id='x') # pulls a valid profile print profile.django_user I get this error: Exception Value: 'Profile' object has no attribute 'password' Exception Location: /Users/../lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py in <dictcomp>, line 291 -
Saving a span to the database in django
I am having an issue where I created some html that creates tags. <span> Qualifications: </span> <input type="text" class="qualif_txt" id="qualif_txt"><input type="button" class="qualif_btn" id="qualif_btn" value="Add"> </label> <div id="qualif" class="qualif"></div> </div> This results in a tag being created, but I need to save it in order to display it on another page. I'm using Django 1.9 It is preferable to use this method rather than something like django-taggit. Thanks for the help in advance. -
Using python scrapy based crawler but getting error
Hi folks I have written a crawler in python for scraping...... import scrapy from c2.items import C2Item try: class C2(scrapy.Spider): name = 'cn' allowed_domains = ['priceraja.com'] start_urls = ['https://www.priceraja.com'] def parse_item(self, response): Item = [] Item['url']=response.xpath('//a/@href/text()').extract() yield Item except Exception: logging.exception("message") I keep on getting NotImplemented error -
django postgresql url unix socket
I've read the Django docs and other references to using PostgreSQL over Unix sockets with Django, but am stuck trying to find the correct format (if possible) using a DB URL in a .env file. My current DB conn parameter in my env file is: DATABASE_URL="psql://sqluser:passwd@127.0.0.1:5432/dbname" I tried: DATABASE_URL="psql://sqluser:passwd@/var/run/postgresql/.s.PGSQL.5432/dbname" I have MD5 set for the sqluser on the dbname in pg_hba.conf but with this I get: psycopg2.OperationalError: FATAL: Peer authentication failed for user "flicker1" My pg_hba.conf: # Database administrative login by Unix domain socket local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local dbname sqluser md5 local all all peer PSQL logs show the user ID is passed, but conflicts with the Unix user as an error, as it seems to want to use the peer method and not the MD5. -
Django 1.11 custom widget template TemplateDoesNotExist
I am trying replace widget template with my own, but in any way getting TemplateDoesNotExist error. in app\forms.py: class SelectPlus(Select): template_name = 'selectplus.html' class SimpleForm(ModelForm): somefield = ModelChoiceField( queryset=SomeObjects.objects.all(), widget=SelectPlus(attrs={'url': 'custom_url_to_context'}) ) in settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ROOT_PATH, 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, In debug trace i see that template-loader doesn't search in apps folders or main template folder: bun all other templates works fine. -
Django background task for sequential execution
I am developing a Django website where user will submit his request.After submission the user will receive a message that he will receive the result through mail and the request will go in a request queue (FIFO) which has to be processed sequentially . What i need is a background task that will be global which fetches request from the queue one by one and processes it ? This requests coming through website can be multiple but processing is sequentially. I researched on the stack overflow a bit and came across CELERY and THREADS to implement this. What should i do celery, threads or any other method ? -
Missing form fields in Django model admin
I'm upgrading a Django app to 1.6, and I'm getting the error: Unknown field(s)(custom_field) specified for MyModel. Check fields/fieldsets/exclude attributes of class MyModelAdmin. I have a custom form for my ModelAdmin that adds a custom field like: class MyModelForm(ModelForm): class Meta: model = models.MyModel fields = '__all__' def __init__(self, *args, **kwargs): print('before form init') super(MyModelForm, self).__init__(*args, **kwargs) print('after form init') self.fields['custom_field'] = forms.IntegerField(required=False) class MyModelAdmin(ModelAdmin): form = MyModelForm I'm not seeing either of the print statements, so it seems the ModelAdmin isn't even initializing the form before it tries to render the admin page. Unfortunately, I can find nothing in the 1.6 release notes that would explain this, as it doesn't mention any change to how the ModelAdmin class supports custom forms. How do I fix this? -
Creating postgresql database in Docker with Django project
I would like to create postgresql database in docker with my Django project. I'm trying to do it using init.sql file but it doesn't work: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'aso', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } init.sql: CREATE USER postgres; CREATE DATABASE aso; GRANT ALL PRIVILEGES ON DATABASE aso TO postgres; My updated Dockerfile: FROM python:3.6.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip3 install -r requirements.txt ADD . /code/ FROM library/postgres ADD init.sql /docker-entrypoint-initdb.d/ Unfortunately I get: db_1 | LOG: database system was shut down at 2017-07-05 14:02:41 UTC web_1 | /usr/local/bin/docker-entrypoint.sh: line 145: exec: python3: not found db_1 | LOG: MultiXact member wraparound protections are now enabled db_1 | LOG: autovacuum launcher started db_1 | LOG: database system is ready to accept connections dockerpri_web_1 exited with code 127 -
I want to cache Django database objects without changing every single line that does a DB lookup
Short Version: In Django (ideally Django 1.7), I want to read certain database objects just once each day at 2 AM and cache them. Each time I do MyModel.objects.get() it will not touch the database, it will use the cache. Then I will manually refresh the cache at 2 AM. I do not want to change every single line that has a query like MyModel.objects.get() because I would need to change 100+ lines and it would get verbose. Long Version: I am working with a very large Django project that is old and not entirely sensible. Once each day (at 2 AM after backups, during scheduled downtime), the Django application reads a set of protected database objects (rows, model instances), checks them for consistency, and then it uses exactly those values until the next day. These database objects (rows) can only be changed during the scheduled downtime at 2 AM, and changing them in the middle of the day would corrupt data and make things confusing. I already wrote a pre_save hook that errors out if you try to modify these database objects when it is not in scheduled downtime. I also gave very few people access to these database … -
Django project can't be deployed to Heroku
I am trying to deploy Django project. Firstly, I get this error: Counting objects: 74, done. Delta compression using up to 2 threads. Compressing objects: 100% (65/65), done. Writing objects: 100% (74/74), 25.74 KiB | 0 bytes/s, done. Total 74 (delta 24), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Failed to detect app matching https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to nicoplus. remote: To https://git.heroku.com/nicoplus.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/nicoplus.git' Then, I set the buildpack: heroku buildpacks:set heroku/python But, it still throw an error: remote: -----> Failed to detect app matching https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz buildpack So, any solution to this problem? PS: python is 2.7.12 -
Integrating AngularJS v4 with Django Backend project
Following the Angular v4 Setup instructions, I've navigated to the root of my Django app and run npm install -g @angular/cli and then ng new myappname. I've already set up a RESTful API using the Django Rest framework to use with the Angular Frontend. However, after looking online, i've found very little information as to how to setup Angular v4 with Django, so that I can code in typescript to compile all the Javascript files. Additionally, rather than having the angular app and django server running on different ports, I'd like them to run on the same port. I've researched webpack and webpack-loader as potential solutions to the problem but cannot figure out how to use them. I'd like to run ng new myappname in my root directory, and then when running python manage.py runserver, I can navigate to my angular project from there. Any tips would be greatly appreciated. -
GeoDjango: Add map of related objects to model Admin page
Using the GeoDjango library: Is it possible to plot a related set of (Station) objects on a single map within the admin change page for the System model (which doesn't have any geometry of its own)? The models are below: from django.contrib.gis.db import models class System(models.Model): pass class Station(models.Model): system = models.ForeignKey(System) location = models.PointField() The admin change page for each Station renders the 'location' PointField on a map. However, I want to squeeze the most out of the admin interface's out-of-the-box functionality as possible before delving into writing my own js, html and rest endpoints for spending over Geojson. I'm pretty new to gis web mapping, so any suggestions will help! I'm not sure if this is even the right approach, but if in helps you to point me in the right direction here is what I'm attempted so far: Admin: class SystemAdmin(gisadmin.OSMGeoAdmin): form = SystemForm map_template = 'admin/system_OSM.html' def get_station_data(self): return Station.objects.filter(system__id_exact=self.id) def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['station_data'] = self.get_station_data() return super().change_view( request, object_id, form_url, extra_context=extra_context, ) Custom map_template: {# Override the extra_layers block (defined in gis/admin/openlayers.js??) #} {% block extra_layers %} <script type="text/javascript"> new layer/GeoJSON data goes here???? </script> {% endblock … -
DJANGO REST API: Not NULL Constraint Failed
I'm working on a User Preferences viewset in DJANGO REST API in which a user can get a list of preferences along with updating the preferences. In Postman i can get the user's preferences, but when i go to 'put' i'm getting the following error: Integrity Error --NOT NULL constraint failed: pugorugh_userpref.age --any reason this might be happening? The UserPref Model is below: class UserPref(models.Model): user = models.ForeignKey(User) age = models.CharField(choices=AGE, max_length=7, default='b,y,a,s') gender = models.CharField(choices=GENDER_PREF, max_length=3, default='m,f') size = models.CharField(choices=SIZE_PREF, max_length=8, default='s,m,l,xl') def __str__(self): return '{} preferences'.format(self.user) def create_user_preference(sender, **kwargs): user = kwargs['instance'] if kwargs['created']: user_pref = UserPref(user=user) user_pref.save() post_save.connect(create_user_preference, sender=User) Here is my ViewSet: class UserPrefViewSet( mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """View to get and update User Preferences.""" permission_classes = (permissions.IsAuthenticated,) queryset = models.UserPref.objects.all() serializer_class = serializers.UserPrefSerializer # /api/user/preferences/ @list_route(methods=['get', 'put']) def preferences(self, request, pk=None): user = request.user user_pref = models.UserPref.objects.get(user=user) if request.method == 'PUT': data = request.data user_pref.age = data.get('age') user_pref.gender = data.get('gender') user_pref.size = data.get('size') user_pref.save() serializer = serializers.UserPrefSerializer(user_pref) return Response(serializer.data) and SERIALIZER class UserPrefSerializer(serializers.ModelSerializer): extra_kwargs = { 'user': {'write_only': True} } class Meta: fields = ( 'age', 'gender', 'size' ) model = models.UserPref -
Many to Many django field not saving
I am trying to store form data to a model, when the user submits the form all of the data is saved correctly besides a many to many field (shoes) which is showing up as ShoeApp.Shoe.None, can someone please help me edit my view so that I can save this information? Thank you in advance. models.py: class Shoe(models.Model): """ Stores shoes for use in app """ symbol = models.CharField(max_length=32) aliases = ArrayField(models.CharField(max_length=16, blank=True), blank=True, null=True) description = models.CharField(max_length=512, blank=True) ensembl_id = models.CharField(max_length=32, blank=True) def get_absolute_url(self): return reverse('shoelist') def __str__(self): return self.symbol class Meta: ordering = ('symbol',) class ShoeList(models.Model): """ A list of shoes that can be selected """ name = models.CharField(max_length = 256) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.CharField(max_length = 512) notes = models.TextField() shoes = models.ManyToManyField(Shoe) public = models.BooleanField(default = False) def get_absolute_url(self): return reverse('shoelistlists', kwargs={'pk': self.pk}) forms.py: class ShoeListCreateForm(forms.ModelForm): shoes = forms.ModelMultipleChoiceField( queryset=Shoe.objects.all(), widget=autocomplete.ModelSelect2Multiple(url='shoelist-autocomplete') ) class Meta: model= ShoeList fields = ['name', 'description', 'notes', 'shoes', 'public'] views.py class ShoeListAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated(): return Shoe.objects.none() qs = Shoe.objects.all() if self.q: qs = qs.filter(symbol__istartswith=self.q) return qs class ShoeListCreateView(CreateView): form_class = ShoeListCreateForm model = ShoeList def form_valid(self, form): # print('form is valid') # print(form.data) obj = form.save(commit=False) … -
Django : cannot access the field from template
can't get the field data when using for loop in template.without using for loop it displays the data. models.py from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): # __unicode__ on Python 2 return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): # __unicode__ on Python 2 return self.headline class Meta: ordering = ('headline',) views.py def index(request): user = Reporter.objects.get(id = 1) detail = user.article_set.all() args = {'index':detail} return render(request, 'index.html ',args) index.html {{ index }} {% for i in index %} <h1>i.headline<h2>i.pub_date</h2></h1> {% endfor %} i get This error -
Django overriding save method with multiplied db
First of all sorry for my english. Now i'm trying to multiply db with django + postgres. I got stuck at syncronizing my databases. There are 1 master database and two replicas. All under django. And one 3-d party app which writes data to one django app. How should I syncronize my databases? I mean what is the best practice in this case. Also I'd like to ask what is the best way to write data inside django data to databases? My master db is configured to write and slaves to just read. How should I write data to my slaves? Could you give me some examples please? -
Make dumpdata automatic each time I record a template
A great thing with Django is we could create templates directly in the admin of a web application. The problem with that is I have to manually convert it into JSON format and dump into the dedicated .json file. Explicitly, I have to write the following command in bash (in my django project) : python manage.py dumpdata --indent=2 configurations.emailtemplate > loanwolf/configurations/fixtures/tests_emailtemplates.json. I'd like this command to run automatically each time I record a template. Coud I do such thing? If not, how could I build a .sh command to make that easier? -
Django system check stuck on unreachable url
In my project I have requests library that sends POST request. Url for that request is hardcoded in function, which is accessed from views.py. The problem is that when I dont have internet connection, or host, on which url is pointing, is down, I cant launch developer server, it gets stuck on Performing system check. However, if I comment the line with url, or change it to guarantee working host, check is going well. What is good workaround here ? -
TypeError: __init__() missing 1 required positional argument: 'get_response' [duplicate]
This question already has an answer here: Why does list.append evaluate to false? 5 answers Creating a custom middleware, I ve got such en Error: TypeError: __init__() missing 1 required positional argument: 'get_response' But write how in django docs. Has anyone any ideas how to make this work? middleware.py class RequestMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) info = RequestInformation(request_method=request.META['REQUEST_METHOD']) info.save() time = RequestInformation(execution_time=datetime.now()) time.save() return response -
Can't style form using crispy-forms FormHelper - bootstrap-horizontal
I am trying to override Django form styling with crispy-forms FormHelper. Precisely form-horizontal. On crispy-forms site it is explained nice, but I am doing something wrong (probably). https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html example from site helper.form_class = 'form-horizontal' helper.label_class = 'col-lg-2' helper.field_class = 'col-lg-8' helper.layout = Layout( 'email', 'password', 'remember_me', StrictButton('Sign in', css_class='btn-default'), ) forms.py from django import forms from .models import Sertifikat from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit # from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field # from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions class SertifikatFormularM(forms.ModelForm): def __init__(self, *args, **kwargs): super(SertifikatFormularM, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-2' self.helper.field_class = 'col-md-8' self.helper.layout.append(Submit('save', 'Završi Uverenje')) class Meta: model = Sertifikat fields = [ 'broj_zapisnika', 'broj_kartice_radionice', 'ime', 'adresa', 'proizvodjac_v', 'tip_v', ... novi.html (template for this page) {% extends 'legendarna/base.html' %} {% load crispy_forms_tags %} {% block main %} <h2>Novi sertifikat</h2> <button type="button" class="btn btn-info" data-toggle="modal" data-target="#modalObim">Unesi obim točka</button> <!-- Modal --> <div id="modalObim" class="modal fade" role="dialog"> <div class="modal-dialog modal-sm"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> --- uninportant, code for modal </div> </div> </div> <!-- <form action="." method="post"> --> {% csrf_token %} {% crispy f %} <a href="{% url 'lista_sertifikata' %}" class="btn btn-warning">Odustani</a> <!-- </form> --> <script …