Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a many-to-many relationship after save in django?
I'm trying to build a simple ToDo app in django: A 'box' contains multiple 'tasks', has an 'owner' (the person who created the box and has administrative privileges) and multiple 'users' (persons who can access the box and add/edit tasks). I want to automatically add the owner to the users set. I've tried this multiple ways: Overwriting the save(): class Box(models.Model): owner = models.ForeignKey(User, related_name='boxes_owned', on_delete=models.CASCADE, null=True, blank=False) users = models.ManyToManyField(User, related_name='boxes_assigned') title = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) def save(self): super().save() self.users.add(self.owner) This does not work and neither does working with a post-save signal. @receiver(post_save, sender=Box) def update_box(sender, instance, **kwargs): instance.users.add(instance.owner) The owner won't be added to the users set. What am I doing wrong, how can I fix this? Is this the right approach at all? -
Django: order_by column from another table
I am building a forum and have the next model for messages: class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=100000) date_publication = models.DateTimeField(auto_now_add=True) class Discussion(Message): title = models.CharField(max_length=500) views = models.PositiveBigIntegerField(default=0) class Response(Message): topic = models.ForeignKey(Discussion, on_delete=models.CASCADE) reply_to = models.ForeignKey( Message, on_delete=models.CASCADE, related_name='message_replied', null=True) I wonder how can I get a list of Discussions order_by date_publication from Response. -
Trouble with urls mapping to view functions in Django
I want to group all of my URLs within my todo list app into the project/todolist/urls.py file. So I have a button and a String field where you can add the item to the list, and when you push the button it should send the string to the data model and redirect back to the homepage with the updated list. This works when I have all of the urls placed in the project/urls.py file like below: urlpatterns = [ url(r'^admin/', admin.site.urls), url('todo_list/', include('todolist.urls')), url('addItem/', addItem), url('deleteItem/(?P<i>[0-9]+)', deleteItem) ] But I wanted to use the include() function instead and group all of the add, delete and todo_list views into a single file in project/todolist/urls.py. But when I do this I get Page not found errors and such: Using the URLconf defined in test_django.urls, Django tried these URL patterns, in this order: ^admin/ todo_list/ The current path, addItem/, didn’t match any of these. Below is the code that is throwing the error. I have tried to change things in the html template so that the form action goes to /todo_list/addItem/ instead of /addItem/, but this for some reason doesn't solve the problem. *** project/todolist/urls.py *** from django.urls import path from . import … -
Ubuntu : FATAL : can't find command '/home/ubuntu/env/bin/gunicorn'
I am trying to set up my gunicorn config file for my Ubuntu server , however I keep running into a guni:gunicorn FATAL can't find command '/home/ubuntu/env/bin/gunicorn' error when trying sudo supervisorctl status Here is the config files code: [program:gunicorn] directory=/home/ubuntu/spookie command=/home/ubuntu/env/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/spookie/app.sock spookie.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn I have tried whereis gunicorn and it does return the /env/bin/gunicorn file I have tried ls /home/ubuntu/env/bin/gunicorn and that gives an error stating that the directory doesn't exist -
Django Import Export, Filter ForeignKey objects connected to users
I'm building an import excel files system for every leads whit import export library. In the Website each user must be able to import his leads and make sure that they are viewed only by him. In all other cases I filtered the "organisation" field linked to a UserProfile model through the views.py. But now I don't know how to filter the field organisation for a specific user.At the moment I can import the excel files from the template but leaving the organisation field blank. Help me please I'm desperate Models.py class Lead(models.Model): nome = models.CharField(max_length=20) cognome = models.CharField(max_length=20) luogo=models.CharField(max_length=50, blank=True, null=True, choices=region_list) città=models.CharField(max_length=20) email = models.EmailField() phone_number = models.CharField(max_length=20) description = models.TextField() agent = models.ForeignKey("Agent", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="leads", null=True, blank=True, on_delete=models.SET_NULL) chance=models.ForeignKey("Chance",related_name="chance", null=True, blank=True, on_delete=models.CASCADE) profile_picture = models.ImageField(null=True, blank=True, upload_to="profile_pictures/") converted_date = models.DateTimeField(null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) organisation = models.ForeignKey(UserProfile, on_delete=models.CASCADE,null=True, blank=True) objects = LeadManager() age = models.IntegerField(default=0) def __str__(self): return f"{self.nome} {self.cognome}" class User(AbstractUser): is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username Views.py def simple_upload(request): if request.method == 'POST': Lead_resource = LeadResource() dataset = Dataset() newdoc = request.FILES['myfile'] imported_data = dataset.load(newdoc.read(),format='xlsx') #print(imported_data) for data in imported_data: … -
How to return an array inside of a function?
I created a class in my Django project and I call it from views. I need a result of a function in this class but I cannot return the array. I tried to equalize a array from outside but it returns: <module 're' from 'C:\\Users\\edeni\\AppData\\Local\\Programs\\Python\\Python39\\lib\\re.py'> How can I use this array in my views? views.py def setup_wizard(request): ... functions.myClass(setup.n_username, setup.n_password, setup.n_url, setup.n_port, setup.db_password, username=request.user.username) **functions.py** class myClass(): def __init__(self, n_user, n_password, n_url, n_port, db_password, username): ... self.elastice_yolla(username) ... def elastice_yolla(self, username): self.report_final = [] array_length = len(glob.glob(self.location + "\*\*.nessus")) self.static_fields = dict() for in_file in glob.glob(self.location + "\*\*.nessus"): try: i = 0 with open(in_file) as f: if os.path.getsize(in_file) > 0: np = NES2(in_file, self.index_name, self.static_fields, username) report_final = np.toES() time.sleep(0.02) i = i + 1 except: pass print("report") print(report_final) class NES2: def __init__(self, input_file, index_name, static_fields, username): .... def toES(self): ... for ... for ... try: if bas['cve']: self.es.index(index=self.index_name, doc_type="_doc", body=json.dumps(bas)) rep_result.append(json.dumps(bas)) except KeyError: pass -
How do I get more details from uWSGI process Segmentation Fault?
I decided to follow the "uwsgi, Django, and nginx tutorial"; But I didn't get too far before I received a segmentation fault message. I can't seem to figure out how to get more details. How do I get more details from uWSGI process Segmentation Fault? Here are the steps to help reproduce the same issue. Tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html Setup OS: alpine3.13 Python: 3.10 Django: 3.2.9 Dockerfile: https://github.com/docker-library/python/tree/8e591562e4e9ea0c2ab27d428918007abbc688a1/3.10/alpine3.13 RUN apk update && apk add gcc musl-dev python3-dev libffi-dev libressl-dev cargo bash vim && \ apk add pcre pcre-dev supervisor openssl curl ca-certificates nginx && \ pip install --upgrade pip && \ pip install Django==3.2.9 && \ pip install -I --no-cache-dir uwsgi After starting up the container and logging into it: git clone https://github.com/do-community/django-polls.git cd django-polls/ uwsgi --http :8000 --module mysite.wsgi The output and No details to the Segmentation Fault *** Starting uWSGI 2.0.20 (64bit) on [Sun Nov 14 18:30:03 2021] *** compiled with version: 10.2.1 20201203 on 14 November 2021 08:43:40 os: Linux-5.10.47-linuxkit #1 SMP Sat Jul 3 21:51:47 UTC 2021 nodename: 39e77de2e1ed machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: /app/django-polls detected binary path: /usr/local/bin/uwsgi uWSGI running as root, you can use … -
How can i do, When user come my site than show "page is UnderConstruction"?
I went to do, whan any user come my wabsite than only one url/view show him page is UnderConstruction ???? I know full site UnderConstruction but don't only one page ..... This is my middelware.py:- class UnderConstruction: def __init__(self,get_response): self.get_response = get_response def __call__(self,request, *args, **kwargs): response = reverse("about") return response I went to show him only about view so, i provide only about views views.py:- from .middelware import UnderConstruction from django.utils.decorators import decorator_from_middleware @decorator_from_middleware(UnderConstruction) def about(request): return render(request, 'blog/about.html') setting.py:- By the way my app name is blog 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', #.......This middelware for site UnderConstruction........# 'blog.middelware.UnderConstruction' ] urls.py:- path('base/', base, name='base'), So, i think i went to change/add in middelwaer.py file , i don't understand what need plz help anyone.... Thanks.... -
How to handle login API in Django web app
I have already implemented a list of shop API including user api, product api etc using Rest Framework. User api include basic login/logout/register methods. Login require username and password, so API call looks like requests.post('api/api_user/login', {username='name', password='password'}). Post method returns auth token like following: Post result The issue is how can i handle @login_required in web app using my API. The idea of login is intuitive, i can send post request and get token which can be stored in cookies, but Django use it's own authentication system to handle user login on viewes (@login_required decorator), so i left with an idea to get token from cookies in every request and check it for correctness, but is it right way to do such things? I'm looking for examples or suggestions how this thing should be implemented. -
I don't understand why! show me that error local 'variable referenced before assignment' Django?
I don't understand why! show me that error local 'variable referenced before assignment' Django? it works fine till the homeTeam, awayTeam, referees that i cant pass in results dict. i tried some solutions like using variable as GLOBAL but fails. def my_api(request): matches = Matches.objects.all().prefetch_related('score', 'homeTeam', 'awayTeam', 'referees').order_by('-id') all_results = [] for match in matches: # Works fine id = match.id utcDate = match.utcDate status = match.status matchday = match.matchday stage = match.stage group = match.group lastUpdated = match.lastUpdated for score in match.score.all(): #Works fine sco = {} sco['winner'] = score.winner sco['duration'] = score.duration sco['fthomeTeam'] = score.fthomeTeam sco['ftawayTeam'] = score.ftawayTeam sco['hthomeTeam'] = score.hthomeTeam sco['htawayTeam'] = score.htawayTeam sco['exthomeTeam'] = score.exthomeTeam sco['extawayTeam'] = score.extawayTeam sco['phomeTeam'] = score.phomeTeam sco['pawayTeam'] = score.pawayTeam for homeT in match.homeTeam.all(): # Here is the problem local variable 'hometeams' referenced before assignment hometeams = { # i can't pass this variable to result 'id': homeT.id, 'name': homeT.name, } #hometeams['id'] = homeT.id #hometeams['name'] = homeT.name for awayT in match.awayTeam.all(): # Here is too problem awayteam = {} awayteam['id'] = awayT.id awayteam['name'] = awayT.name for referees in match.referees.all(): # And here too problem refer = {} refer['id'] = referees.id refer['name'] = referees.name refer['role'] = referees.role refer['nationality'] = referees.nationality result = { … -
Why am I getting name 'request' is not defined?
I'm following a Django tutorial and have reached the point of using return renderand currently my views.py looks like this: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def construction_view(*args, **kwargs): return HttpResponse("<h1> This site is currently being constructed. Please check back later </h1>") def home_view(*args, **kwargs): return render(request, "home.html", {}) I am getting an error whien trying to go to my home page: views.py", line 9, in home_view return render(request, "home.html", {}) NameError: name 'request' is not defined Not sure what is causing this as according to Django docs request is part of render which is imported above. -
Django annotate Count over queryset results
Let's imagine the next model: class Product(models.Model): name = models.CharField(max_lenght=255) category = models.ForeignKey(Category, ...) type = models.ForeignKey(Type, ...) platform = models.ForeignKey(Platform, ...) [...] Users can filter by every ForeignKey__id field and the filtered queryset is used to construct a dynamic filter for the frontend with next structure: "filter": { "categories": [ { "category__id": 1, "category__name": "videogames", "total": 12 }, { "category__id": 2, "category__name": "funkos", "total": 3 } ], "types": [ { "type__id": 3, "type__name": "accessory", "total": 2 }, { "type__id": 2, "type__name": "console", "total": 4 } ] } Where total is the number of Products associated with each category, type, etc.. The values are calculated as following: categories = queryset.values('category__id', 'category__name').annotate(total=Count('id')) queryset can also be filtered by, for example, products with a price grater than 25.00$. Is there any way to get the total field value (currently annotate(total=Count('id'))) based on queryset values, not on database values? -
How do I create a queue of records in django?
In general, when I experimented with the capabilities of Django, I had a question how I can add a queue for model records, for example, I have a couple of blocks and I need to display the model that was registered first and on the second block it should be displayed next entry. How can I do this? here is an example query_set class IndexView(generic.ListView): template_name = 'article/sale.html' model = Goods context_object_name = 'goods' def get_queryset(self): return Goods.objects.order_by('-pub_date')[:1] In html, I output the entry like this {% for good in queryset %} <h1 class="price" >{{ good.price2_text }}</h1> {% endfor %} this is code of models.py class Goods(models.Model): description_text = models.CharField(max_length=200) price_text = models.CharField(max_length=200) image_sale = models.ImageField(blank=True, upload_to='images/') description1_text = models.CharField(max_length=200) price1_text = models.CharField(max_length=200) image1_sale = models.ImageField(blank=True, upload_to='images/') description2_text = models.CharField(max_length=200) price2_text = models.CharField(max_length=200) image2_sale = models.ImageField(blank=True, upload_to='images/') pub_date = models.DateTimeField('date published') def __str__(self): return self.description_text def __str__(self): return self.price_text def __str__(self): return self.description1_text def __str__(self): return self.price1_text def __str__(self): return self.description2_text -
How to get selected <div> from loop of multiple <divs> in Django template
I want to make a entry into the database using a button for which I have an event listener which is getting the data and making a ajax request. My code looks like this: home.html -> {% for fig in user_figs %} <div class='card'> {% if fig.chart %} <input type="hidden" id="card_chart" value="{{ fig }}"> <input type="hidden" id="card_filter_id" value="{{ fig.filter_id }}"> {{ fig.chart|safe }} {% endif %} </div> {% endfor %} model looks like this: class Card(models.Model): filter_id = models.CharField(max_length=120) title = models.CharField(max_length=120) chart = models.TextField() profile = models.ForeignKey(Profile, on_delete=models.CASCADE) dashboard = models.ForeignKey(Plot, on_delete=models.SET_NULL, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if(len(self.filter_id) == 0): self.filter_id = str(uuid.uuid1()) super(Card, self).save(*args, **kwargs) def __str__(self): return f"Card title: {self.title} Card id: {self.filter_id}" The event listener in JS looks like this: save_changes_button.addEventListener('click', ()=>{ console.log("SAVE CHANGES BUTTON CLICKED") const card_id = document.getElementById('card_filter_id').value console.log(card_id) const form_data = new FormData() form_data.append('csrfmiddlewaretoken', csrf_token) form_data.append('name', name_of_dashbaord) form_data.append('title', title) form_data.append('chart', fig) form_data.append('card_id', card_id) $.ajax({ type: 'POST', url: '/card/save/', data: form_data, success: function(response){ console.log(response) }, error: function(error){ console.log(error) }, processData: false, contentType: false, }) }) now when user clicks the button, I want to make an entry into the database which looks like this: def create_card_view(request): if(request.is_ajax()): name … -
Python 3 and Django: write Georgian text to PDF file
The problem was to write Georgian text to PDF file. I have tried several encodings, however, this didn't solve the problem. Also I tryd to use some fonts, but it hasnot any goal. I need help.. i use xhtml2pdf modul def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') customer = get_object_or_404(id, pk=pk) template_path = 'test.html' context = {'customer': customer} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename= "report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, encoding='utf-8' ) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response -
Django- some images are missing sometimes can you help me
On the website I made with Django, I take 6 photos from the database from the same object, but while projecting them to html, some of them are missing from time to time. Can you help me? Below one is my codes Urls.py Here my url,settings,view and html code from django.urls import path, include, re_path from . import views from django.conf import settings from django.conf.urls.static import static from django.views.static import serve urlpatterns = [ path('', views.index, name='index'), path('signin',views.signin, name='signin'), path('register',views.register, name='register'), path('answers', views.answers, name='answers'), path('logout',views.logout,name='logout'), path('help',views.help,name='help'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,}),] Settings.py STATIC_URL = '/static/' STATIC_ROOT = '/home/static' STATICFILES_DIRS = (os.path.join(BASE_DIR,'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = '/home/media' MEDIA_DIRS = (os.path.join(BASE_DIR,'media'),) views.py questionlist = [] answerlist = [] if(each.questionimg != ""): questionlist.append(each.questionimg) if(each.questionimg2 != ""): questionlist.append(each.questionimg2) if(each.questionimg3 != ""): questionlist.append(each.questionimg3) if(each.answer != ""): answerlist.append(each.answer) if(each.answer2 != ""): answerlist.append(each.answer2) if(each.answer3 != ""): answerlist.append(each.answer3) if(each.answer4 != ""): answerlist.append(each.answer4) if(each.answer5 != ""): answerlist.append(each.answer5) flag = False context = { "questionlist": questionlist, "answerlist": answerlist} return render(request,'answers.html',context) ``` Html {% for questionphoto in questionlist %} <img src="media/{{ questionphoto }}" class="img-fluid"> {% endfor %} -
Django - Replace model fields values before save
Just to note: I know about overwriting Model's .save() method but it won't suit me as I explained it at the end of my question. In one of my projects, I've got more than of 30 database Models and each one of these models accept multiple CharField to store store Persian characters; However there might be some case where users are using Arabic layouts for their keyboard where some chars are differ from Persian. For example: The name Ali in Arabic: علي and in Persian: علی Or even in numbers: 345 in Arabic: ٣٤٥ And in Persian: ۳۴۵ I need to selectively, choose a set of these fields and run a function on their value before saving them (On create or update) to map these characters so I won't end up with two different form of a single word in my database. One way to do this is overwriting the .save() method on the database Model. Is there any other way to do this so I don't have to change all my models? -
Django Admin change/modify the text "Add another" for inlines
In Django Admin, how can you change the text "Add another" for inlines? I am not referring to the object name ("Add another ObjectName"), that you can change with "verbose_name". I am referring to the words "Add another". For example to change "Add another Company" to "Include Company". I found that i can override directly the django/contrib/admin/helpers.py file. However it is not the best possible solution. What is the best/correct way to override helpers.py file? Where do i put the new helpers.py file? What other option are there to modify the text "Add another"? -
Django 'jsonify' is not a registered tag library. Must be one of:
I am working on a django project where Installed a package called jsonify which is to be used in the django template from https://pypi.org/project/jsonify/ & added in the installed apps: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "jsonify", "main", ] In my local environment it works just fine but when I deployed to heroku I keep 'jsonify' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static to_and tz Also note I have also made my own custom template tag "to_and" which works perfectly fine. This only happens in production in heroku and not in my local envirnoment. Thanks in advance -
How to put button value to database Django
do you have some tips how to put buttons values to the Django sqlite database? I have a page with some buttons with theirs values and some final button, which would send the buttons values to the database after the final button click. Thanks. -
Regex: how to extract incomplete date and convert
How can I get a date that may not contain the month or the day? Right now I only know how to break the date date_n= '2022-12' match_year = re.search(r'(?P<year_only>(?P<year>\d+))', date_n) match_month = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+))', date_n) match_day = re.search(r'(?P<whole_date>(?P<year>\d+)-(?P<month>\d+)-(?P<day>\d+))', date_n) year = match_year.group('year_only') month = match_month.group('month') day = match_day.group('day') Try and Except does not work. -
How to add my TimedRotatingFileHandler to django logger?
I'am actually using my own logger (tools\logger.py) : ... logger = logging.getLogger("MyPersonalLogger") ... fh = handlers.TimedRotatingFileHandler( os.path.join(LOG_DATA_PATH, '{:%Y-%m-%d}.log'.format(datetime.now(tz=ZoneInfo("Europe/Paris")))), when='midnight', interval=1, backupCount=30, encoding='utf-8', delay=False, utc=False, atTime=None, errors=None) formatter = logging.Formatter('%(asctime)s | %(levelname)-8s | %(name)-8s | %(module)-8s | %(message)s', datefmt='%H:%M:%S') formatter.converter = lambda *args: datetime.now(tz=ZoneInfo("Europe/Paris")).timetuple() fh.setFormatter(formatter) logger.addHandler(fh) In django I'am trying to add my handler fh to the django logger without success... in settings.py import logging import tools.logger LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': {... }, 'handlers': {... }, 'loggers': { 'django': { 'handlers': ['console'], #defined in handlers up 'level': "DEBUG", 'propagate': True, } } } # ADDING my_logger = logging.getLogger('django') my_logger.addHandler(tools.logger.fh) And it doesn't work. Logging on console for django is working but clearly not for my TimedRotatingFileHandler fh. -
If-In statements not working as intended in Django Templates
I am trying to execute the following in python in a .html file in a Django environment: {% if data.author in s.suscriptions %} <p>Print this statement</p> {% endif %} data.author -> Johnny s.suscriptions -> JohnnySarahMatt In this code, data.author is just a string so upon testing data.author = Johnny. s.suscriptions is another string and will have an output something like JohnnySarahMatt. According to Django Documentation the in operator should work. But it is not, I can't locate what the issue actually is. I am a bit new to Django so I need some help on this. -
Django forms: Referecing variable defined in views def as placeholder within forms
I'm using Django and trying to reference a 'topic' available within a def in views as a placeholder that I had referenced from a url. In the code below, 'Replace this' should show the content of 'topic' as defined in 'def editpage(request, topic)' but I cannot seem to get the reference to work. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import forms from . import util class EditPageForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Replace this', 'class': 'form-control'})) def editpage(request, topic): return render(request, "encyclopedia/editpage.html", {"form": EditPageForm(), "topic":f"{topic}" }) My attempt was to swap 'Replace this' with f'{topic}', but it does not appear to work. from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import forms from . import util class EditPageForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': f'{topic}', 'class': 'form-control'})) def editpage(request, topic): return render(request, "encyclopedia/editpage.html", {"form": EditPageForm(), "topic":f"{topic}" }) Instead, I get an error that 'topic' is not defined. Thanks in advance! -
Not able to access fields inside Div in Django forms
What works fine <form action = "{% url 'dashboard'%}" method = "POST"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name"> <input type="submit" value="OK"> </form> What does NOT work... <form action = "{% url 'dashboard'%}" method = "POST"> {% csrf_token %} <div class="col-lg-3 col-md-3 col-sm-12 p-0"> <input type="text" id="cve" class="form-control search-slt" placeholder="Enter CVE"> <input type="submit" value="OK"> </div> </form> Whenever I have values inside DIV tag, inside a form, The POST request does not contains values of DIV fields.