Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to be able have a form input and display variables on the same page in django html python?
I was wondering how you would be able to take in inputs, and display a different set of read only variables on the same page using django with python and jinja and html. Currently, I am able to display a set of variables on one page and read a different set of inputs on a different page. I want to accomplish both on the same age, but when I return a render in the views.py file I am unable to do both on the same page. Constraints: Python Django Jinja Html Javascript Css -
How to populate a column in Django from Views.py?
My task is to insert data into a database with 4 columns and those are: class Userdata(models.Model): childname = models.CharField(max_length= 100) age = models.IntegerField() gender = models.CharField(max_length=6) action = models.TextField() Data to be inserted into the Database is being received from a form only for columns childname, age, gender. The column "Action" is supposed to have a downloadable URL for each row. I am receiving the parameters except for Action from the form using the request.GET function. In order to create a downloadable URL I am planning to use: <a href="<path>" download> </a> But in Views.py I can't write an HTML code and insert into a DB. For insertion I am using model_name.save() Is there a way to create a downloadable link in python or How do I populate my Actions column? -
Defining FastCGI directives as part of WSGI
I'm using flup to run Python on FastCGI. I want to change FCGI directives (for example FcgidMaxRequestsPerProcess). How do I change it? Here is my code #!/home/user1/.venv/python import os, sys from flup.server.fcgi import WSGIServer from django.core.wsgi import get_wsgi_application sys.path.insert (0, "/home/user1/website") os.environ ['DJANGO_SETTINGS_MODULE'] = "myproject.settings" WSGIServer(get_wsgi_application()).run() -
Django datatable view load and CRUD operations
I want to use django datatable-view with my Product model and apply search and filter with category also i want to add, create and delete product from table. i can't do any cause my url open page with Json response and i want to load all model data in my template page, how can do that. my model file `class Product(models.Model): name = models.CharField(blank=True, max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True)` #my view from django_datatables_view.base_datatable_view import BaseDatatableView from .models import Product class OrderListJson(BaseDatatableView): model = Product template_name = 'test.html' columns = ['name', 'category', 'price', 'created', 'updated'] order_columns = ['name', 'category', 'price', 'created', 'updated'] max_display_length = 500 def filter_queryset(self, qs): search = self.request.GET.get('search[value]', None) if search: qs = qs.filter(name__istartswith=search) return qs #my template file <body> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>name</th> <th>category</th> <th>price</th> <th>created</th> <th>modified</th> </tr> </thead> </table> <script type="text/javascript"> $(document).ready(function() { var oTable = $('.example').dataTable({ // ... "processing": true, "serverSide": true, "ajax": "{% url 'product_list' %}" }); // ... }); </script> </body> #my url file path('', login_required(views.OrderListJson.as_view()), name='order_list_json'), -
show comments to unique to specific blog post
I want to show comments unique to the blog post on each blog post but when I click submit on the comment posting form it throws an error saying IntegrityError at /post/6/comment/ NOT NULL constraint failed: blog_postcomment.Post_id I add comments in the database manually but it doesn't show on my page. HTML {% block content %} <div class="container"> <div class="row"> <div class="col-md-8 card mb-4 mt-3 left top"> <div class="card-body"> {% if comment_list %} <h2 class="post-title">Comments</h2> {% for comment in blog_postcomment.post %} <p class=" text-muted">{{ comment.author }} | {{ comment.post_date }}</p> <p class="card-text ">{{ comment.description | safe }}</p> {% endfor %} {% endif %} </div> </div> </div> </div> {% block content %} model class PostAuthor(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) bio = models.TextField(max_length=400, help_text="Enter your bio details here.") class Meta: ordering = ["user", "bio"] def get_absolute_url(self): return reverse('post-by-author', args=[str(self.id)]) def __str__(self): return self.user.username class Post(models.Model): title = models.CharField(max_length=200, unique=False) slug = models.SlugField(max_length=200, null=True, blank=True) author = models.ForeignKey(PostAuthor, on_delete=models.CASCADE, null=True, blank=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) def __str__(self): return self.title class PostComment(models.Model): description = models.TextField(max_length=1000, help_text="Enter your comment here.") author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, … -
Can't identify problem in my serializers.py file
I can't figure out why I'm getting errors. If I don't import the serializers.py file then the error goes (my views don't yet make use of this file). Serializers.py: from rest_framework import serializers # This file is the equivilent of forms.py in that we define models to serialise. class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) logo = serializers.URLField(max_length=250, required=False) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True, min_value=0) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) is_load = serializers.BooleanField() settled = serializers.DateTimeField() merchant = serializers.ListField(child=MerchantSerializer) class TransactionSerializer(serializers.Serializer): type = serializers.CharField(required=True, max_length=50) data = serializers.ListField(child=DataSerializer) My view isn't doing anything yet. Plan was to just receive some JSon to create my webhook, validate the JSON and then save the data. The JSON contains objects that span several models and the field names won't match the models so I don't think I can use any model serializers. Views.py: from django.shortcuts import render from django.contrib.auth.models import User from rest_framework import viewsets from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json import datetime from .models import Transaction from .serializers import TransactionSerializer #Enable logging import logging logger = logging.getLogger(__name__) … -
Validate Json in Django - Django Rest Framework
I need to validate the following JSON: { "monday": [ //List of MyClass object ], "tuesday": [ //List of MyClass Object ], "wednesday": [ //List of MyClass Object ], ...... } I need to check if it contains any key that is not a day of the week (mondai, thudai for example). Also MyClass is defined as: class MyClass(models.Model): type = models.CharField(unique=True, max_length=20) value = models.IntegerField() The fieldvalue must be a positive integer and cannot exceed 10000. Also, type must be either cost or benefit In Scala I would use the following: object MyClass { val ALLOWED_TYPES = Seq[String]("cost", "benefit") implicit val openingHourReads: Reads[OpeningHour] = ( (JsPath \ "type").read[String].filter(JsonValidationError("Type must be cost or benefit"))(ALLOWED_TYPES.contains(_)) and (JsPath \ "value").read[Int](min(1).keepAnd(max(10000))) )(MyClass.apply _) Is there an equivalent approach in Django? -
Extracting all the APIs paths/urls for Django Rest Framework
We want to discover/extract a list of new APIs between two releases. Is there a way to parse and extract a list of API URLs and HTTP-methods to have this list of new APIs when comparing release code branches? -
File not saving django
I'm generating a docx file with user input and trying to upload the file with File method but neither it gives an error nor it saves the file. views.py def schoolinput_view(request): if request.method == 'POST': worddocument = docx.Document() school_name_view = request.POST.get('school_name') documenttitle = worddocument.add_heading(school_name_view.title(), 0) path = join(settings.MEDIA_ROOT, 'word_documents','quicktimetable.docx') documentfile = Timetables() if request.user.is_anonymous: pass elif request.user.is_authenticated: documentfile.user = request.user document = File(path, worddocument) documentfile.save(document) models.py class Timetables(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1, related_name='timetables_files', null=True, blank=True) timetable_files = models.FileField( null=True, blank=True, upload_to='word_documents') The word file it's generating is not saving in the file storage. However in the admin panel it shows number of objects created in Timetables and the user for the files is also correct. What am I doing wrong? -
Dynamic view for creating a model entry that involves ForeignKeys and ManyToMany relationships
Consider the following Django models: class Agent(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Report(models.Model): date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='reports', ) # just the Django User creating the Report agent = models.ForeignKey( Agent, on_delete=models.CASCADE, related_name='reports', ) # Agent which the Report is about body = models.TextField() class Objective(models.Model): agent = models.ForeignKey( Agent, on_delete=models.CASCADE, related_name='objectives', ) # Agent who has this Objective reports = models.ManyToManyField(Report, related_name='reports') body = models.CharField(max_length=255) The intended relationship here is that Agents can have multiple Objectives, and a Report can relate to a single Agent, but any number of that Agent's Objectives. My issue comes with creating a view/template/form in order to create a new Report. What is a good approach for creating a page that: has a dropdown to select an Agent (trivial part on its own; just use a ModelForm with model = Report) then has that Agent's Objectives populate on the page so that an arbitrary number of them can be selected (at least one is required, though) and then once the form is submitted, the new Report is saved in each Objective's "reports" ManyToManyField relationship? I'm relatively new to Django, so I'm completely unsure the approach to take here, … -
What is the best way to get user-info from Authentication server (Django OAuth)?
I'm using django-oauth-toolkit and djangorestframework with separated Resource and Authentication servers. On Authentication server there is all user registration data. I need all user-info (including first_name and last_name) on my Resource server too. But django-oauth-toolkit's methods send only token with username. What is the best way to get/sync user-info from Authentication server to Resource server? -
Typeerror at/10 my_view() got an unexpected keyword argument 'pk'
i am getting a typeerror my_view() got an unexpected keyword argument 'pk' views.py ```def my_view(request): prod = get_object_or_404(Products, pk=1) context = { 'prod': prod, } return render(request, 'title.html', context) ``` `urls.py` ```urlpatterns = [ path('search/', views.search, name='search'), path('<int:pk>', views.my_view, name='my_view'), path('', views.index), ]``` my template when i make a search {% if results.products %} {% for product in results.products %} <div class="col-sm-{% column_width results.products %} pb-5"> <div class="card"> <div class="card-header bg-default" align="center"> <b>{{product.title}}</b> </div> <div class="card-body"> <a href="{% url 'my_view' product.id %}">{{ product.Author }}</a> <p>{{ product.description|striptags }}</p> <h6 class="btn btn-primary btn-large">{{product.price}}</h6> </div> </div> </div> {% endfor %} {% endif %} my template to render when making a click on one of the search ``` {{ prod.title }} {{ prod.description }} <h6 class="btn btn-primary btn-large">{{judi.price}}</h6> <h6 style="float: right;">{{judi.modified_date}}</h6> </div> </div> </div> ``` -
How to do pagination in list method with multiple sorted serializers django rest framework views
I am trying to combine two serializers(Post and PostShare) in in one single view to show in my feeds. Here is my View class PostAPIView( mixins.CreateModelMixin, generics.ListAPIView, ObjectMultipleModelAPIView, mixins.ListModelMixin, ListView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = PostSerializer # filter_backends = [filters.OrderingFilter,filters.SearchFilter, django_filters.rest_framework.DjangoFilterBackend] # filter_fields = ['author'] # search_fields = ['content','author'] # ordering_fields = ['created_at'] # ordering = ['-created_at'] pagination_class = LimitOffsetPagination # pagination_class = LimitPagination default_limit = 2 # # paginate_by = 2 # # page_size=2 # #queryset = Post.objects.all() def list(self, request, format = None, **kwargs): posts = Post.objects.all() post_shares = PostShare.objects.all() serializer_post = PostSerializer(posts,many=True).data serializer_post_share = PostShareReadSerializer(post_shares,many=True).data # rr=sorted(list(chain(posts,post_shares)), key=lambda x: x.created_at,reverse = True) # print(rr) result_lst = sorted(serializer_post + serializer_post_share, key=lambda x: x.get('created_at'),reverse = True) print(result_lst) # page = self.paginate_queryset(result_lst,2) # paginator_request_var = "page" # page = request.GET.get(paginator_request_var) # posts = paginator.get_page(page) # return Response(result_lst_page,context) # print(result_lst) # return self.get_paginated_response(result_lst) return Response(result_lst) This is not working in get_queryset so I put it in list method but this is not showing me pagination. Is there any way I can paginate my result? or any other approach to combine these querysets and serializers with pagination? -
Filtering based on a foreign key in Django
I'm trying to filter a table based on a value in another table, via a foreign key. trench_id = models.ForeignKey(Trench, db_column='trench_id', on_delete = models.PROTECT) As above, the Context model joins to the Trench model via trench_id__trench_id I want to access trench.name as you can see below I'm then using this value in a filter. I include the views.py code and for reference my models.py. def allcontexts(request): allcontexts = Context.objects.filter(trench_id__trench_id__name=request.session.get("name")) return render(request, 'context_manager/context_manager.html', { 'allcontexts':allcontexts, }) I'm getting the following error Unsupported lookup 'name' for AutoField or join on the field not permitted. models.py class Trench(models.Model): trench_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) area_easting = models.IntegerField() area_northing = models.IntegerField() def __str__(self): return str(self.name) class Context(models.Model): context_id = models.AutoField(primary_key=True) trench_id = models.ForeignKey(Trench, db_column='trench_id', on_delete = models.PROTECT) number = models.IntegerField() type = models.CharField(max_length = 50, blank=True, null=True) description = models.TextField(blank=True, null=True) excavation_method = models.CharField(max_length = 50, blank=True, null=True) open_date = models.DateField(blank=True, null=True) close_date = models.DateField(blank=True, null=True) excavated_by = models.CharField(max_length = 50, blank=True, null=True) area_easting = models.IntegerField() def __str__(self): return str(self.number) -
How to structure template libraries in a Django project?
I'm in the early innings of the development process and am trying to figure out best practices for structuring the template libraries for a website. I plan to have a "base" template to extend across the site. I have seen some examples where a template directory is created at the project level to house this file, and others where a "base" file is created in one of the app folders and then extended to other apps as needed. Is there a correct way this should be done? Thank you in advance for humoring me on this extremely basic question. Trying to get my feet under me for the first time. -
Django Model.py Q: Have tow class is foreignkey.The class how can get CharField of another class
My model.py Have tow class,the Goods class have CharField,the pictuers class is save pictures. The Goods class can save name (Chinses words),the another class can transform name into pinyin The question is I can't get name for pictures class. from django.db import models from uuid import uuid4 from xpinyin import Pinyin import re class Goods(models.Model): goods_sort = models.ForeignKey(Goods_Sort,related_name='Goods_GoodsSort',on_delete=models.CASCADE,verbose_name='分类',default='1') goodsname = models.CharField('商品',max_length=20) def __str__(self): return self.goodsname class Goods_Pictures(models.Model): goods_name = models.ForeignKey(Goods,related_name='GoodsPictures_Goods',on_delete=models.CASCADE,verbose_name='商品图片',default='1') def goodspictuer_path(goodsname,filename): def match_zhcn_change(goodsname): p = Pinyin() if str(goodsname) >= u'\u4e00' and str(goodsname) <= u'\u9fa5': return p.get_pinyin(str(goodsname),'') else: return str(goodsname) postfix = re.findall(r'\.[a-z]+[a-z]+[a-z]',filename) path = '{0}/{1}{2}'.format(match_zhcn_change(goodsname),uuid4().hex,postfix) return path goodpictuer_file = models.ImageField('商品图片',upload_to=goodspictuer_path)``` -
Can't load bootstrap css file
I'm creating a django project in pycharm and I'm trying to use bootstrap blog example(https://getbootstrap.com/docs/4.4/examples/blog/). I came across a problem: bootstrap.min.css file is not working properly, when I link it like this it works properly, <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> but when I download this file then save it in my_app/static/my_app/bootstrap.min.css and link it like this, <link rel="stylesheet" href="{% static 'blogs/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> it doesn't work, the django development server is properly loading the css file [14/Jan/2020 19:04:26] "GET /static/blogs/bootstrap.min.css HTTP/1.1" 304 0 but it just doesn't have any effect on the site apperance, the blog.css file does have effect as I can see fonts and a few thing change but the bootstrap.min.css file just doesn't. -
JavaScript Readonly Attribute Not Working
I have in my code to make a field readOnly, however it just grays the field out and the field can still be edited. What am i doing wrong here ? The fields I'm using in this are Django crispy fields on my form. Code For The Form <form action="" method="POST"> {% csrf_token %} <div class="row"> <div class="col-3"> {{form.class_name|as_crispy_field }} </div> <div class = "col-3"> {{form.date|as_crispy_field }} </div> <div class = "col-3"> {{form.week_of|as_crispy_field }} </div> <div class = "col-3"> {{form.day|as_crispy_field }} </div> </div> <div class="row"> <div class="col-3"> {{form.student_name|as_crispy_field }} </div> <div class = "col-3"> {{form.time_frame|as_crispy_field }} </div> <div class = "col-3"> {{form.behavior|as_crispy_field }} </div> <div class="col-3" > {{form.academic|as_crispy_field }} </div> </div> <div class="row"> <div class = "col-3"> <button type="submit" class="btn btn-success" ><i class="fas fa-star"></i> Level Up</button> </form> </div> </div> </div> <script> const student_name = "{{student_id}}"; var studentnamedropdown = document.getElementById('id_student_name'); for (i = 0; i < studentnamedropdown.options.length; i++) { // if(studentnamedropdown.options[i].text == "Ray Zuchowski") if(studentnamedropdown.options[i].text == student_name) { console.log(studentnamedropdown.options[i].text) $("#id_student_name").val(studentnamedropdown.options[i].value) $("#id_student_name").attr('readonly', 'readonly') } } </script> -
Django filtering in views.py with a session variable
I sessions up and running and currently I'm getting the variable 'context_number' set in the browser. In the view I would like to filter on this variable. So I have this in my views.py. def allcontexts(request): allcontexts = Context.objects.all() return render(request, 'context_manager/context_manager.html', { 'allcontexts':allcontexts, }) In order to filter I change the second row to the following allcontexts = Context.objects.filter(context_number=____) In the blank I want to insert the context_number variable, so context_number[dbcolumn] = context_number[session variable] I can't seem to figure out the correct syntax, any ideas? -
Setting up Telegram Bot with Django as webhook+Nginx+guincorn on CentOS 7
I want to setting up my Telegram bot that I was developed with python-telegram-bot library on CentOS 7 VPS with using Nginx as reverse proxy and Gunicorn,I have Celery and flower for concurrency and monitoring too. Until know Django part works fine, I have self signed certificate for telegram bot too. but Telegram Bot doesn't work at all, in Otherhand I don't know How can I config Celery and Flower to works on VPS: my Nginx Config: server { listen 443 ssl; server_name 136.243.218.9; ssl_certificate /home/farzin/telegbot/django-telegbot/telegbot/cert.pem; ssl_certificate_key /home/farzin/telegbot/django-telegbot/telegbot/private.key; access_log /home/farzin/nginx.bot.access.log main; error_log /home/farzin/nginx.bot.error.log warn; location /token { proxy_pass http://127.0.0.1:8001/token/; } } server{ listen 80; server_name 136.243.218.9; ssl_certificate /home/farzin/telegbot/django-telegbot/telegbot/cert.pem; ssl_certificate_key /home/farzin/telegbot/django-telegbot/telegbot/private.key; charset utf-8; access_log /home/farzin/nginx.access.log main; error_log /home/farzin/nginx.error.log warn; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/farzin/telegbot/django-telegbot; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; proxy_pass http://unix:/home/farzin/telegbot/django-telegbot/telegbot.sock; } } server { listen 80 default_server; listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } Gunicorn Config that works for Django, should I use something like this for celery and flower too: [Unit] Description=gunicorn … -
Rich text editor for django
I am trying to include a richtexteditor for my project. Any recommendations for a open source richtexteditor in Django? Should consist options for image upload, video upload and file upload. -
django permissions not being respected
I am trying to show a button if the logged in user has the right permissions. The code in the template: {% if perms.django_apo_training.can_add %} <a href="{% url 'training:trainee_add' %}"> <button type="button" class="btn btn-success">Add Trainee</button> </a> {% endif %} I can print to the webpage to debug what the permissions the user has: <p> {{ perms.django_apo_training }} </p> It shows: {'training.view_trainee', 'training.add_trainee', 'training.delete_trainee', 'training.change_trainee'} but perms.django_apo_training.can_add always returns false, not sure what what I am missing? Even double checked in the admin console: Lastly, even once this works, how do I make sure that only those with that permission and logged in can get to (it is a lot more than an @login required decorator) http://localhost:8000/training/add/ -
unable to install django though "Successfully installed django-2.2" in amazon linux
I try to make django server in amazon linux ami. I install python3, pip and made virtualenv. After activate virtualenv, I tried to install django. But after installation, I only can't find Django. Other packages are installed well. Is there anything that I miss? Thanks in advance! (python3) [ec2-user@ip-10-0-1-xxx ~]$ pip install django==2.2 Collecting django==2.2 Using cached https://files.pythonhosted.org/packages/54/85/0bef63668fb170888c1a2970ec897d4528d6072f32dee27653381a332642/Django-2.2-py3-none-any.whl Collecting sqlparse Using cached https://files.pythonhosted.org/packages/ef/53/900f7d2a54557c6a37886585a91336520e5539e3ae2423ff1102daf4f3a7/sqlparse-0.3.0-py2.py3-none-any.whl Collecting pytz Using cached https://files.pythonhosted.org/packages/e7/f9/f0b53f88060247251bf481fa6ea62cd0d25bf1b11a87888e53ce5b7c8ad2/pytz-2019.3-py2.py3-none-any.whl Installing collected packages: sqlparse, pytz, django Successfully installed django-2.2 pytz-2019.3 sqlparse-0.3.0 (python3) [ec2-user@ip-10-0-1-xxx ~]$ pip freeze pytz==2019.3 sqlparse==0.3.0 (python3) [ec2-user@ip-10-0-1-xxx ~]$ -
Cannot access query result value from select_related() in html file
I am trying to join 3 tables and want attributes from all 3 tables. I have used select_related('goal_id','mealtype_id') so it gives me all attributes from 3 tables. I converted the query into raw and print it. Then in html template I cannot get "g_name" and "mt_name" value IDK why. Please take a look on my code and snapshot This is view method: def mealslist(request): meals = Meals.objects.select_related('mealtype_id','goal_id') print(meals.query) return render(request,'meals_list.html',{'table':meals}) This is raw query: SELECT `meals`.`id`, `meals`.`goal_id_id`, `meals`.`mealtype_id_id`, `meals`.`name`, `meals`.`quantity`, `meals`.`calories`, `meals`.`day_time`, `goal`.`id`, `goal`.`g_name`, `meal_type` .`id`, `meal_type`.`mt_name` FROM `meals` LEFT OUTER JOIN `goal` ON (`meals`.`goal_id_id` = `goal`.`id`) LEFT OUTER JOIN `meal_type` ON (`meals`.`mealtype_id_id` = `meal_type`.`id`) This is html table code: <tbody> {% for f in table %} <tr> <td>{{f.id}}</td> <td>{{f.g_name}}</td> <td><a href="/mealtype/delete/{{f.id}}">Delete</a><br> <a href="/mealtype/update/{{f.id}}">Edit</a></td> </tr> {% endfor %} </tbody> Please HELP me!! -
How to serialise model field verbose_name
I want to create a generic ListView template that I can use with any model. I am currently using this approach to create a dict of field names and values: views.py from django.core import serializers data = serializers.serialize( "python", SomeModel.objects.all() ) template.html {% for instance in data %} {% for field, value in instance.fields.items %} {{ field }}: {{ value }} {% endfor %} {% endfor %} This will return the field but not the field verbose_name. E.g on a user model is_active does not return as Is the user active?. Is there any way to also serialise the verbose name?