Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get one object in queryset iteration
I have two models, A and B, and B is ForienKey relationship to A. I want to check each object in queryset and if it has certain fields then I want to display it in template. Below is my template example: {% for a in a_qs %} <tr> <th>{{ a.b_set.first.a_field }}</th> <th>{{ a.b_set.first.another_field }}</th> {% endfor %} They work fine, but I want to apply something like get method in queryset. Below is what I want to achieve: {% for a in a_qs %} <tr> <th>{{ a.b_set.get(a_field_in_B='hello').a_field }}</th> <th>{{ a.b_set.get(a_field_in_B='hello').another_field }}</th> {% endfor %} I understand that something above is not possible and I want to give some change to my views or models, but I don't know where to start. Below is something like my views.py snippet: a_qs = A.objects.all() a_obj = a.b_set.get(a_field='something') # a is not defined yet. I want every a in a_qs to be checked Thanks for your advice in advance. -
Stream multiple files at once from a Django server
I'm running a Django server to serve files from another server in a protected network. When a user makes a request to access multiple files at once I'd like my Django server to stream these files all at once to that user. As downloading multiple files at once is not easily possible in a browser the files need to be bundled somehow. I don't want my server having to download all files first and then serve a ready bundled file, because that adds a lot of timeloss for larger files. With zips my understanding is that it can not be streamed while being assembled. Is there any way to start streaming a container as soon as the first bytes from the remote server are available? -
NoReverseMatch at /collection/6/
I'm a beginner at Django/programming in general. I have a problem with a redirecting url button on one of my HTML pages. Basically I have a collection page where one can add plants. The collection page displays all of the added plants and an add plant button for the user to enter another one to the database. Then when you click on a plant, you see the plant, the picture you added, and the nickname. There is also other data that can be added, for that I made a CreateView that adds details such as date purchased and notes. Now this page works and when I go to the URL manually I can update a plant. However when I want to add an 'add details' button to my html file of a specific plant, I get this error that I just cannot solve. Here is some mandatory code: Models.py class PlantDetail(models.Model): """This class contains various types of data of added plants""" """links the details to one plants""" from datetime import date plant = models.ForeignKey(Plant, on_delete=models.CASCADE) date_purchased = models.DateField(default=date.today) notes = models.TextField() def __str__(self): """Return the detail input from the user""" return self.notes def age(self): """Return the age of the plant … -
Django - Change records in pandas dataframe
with tkinter and pandas I have created a program where I can import csv files, and then using python script correct the file (delete columns, change rows, delete duplicates etc.) and then export a new csv. the script I use - https://gist.github.com/Dackefejd/972f4c37861df3cda3398e29f9a17344 I now want to get the same function through a Web application. Found Django who with the help of pandas seems to fulfill my purpose. My question: is there any good way to correct panda's data frame in Django? For example, delete columns / rows I have looked at tablib, but is there anything to recommend? If I am unclear, you are welcome to ask questions -
return a splitted long sting in a table field in django queryset
I am using mySQL as the database of my django project. One filed of a table in this db has text values seprated by , like: tags = "Django, MySql, C, C++, Python, Cython" I need to check if there is my desired string in the above field when I am filtering query set: this is my query: my_tag = "C" posts = Post.objects.filter(tags__icontains=my_tag).order_by('-date_created') The above query also return Cython but I just expect C and that's because tags text is not splitted by ,. How can I find a sting in a text, In regular python there is str.split(',') or regex however in django I don't know! -
How to compare database values with forms.py value in django
How to compare database reseved_start_time value with forms.py reserved_start_time form value. models.py class Reservation(models.Model): Power_System = 0 Water_System = 1 Blade = 2 STATUS = ( (Power_System, _("Power System")), (Water_System, _("Water System")), (Blade, _("Blade Server")), ) user = models.ForeignKey("auth.User", on_delete=models.CASCADE) username = models.CharField(max_length=20, blank=True) lastname = models.CharField(max_length=20, blank=True) email = models.EmailField(max_length=50, blank=True) reserved_start_date = models.DateField(default=timezone.now) reserved_start_time = models.TimeField(blank=True, null=True) reserved_end_time = models.TimeField(blank=True, null=True) status = models.SmallIntegerField(choices=STATUS, default=Power_System) updated_datetime = models.DateTimeField(auto_now=True) def __str__(self): return str(self.reserved_start_date) if reserved_start_time section return "Try the another starting time" message when database values dont have any time which write in the form screen. forms.py class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = ["username","lastname","email","reserved_start_date","reserved_start_time","reserved_end_time","status"] def clean(self): username = self.cleaned_data.get("username") lastname = self.cleaned_data.get("lastname") email = self.cleaned_data.get("email") reserved_start_time = self.cleaned_data.get("reserved_start_time") reserved_end_time = self.cleaned_data.get("reserved_end_time") if not username: raise forms.ValidationError("Adınızı Giriniz") if not lastname: raise forms.ValidationError("Soyadınızı Giriniz") if not email: raise forms.ValidationError("Email Adresini Giriniz") if not reserved_start_time: raise forms.ValidationError("Başlangıç Saatinizi Giriniz") if not reserved_end_time: raise forms.ValidationError("Son Saatinizi Giriniz") if email: validator = EmailValidator("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") validator(email) if reserved_start_time: rezersvasyon_zamani = Reservation.objects.get(reserved_start_time=reserved_start_time) for reservasyon in rezersvasyon_zamani: if reservasyon.reserved_start_time not in reserved_start_time: raise forms.ValidationError("Try the another starting time") values = { "username": username, "lastname": lastname, "email": email, "reserved_start_time": reserved_start_time, "reserved_end_time": reserved_end_time, } return values -
How rel_db_type() method works in django?
Django documentations says, It returns the database column data type for fields such as ForeignKey and OneToOneField that point to the Field, taking into account the connection. I have gone through the Custom Model Field documentation. But I am not able to understand this part. How does ForeignKey and OneToOneField calls this method of another field. -
UNIQUE constraint failed: Users.username error in Django
For some unknown reasons, I am facing that error I have searched for some of the possible errors but those I have tried doesn't work I tried user = form.save(commit=False) maybe it would work but no positive result Here is the error log Environment: Request Method: POST Request URL: http://localhost:8000/accounts/register-result Django Version: 3.1.2 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.accounts', 'apps.result'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'apps.result.middleware.LoginRequiredMiddleware'] Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: Users.username) was the direct cause of the following exception: File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\resultLab\apps\accounts\views.py", line 32, in register_school user = User.objects.create_user(username=username,email=email,password=password) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\models.py", line 146, in create_user return self._create_user(username, email, password, **extra_fields) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\models.py", line 140, in _create_user user.save(using=self._db) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 754, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base force_update, using, update_fields, File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) … -
net::err_content_length_mismatch 200 (ok) django, apache
My django website sometimes cannot open images and the error message is "Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH". However, when I open the link next to the error message on a new tab, the image is loading. I am using Apache not nginx Could someone help me with this problem? -
How does django's ORM get one to one fields without having to call a function
So let's say I have a django model like so: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) After creating this one to one field, the profile object can be accessed by doing user_instance.profile I've enabled logging for the ORM to see the queries sent to the database using this in my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': False, }, }, } I then opened the shell using python3 manage.py shell and executed the following: firstuser = User.objects.first() This resulted in the following query logged out: SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."username", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."name", "users_user"."email", "users_user"."join_date", "users_user"."date_of_birth" FROM "users_user" ORDER BY "users_user"."id" ASC LIMIT 1; args=() Further I did: firstuser.profile And got this query logged out: SELECT "users_profile"."id", "users_profile"."user_id", "users_profile"."status", "users_profile"."institute" FROM "users_profile" WHERE "users_profile"."user_id" = 1 LIMIT 21; args=(1,) So, how does django execute a query when I request a related object without having to call any functions within my own code. Is there a python method to override behaviour of how attributes from a class are read? Thanks in advance! -
graphene-django add additional argument for DjangoObjectType and pass it to get_queryset
I have added an additional argument called user_type to disposal_request query, and I want to use this argument to add another filter but when I passed it to get_queryset function. I get the following error: get_queryset() missing 1 required positional argument: 'user_type' I'm not sure how to pass the argument properly. import graphene import graphene_django from app.disposer.models import DisposalRequest from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required class UserType(graphene.Enum): as_collector = "as_collector" as_disposer = "as_disposer" class DisposalRequestsType(graphene_django.DjangoObjectType): latitude = graphene.String() longitude = graphene.String() class Meta: model = DisposalRequest exclude = ("location",) filter_fields = [ "uuid", "disposal_status", ] interfaces = (graphene.Node,) convert_choices_to_enum = False @classmethod @login_required def get_queryset(cls, queryset, info, user_type): user = info.context.user if user_type == UserType.as_collector: print("as_collector") return queryset.filter(collector=user) elif user_type == UserType.as_disposer: print("as_disposer") return queryset.filter(disposer=user) def resolve_latitude(self, _): return self.location.x def resolve_longitude(self, _): return self.location.y class DisposalQueries(graphene.ObjectType): disposal_requests = DjangoFilterConnectionField( DisposalRequestsType, user_type=UserType() ) -
Django 3: Filter queryset for letter or non-letter
In my database I have a table with items who's titles can start with a letter or a non-letter-character. For example a number or an "@" or a "#". The model looks like this: class Items(models.Model): title = models.CharField(max_length=255) body = models.TextField In my view I would like to separate the model into two objects. One objects that contains all the item with a title starting with a letter and an other object with all the other items: class ItemsView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): alpha_list = Items.objects.filter(title__startswith=<a letter>) other_list = Items.objects.filter(title__startswith=<not a letter>) context = { "list_a": alpha_list, "list_b": other_list } return context I have been consulting the documents, stackoverflow and the holy google, but so far I have not been able to find a solution. Any help is very much appreciated. -
Sorting filtered results based on word occurrence using Django Model Filter
Platform: Django 1.1, Python 3.6 on a Linux server, backend is MySQL. I'm after a fairly common functionality but I need guidance to where/how to begin this: I have a model object called Article. I'm trying to implement a search function that retrieves articles based on searched terms, and then sort based on occurrences of words in the searched term. In Article, I have the following fields that I'd like to sort or 'prioritise' based on: - name, a text field - keywords, also a text field but would contain comma-separated words - article_text, a text area field that will contain the article itself I want to basically sort the most relevant article to the least relevant, based on the searched terms input against name, keywords, and occurrences of words in article_text. In my views.py I have this function that triggers on request.POST: form_data['search_term'] = request.POST.get('search_term') #removing question mark from term search_term = search_term.replace("?","") #Converting terms to a list of words, then converting all words to lowercase search_terms_list = search_term.split(' ') search_terms_list = [x.lower() for x in search_terms_list] #Fetching results results = Article.objects.filter(reduce(lambda x, y: x | y, [Q(name__icontains=word) | Q(keywords__icontains=word) | Q(article_text__icontains=word) for word in search_terms_list])) I am retrieving … -
Calling a script to save form data in google sheets from django app using js
I am making a web app and I have one form in it. I want to store the data that a person enters, in the form to be mapped in google sheets. The script successfully saves the data onto the sheet but upon saving I am redirecting the user to a new page. The problem is when I attach the code of data mapping, the redirection doesn't work but if I comment the code where I am calling the script, the redirection starts working. # here is the code where i have made the form in HTML file using crispyforms <form method="POST" id="submit_info" class="bg-light p-4 p-md-5 contact-form" name="google-sheet"> {% csrf_token %} {{form|crispy}} <div class="form-group text-center"> <input type="submit" value="Send Message" class="btn btn-primary center py-3 px-5"> </div> </form> This is the js code that executes to save the data onto google sheets <script> const scriptURL = 'https://script.google.com/macros/s/AKfycbwN9jxAQwA9f7qF_tvUbpuRpIhObeAJT8nAqwIRrDZYMPqbyf6j/exec' const form = document.forms['google-sheet'] form.addEventListener('submit', e => { e.preventDefault() fetch(scriptURL, { method: 'POST', body: new FormData(form)})}) </script> This is the code where I am handling the redirection and saving in django views.py file: def store(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('thankYouPage') # a second webpage where user should be … -
How to create multiple objects with different values with forloop in django?
I need to create two models from a single template. Creating Product model is fine. The Product model has the ManyToOne relation with ProductVariant. But I got problem while creating ProductVariant model. request.POST.getlist('names') this gives me the result like this ['name1','name2] and the same goes for all. I want to create ProductVariant object with each values. How can I do this ? Also I think there is a problem while stroing a HStoreField. request.POST.getlist('attributes') gives the value like this ['a:b','x:z'] so I converted it into dictionary(but not sure it works). models class ProductVariant(models.Model): name = models.CharField(max_length=255, blank=False, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) attributes = HStoreField() price = models.FloatField(blank=False, null=False, default=0.0) views product = product_form.save() attributes = request.POST.getlist('attributes') names = request.POST.getlist('name') up = request.POST.getlist('price') weight = request.POST.getlist('weight') print(names, 'names') # converting attributes into the dictionary for the HStore field for attribute in attributes: attributes_dict = {} key, value = attribute.split(':') attributes_dict[key] = value ProductVariant.objects.create(name=name,...) # for each value I want to create this. -
Pass value to CSS style Tag from Django View
I have this View where I generate a percentage value that depends on some logic in the backend. def my_view(request): #[..other stuff..] perc_value = 80 # this changes with the logic above context = {'perc_value': perc_value} return render(...) In my HTML I need to render a progress-bar that will be filled with perc_value, like this: <div class="progress progress-xl mb-2"> <div class="progress-bar" role="progressbar" style="width: {{ perc_value }}">{{ perc_value }}%</div> </div> I have found this similar question (link), which is pretty old and I can't find a way to make it work. What's the best way for this kind of problem? -
Save method of Django model does not update fields of existing record even if force update
I am trying to update the record that already exists in the database and therefore I use this code if 'supplierId' not in req.keys(): return JsonResponse({'code': 0, 'msg': "supplier was not selected", 'result': ''}, safe=False) if 'assigneeId' not in req.keys(): assigneeId = User(0) else: assigneeId = User(req['assigneeId']) if 'responsibleId' not in req.keys(): responsibleId = User(0) else: responsibleId = User(req['responsibleId']) if 'redistributionMethod' not in req.keys(): redistributionMethod = 0 else: redistributionMethod = req['redistributionMethod'] if 'allCost' not in req.keys(): amount = 0 else: amount = req['allCost'] procurement_doc = ProcurementDocJournal.objects.get(id=pk) print(procurement_doc) procurement_doc.docType = req['docType'] procurement_doc.status = req['status'] procurement_doc.companyId = Company(req['companyId']) procurement_doc.datetime = req['datetime'] procurement_doc.supplierId = Partner(req['supplierId']) procurement_doc.assigneeId = assigneeId procurement_doc.warehouseId = Warehouse(req['warehouseId']) procurement_doc.responsibleId = responsibleId procurement_doc.redistributionMethod = redistributionMethod procurement_doc.amount = amount procurement_doc.comment = req['comment'] procurement_doc.save() where req contains a request something like this { 'docType': 3, 'status': 1, 'companyId': '2', 'warehouseId': '3', 'assigneeId': '5', 'supplierId': '12671', 'responsibleId': '5', 'datetime': '2020-04-01 08:01:00', 'comment': '' } As you can see there is a print which assures me that I selected the correct row when I noticed that these records are not updated I searched for causes and found this question where the guy who asked says The message field was missing from the model definition in … -
Got AttributeError when attempting to get a value for field `name` on serializer
I'm new with this django rest framework thing and I'm having a problem showing one of my models in the api interface. I have 3 models that are related License, Profile and Rules. I can see Profile and License clearly but Rules (which is related with profile and license) gives me the next error: Got AttributeError when attempting to get a value for field name on serializer LicenseSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Rule instance. Original exception text was: 'Rule' object has no attribute 'name'. This is my model file: models.py: class License(LogsMixin, models.Model): """Definicion de modelo para licencias""" name = models.CharField( "Nombre de la licencia", max_length=100, null=False, blank=False) billable = models.BooleanField(default=False) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Profile(LogsMixin, models.Model): """Definición de modelo para Perfiles""" name = models.CharField( "Nombre de la perfil de usuario", max_length=100, null=False, blank=False ) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Rule(LogsMixin, models.Model): """Definición de modelo para Reglas""" FIELDS = [ ('user_name', 'Nombre de usuario'), ('user_code', 'Codigo de usuario') ] string = models.CharField("Cadena de referencia", max_length=100, null=False, default="", blank=False) profile = models.ForeignKey(Profile, null=False, default=None, on_delete=models.DO_NOTHING) license = models.ForeignKey(License, null=False, default=None, on_delete=models.DO_NOTHING) field = models.CharField("Campo … -
Prevent Nginx from changing host
I building an application which is right now working on localhost. I have my entire dockerized application up and running at https://localhost/. HTTP request is being redirected to HTTPS My nginx configuration in docker-compose.yml is handling all the requests as it should. I want my application accessible from anywhere hence i tried using Ngrok to route the request to my localhost. Actually i have a mobile app in development so need a local server for apis. Now, when i enter ngrok's url like abc123.ngrok.io in the browser, the nginx converts it to https://localhost/. That works for my host system's browser, as my web app is working there only, but when i open the same in my mobile emulator. It doesn't work. I am newbie to nginx. Any suggestions will be welcomed. Here's my nginx configuration. nginx.conf upstream web { ip_hash; server web:443; } # Redirect all HTTP requests to HTTPS server { listen 80; server_name localhost; return 301 https://$server_name$request_uri; } # for https requests server { # Pass request to the web container location / { proxy_pass https://web/; } location /static/ { root /var/www/censr.me/; } listen 443 ssl; server_name localhost; # SSL properties # (http://nginx.org/en/docs/http/configuring_https_servers.html) ssl_certificate /etc/nginx/conf.d/certs/localhost.crt; ssl_certificate_key /etc/nginx/conf.d/certs/localhost.key; root … -
How To Use Scope Variable In NG-REPEAT Angular JS
Since I am quite new to AngularJS, Have a problem with this code. var app = angular.module("demoModule",['infinite-scroll']); app.controller("demoController",function($scope){ $scope.result = []; $('#subCategory').on('change',function(){ subID= $(this).val(); category = new URLSearchParams(window.location.search); $.ajax({ type:'POST', url:'/filter/', data:{'sub_cat_id':subID,'csrfmiddlewaretoken':'{{ csrf_token }}','cat_id':category.get('category')}, success: function(response){ $scope.result = response; } }); }); $scope.lazyLoad = function(){ console.log("LAZY LOAD!"); } }); My HTML Template is:( Am using Django ) {% verbatim %} <div ng-app="demoModule" ng-controller="demoController"> <div class="container mt-2"> <div class="row"> <div class="col-md-12"> <div class="row"> <h1>Results are {{result}}</h1> <div class="col-md-4 mb-3" ng-repeat="item in result"> <div class="card"> <img src="#" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.product_name}}</h5> <button id="{{item.id}}" class="btn btn-primary btn-block">Details</button> </div> </div> </div> </div> </div> </div> </div> </div> {% endverbatim %} The problem is, whenever I select an option from a select menu, the javascript ajax function is called & JSON is responded. (I want to print these JSON objects (which as stored in $scope.result) by using ng-repeat in angular js) Really, can't understand why it is not printing? -
Why does the value of request.user appear to be inconsistent?
I am wanting an application to be able to check whether the user that is currently logged in is "test2". I'm using Django and running the following code: <script> console.log('{{ request.user }}') {% if request.user == "test2" %} console.log('The user that is currently logged in is test2.') {% else %} console.log('There was an error.') {% endif %} </script> And my console is logging the following: test2 There was an error. Why is this? How do I get the application to recognise that "test2" is logged in? -
How to convert each items of list into a dictionary?
Here I have a list like this. ls = ['Small:u', 'Small:o'] What I want is to create a dictionary of each list items like this. dict1 = {'Small':'u'} dict2 = {'Small':'o'} How can I do it ? Is it possible? -
How can I convert list into dictionary in python?
Here I have list and I want to convert this list into the dictionary How can I do it ? I have a list like this ['Small:u,', 'Small:o,'] Now I want to convert this list into this format {'small':'u', 'small':'o'} -
Create modalForm Django
I tried to create modalForm in base.html to call add-article view in any page. Here is how I do views.py def add_article(request): new_article = None if request.method == 'POST': add_article = ArticleCreateForm(request.POST, request.FILES) if add_article.is_valid(): add_article.save(commit=False) new_article.author = request.user new_article.save() else: add_article = ArticleCreateForm() context = { 'add_article': add_article, } return render(request, 'add_article.html', context) urls.py path('article/add-article/', views.add_article, name='add-article') base.html <a class="nav-link" id="add-article"><i class="fa fa-pencil fa-2x" aria-hidden="true"></i></a> <script type="text/javascript"> $function () { $("#add-article").modalForm({ formURL: "{% url 'add-article' %}", }); }); </script> But it doesn't show anything when clicking into write icon. Can anyone help me where I went wrong? -
Cancel button the form doesnt work properly
This is my form. Submit works properly fine. BUt with this I can only CANCEL, only when I fill all the fields. What I want is to cancel anytime and reach the main airlines page. Also, I want the cancel button in the form page.What will the be the solution?? <form action="{% url 'addairlines' %}" method="POST"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-success" formaction="{% url 'addairlines' %}">Submit</button> <button class="btn btn-primary" formaction="{% url 'airlines' %}">Cancel</button> </form>