Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
what are the various ways for Styling the Django Forms?
was working with Django forms, and to beautify the Django forms I came across widgets, and after learning it got to know that we can customize widgets in two ways: it can be via widget instance or via widget class. Later came across django-crispy; django-bootstrap. Which will do the same beautification of the forms along with various other advantages over other. But was wondering, how many more such library / packages / apps are there, and is there any short of description for each, which might help me and others too. Thanks -
Crontab ModuleNotFoundError
I have prepared a py Script to update my Django database and upload a file to gdrive once a day. Trying to use Crontab along with python to run the py script. ModuleNotFoundError: No module named 'googleapiclient' I have already installed googleapiclient module. There is no error while running the same script in venv (virtual environment). 0 2 * * * /usr/bin/python3 /home/user/folder1/folder11/script2.py How to access the already installed module inside crontab..? -
change table header and content dynamically in JavaScript
I have a web app, frontend using normal HTML, backend using Django. In the HTML page, there's a table, which load data by calling API. I want to change table header dynamically in JavaScript after the if condition(in my case:if params['Add_Information'] == "eText_iBookStore":), so the table could have different header based on user selection. How could I change the header and content of my table in Javascript? <table contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;" id="bk-table" data-toggle="table" data-toolbar="#toolbar" data-cookie="true" data-cookie-id-table="materialId" data-show-columns="true" data-show-refresh="true" data-show-fullscreen="true" data-show-export="true" data-height="650" data-click-to-select="true" data-id-field="id" data-show-footer="true" data-url="/api/materials/" data-query-params="queryParams" data-remember-order="true" data-pagination="true" data-side-pagination="server" data-total-field="count" data-data-field="results"> <thead class="thead-dark"> <tr contenteditable='true'> <th data-field="id" data-sortable="true">ID</th> {# <th data-field="courseId" data-visible="false"></th>#} <th data-field="courseCode" data-sortable="true" data-formatter="renderCourse">Course Code</th> <th data-field="book.title" data-sortable="true" data-formatter="renderTitle">Course Material Title</th> <th data-field="book.isbn" data-sortable="true">ISBN</th> <th data-field="book.publisher" data-sortable="true">Publisher</th> <th data-field="retail_price_display" data-sortable="true">Retail Price</th> <th data-field="semester_course.school" data-sortable="true">School</th> <th data-field="year" data-sortable="true">Year</th> <th data-field="month" data-sortable="true">Semester</th> <th data-field="quota" data-sortable="true">Course Quota</th> </tr> </thead> </table> <script> {% block script %} var $table = $('#bk-table'); var $ok = $('#ok'); $(function () { $ok.click(function () { $table.bootstrapTable('refresh') }); function queryParams(params) { params['limit'] = localStorage['Format']; params['discipline'] = localStorage['discipline']; params['Add_Information'] = localStorage['Add_Information']; if params['Add_Information'] == "eText_iBookStore": ***//Here should be header changing part*** params['publisher'] = $("[name='publisher']").val(); params['code'] = $("[name='code']").val(); console.log(params); return params; } {% endblock %} … -
Django - How to simplify the create new row of a table with many foreign key?
Here is the sample model: class GenderDecode(models.Model): gender_code = models.IntegerField(primary_key= True) gender_explain = models.CharField(max_length=100) class AgeDecode(models.Model): age_code = models.IntegerField(primary_key= True) age_explain = models.CharField(max_length=100) class User(models.Model): name = models.CharField(max_length=100) age_group = models.ForeignKey(AgeDecode, on_delete = models.CASCADE) gender_group = models.ForeignKey(GenderDecode, on_delete = models.CASCADE) The initial setup of two tables GenderDecode and AgeDecode: GenderDecode gender_code gender_explain 1 male 2 female AgeDecode age_code age_explain 1 young 2 old Provided I want to create a new user - John Male Young. I have to do this. User(name = 'John', age_group = AgeDecode.objects.filter(gender_code=1).first(), gender_group = GenderDecode.objects.filter(age_code=1).first() ).save() I want to do this User(name = 'John', age_group = 1, gender_group = 1 ).save() But I got this error ValueError: Cannot assign "1": "User.gender_group" must be a "GenderDecode" instance. Well, if the above syntax is a must, is there any way to go around to simplify my new row code ? -
How do I get User's updated name from Python Firebase Admin SDK?
I am using FirebaseAuth on Flutter, and send IdToken to my Django backend to use firebase_admin.auth.verify_id_token(id_token) to verify the user and get the user's basic info. But the user's info doesn't show the latest profile. I changed my Google account user name, but the name decoded from IdToken still showing the old name even though I signed out and signed in again on frontend. How do I get the latest user's profile? Thanks -
Django 404 Error: path doesn't go down urls.py
So I'm trying to make an index.html for the homepage of my Django project. I made an app called pages. Note that the templates folder is empty (moving index.html to templates did nothing). admin.py and models.py also contain nothing. I configured my TEMPLATES settings as such: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, '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 my root project folder, urls.py looks like this. from django.contrib import admin from django.urls import path from django.conf.urls import include # from pages.views import home_view urlpatterns = [ path('homepage/', include('pages.urls')), path('admin/', admin.site.urls), path('explorer/', include('explorer.urls')), ] In the views.py file of the pages app: from typing import ContextManager from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): # Render the HTML template index.html return render(request, 'index.html', context=ContextManager) In the pages app (not project root folder), urls.py looks like this (I created this file myself): from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And index.html: <!DOCTYPE html> <title>Test</title> <p>Test</p> Here is the full file structure. Here is what happens when I run the server: Where http://127.0.0.1:8000/ is … -
how to set up docker compose to use ssh to connect to AWS RDS on private subnets via EC2 Bastion
I have the following configuration of a django app that ssh'ed into an ec2 bastion and i tried to follow this example https://emmer.dev/blog/tunneling-a-database-connection-with-docker-compose/ I am still not able to configure my docker compose file to accept ssh tunnel to AWS Postgres RDS which reside in a private subnets. version: "3.9" services: app: build: ./app restart: always env_file: .env volumes: - ./app:/app - ./app/static:/app/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - "app_network" db: image: postgres restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - "app_network" networks: app_network: driver: bridge volumes: postgres_data: What happen is that using django itself via python manage.py runserver i am able to connect to the RDS instance and everything is fine. Now when i try to do the same with docker compose, docker compose exec app python manage.py migrate or try to access RDS from django shell inside the docker compose after it started with docker-compose up -d , the database crash with the message below: django.db.utils.OperationalError: could not translate host name "xxx.zzz.us-east-z.rds.amazonaws.com" to address: nodename nor servname provided, or not known clearly the issue is that docker compose is not picking the ssh tunnel connection i have tried multiple … -
Django & Js question slider with a next button appear on last question
i have a questions slider made with JS with a next button to go to next questions, i want to disable that button in last slide which is the submit slide. I have tried to remove the id from last slide but it wont appear in the sliders any help or advices to improve the code will be great Here is my code: HTML: W <div class="slider"> <form class="form" action="" method="post"> <!-- fade css --> {% csrf_token %} {% for question in questions %} <div class="myslide fade"> <div class="txt"> <p>{{question.question}}</p> <input id="{{question.id}}" type='radio' name="{{question.id}}" value="{{question.category}}"> <label for="{{question.id}}">Yes</label> <br> <input id="{{question.id}}1" type='radio' name="{{question.id}}" value="no"> <label for="{{question.id}}1">No</label> <br> </div> <img src="{{question.img.url}}" style="width: 100%; height: 100%;"> </div> {% endfor %} <div class="myslide fade"> <div class="txt"> <p>You finished all questions</p> <input type="submit" class="btn" value="Submit"> </div> <img src="{% static 'img/img4.jpg'%}" style="width: 100%; height: 100%;"> </div> <a class="next" onclick="plusSlides(1)">Next</a> </form> </div> JS: const myslide = document.querySelectorAll('.myslide'), dot = document.querySelectorAll('.dot'); let counter = 1; slidefun(counter); let timer = setInterval(autoSlide, 8000); function plusSlides(n) { counter += n; slidefun(counter); resetTimer(); } function currentSlide(n) { counter = n; slidefun(counter); resetTimer(); } function resetTimer() { clearInterval(timer); timer = setInterval(autoSlide, 8000); } function slidefun(n) { let i; for(i = 0;i<myslide.length;i++){ myslide[i].style.display = … -
select_related and prefetch_related django
I have these 4 models: class User(models.Model): user = ... class Subject(models.Model): subject = ... class Section(models.Model): section= ... class Profile(models.Model): user= ... class student(models.Model): student = foreignkey(User) enrolled_subjects = ManyToMany(Subject) section = foreignkey(Section) profile = foreignkey(Profile) how can I get all related objects to Student object using select_related and prefetch_related to get? -
How To Create Chained Filter Form Fields Using Django Smart Selects
I have been searching online about how to make chained selections on filter forms (not forms). What I want to do is, select district according to the city that is selected. With normal forms I can make dependent dropdowns, but when it comes to filter forms, it does not seem to work. Here is my settings.py USE_DJANGO_JQUERY = True INSTALLED_APPS = [ 'smart_selects', ] Here is my template <form method="get"> {% csrf_token %} {{ form.media.js }} {{ myFilter.form|bootstrap }} <button type="submit" class="filter filtrele">Ara</button> </form> Here is my models.py class City(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(city, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Usta(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) gizlilik_sozlesmesi = MultiSelectField(choices=GIZLILIK_CHOICES, max_length=1000, max_choices=1, null=True) sartlar_sozlesmesi = MultiSelectField(choices=SARTLAR_CHOICES, max_length=1000, max_choices=1, null=True) isim = models.CharField(max_length=100) ana_kategoriler= MultiSelectField(choices=ANACATEGORY_CHOICES, max_length=1000, max_choices=5, null=True) usta_kategorileri= MultiSelectField(choices=USTACATEGORY_CHOICES, max_length=1000, max_choices=5, null=True, blank=True) bakici_kategorileri= MultiSelectField(choices=BAKICICATEGORY_CHOICES, max_length=1000, max_choices=5, null=True, blank=True) temizlikci_kategorileri= MultiSelectField(choices=TEMIZLIKCICATEGORY_CHOICES, max_length=1000, max_choices=5, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) district = ChainedForeignKey(District, chained_field="city", chained_model_field="city",show_all=False, auto_choose=True, null=True, sort=True) website = models.CharField(max_length=200, default='ananas.website', null=True) eposta = models.CharField(max_length=200, null=True) aciklama = models.TextField(max_length=10000, null=True) telefon = models.CharField(max_length=200, null=True) # aciklama = models.TextField(max_length=1000, null=True) profil_resmi = models.ImageField(default='ananas.jpg', upload_to='profile_images') resim_1 = models.ImageField(default='ananas.jpg', upload_to='profile_images') resim_2 = … -
How to set leaflet map layer selected as default
In my django app I have a leaflet map with two layers "active_event_layer" and "inactive_event_layer". I can select wich layer I want to see in the top right menu. But when the page is loaded no layer is selected by default, so in order to see a layer I must selected it first. What i want to do is to set a layer by default, so, when the page is loaded the "Active events" layer is selected by default. Here is my code: var active_event_collection = {{ active_events|geojsonfeature:"name"|safe }}; var inactive_event_collection = {{ inactive_events|geojsonfeature:"name"|safe }}; function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.name); } function map_init(map, options) { var active_event_layer= L.geoJson(active_event_collection, {onEachFeature: onEachFeature}) var inactive_event_layer = L.geoJson(inactive_event_collection, {onEachFeature: onEachFeature}) var basemaps = { "Gray scale": L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }), Streets: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }) }; var overlayMaps = { "Active events": active_event_layer, "Inactive events": inactive_event_layer, }; var features = L.control.layers(basemaps, overlayMaps).addTo(map); map.fitBounds(active_event_layer.getBounds()); } -
AttributeError 'Model' object has no attribute 'get_FOO_dispay'
qs = Model.objects.all() q = qs.get(id=1) q.get_field_dispay() returns 'Model' object has no attribute 'get_field_dispay' Am I not using it correctly? -
unsupported operand type(s) for /: 'method' and 'method', Django
Good afternoon community, I am new to Django, thus, I apologize in advance if my question happens to be silly. I am working on an investing project and I get the following error when I try to render the following method from the model: unsupported operand type(s) for /: 'method' and 'method' Here under is the code that I wrote, models.py: class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name #Company methods def net_income(self): return self.revenue - self.expenses def net_assets(self): return self.total_assets - self.total_liabilities def return_on_equity(self): return self.net_income / self.net_assets HTML FILE <li>Net income: {{company.net_income}}</li> <li>Net assets: {{company.net_assets}}</li> <li>Return on equity: {{company.return_on_equity}}</li> Note that both net_income and net_assets work just fine. The error rises with the last method, return on equity. I look forward to your enlightenment. -
Saving image files in django media instead of using base64 in quill editor?
I am using django as a backend and providing the api using rest-framework,I would like to use quill editor for my wysiwyg editor? Can anyone help me out in saving the image to django media files instead of saving as base64 it to the database?Thank you By the way , I am using vue for my frontend framework -
Django custom JSONField
I got JSONFields that I have to encode and decode every trip, the problem is I got few of them, so I'm trying to make a custom field like this: class JSONField(models.JSONField): """A Field to encode & decode JSONField.""" def __init__(self, default=dict, encoder=None, decoder=None): self.encoder = encoder self.decoder = decoder self.default = default def get_prep_value(self, value: Any) -> Any: if value is None: return value return json.dumps(value, default=self.default, cls=self.encoder) def from_db_value(self, value, expression, connection): if value is None: return value return json.loads(value, cls=self.decoder) But when I use it on the model class Employee(models.Model): time_log = JSONField() I get this error AttributeError: 'JSONField' object has no attribute 'name' File "/Users/mac/Documents/Payroll/payroll/models.py", line 106, in <module> class Employee(models.Model): File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/base.py", line 161, in __new__ new_class.add_to_class(obj_name, obj) File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 781, in contribute_to_class self.set_attributes_from_name(name) File "/Users/mac/Documents/Payroll/env/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 768, in set_attributes_from_name self.name = self.name or name AttributeError: 'JSONField' object has no attribute 'name' How can I fix this problem? -
Django Annotate the Sum of a Foreign Key's Duration Values
I'm trying to get 5 foo objects whose children (bar) have the longest combined duration: foo = Foo.objects.annotate( sum_of_bar_duration=Sum("bar__duration") )\ .order_by('-sum_of_bar_duration')[:5] My Models: class Foo(models.Model): name = models.CharField(max_length=30, unique=True) #REVIEW deleted blank, null = False since this is default class Bar(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) duration = models.DurationField() But I ended up getting this error: django.core.exceptions.FieldError: Unsupported lookup 'duration' for BigAutoField or join on the field not permitted. Does anyone know why? How can I fix this? -
No module named W0614 pylint (fatal)
I'm working on a Django project and this error keeps coming up on the first line of every file I work on. I recently reset my computer and this is my first time using VSCode after. Please, what should I do? -
django login showing AnonymousUser after login
def loggin(req): if req.user.is_authenticated: return redirect('home') if req.POST: username=req.POST['username'] password=req.POST['password'] usr = authenticate(req,username=username,password=password) if usr is not None: login(req,usr) return redirect(reverse('home')) return render(req,'cart/login.html') def home(req): if req.user.is_authenticated: name=req.user context = { 'name':name, } return render(req,'anon/home.html',context) My settings.py are fine and have no error in code but after successful get logged in redirection to home view shows AnonymousUser.I dont know what i am doing wrong. -
Django / Crispy Forms Inheritance Not Translating to Rendered HTML Page
I am trying to set up a template for my form in Django using forms.py and Crispy but anything I set up in my forms. Ultimately I am just trying to get two fields on one row at the moment and the form template does not show up as formatted when rendered. I believe it may be an inheritance issue but I am not 100% sure. If I take the individual objects such as {{ form.phone_number|as_crispy_field }} then I can format it with <Div> and CSS in the HTML template but this seems unnecessary. #forms.py from django import forms from .models import * from crispy_forms.helper import FormHelper from crispy_forms.bootstrap import FormActions from crispy_forms.layout import Submit, Layout, Row, Column, Hidden class CustomerCreateForm(forms.Form): customer_name = forms.CharField(max_length=100) phone_number = forms.CharField(max_length=12) business_address = forms.BooleanField(required=False, initial=True) street_address_1 = forms.CharField(max_length=255) street_address_2 = forms.CharField(max_length=255, required=False) city = forms.CharField(max_length=100) region = forms.ChoiceField(choices=REGIONS_OPTIONS) postal_code = forms.CharField(help_text="Please enter in the format 'A1A1A1'", max_length=6) country = forms.ChoiceField(choices=COUNTRY_OPTIONS) def __init__(self, *args, **kwargs): super(CustomerCreateForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.attrs = { 'novalidate': '' } self.helper.layout = Layout( Row( Column('customer_name', css_class='form-group col-md-2 mb-0'), Column('phone_number', css_class='form-group col-md-2 mb-0'), css_class='form-row' ), # FormActions( # Submit('submit', 'Create Me') # ) ) #formtest2.html {% … -
Use an HTML page as default Django homepage
I just learned how to create a homepage like this: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home_view(request,*args, **kwargs): return HttpResponse("<h1>Hello</h1>") To do this I made an app called pages and edited views.py. Is there a way to do the same thing but instead of returning an HttpResponse I use my own HTML page instead? Basically replace the default homepage with my own HTML page. -
django.db.utils.ProgrammingError: (1146, "Table 'lab_equipment.lab_add' doesn't exist")
I am trying to delete objects stored on the database from Django admin page and I have gotten an Error django.db.utils.ProgrammingError: (1146, "Table 'lab_equipment.lab_add' doesn't exist") Views from django.shortcuts import render, redirect, get_object_or_404 from django.http import JsonResponse, HttpResponseRedirect from django.urls import reverse from .forms import * from .models import * # Create your views here. def main(request): return render(request, 'Lab/Lab.html') def generateView(request): if request.method == 'POST': # If the form has been submitted... esrl = Esrl_form(request.POST) # Create a form instance equ = equipment(request.POST) num = count_form(request.POST) add = Add_form(request.POST) if esrl.is_valid() and equ.is_valid() and num.is_valid() and add.is_valid(): # All validation rules pass print("all validation passed") loc = esrl.save() e = equ.save(commit=False) c = num.save(commit=False) a = add.save(commit=False) # not to save and connect the Foreign key e.location_number = loc # b.foreignkeytoA = a Connecting foreign key e.save() c.equipment_name = e c.loc_num = loc c.save() a.location_number = loc a.equipment_name = e a.stock = c a.save() return HttpResponseRedirect(reverse('home')) else: print("failed") else: # if the request method is not post then create a form instance u if the request method is not post then create a form instance and loaded in the templatenloaded in the template esrl = Esrl_form equ = equipment … -
django-simple-history save history only when a certain condition is met
I'm building a project using Django. I want to use the django-simple-history package to save the history of a model for every create/update/delete. I want to save the history only when the superuser or a specific type of user (e.g. supervisor) makes a create/update/delete action, but I don't know how can I implement this condition. I've tried this to see if the current user is one of its arguments to use it, but this method seems that it doesn't work properly. Below a portion of my code: class WFEmployee(models.Model): code = models.IntegerField(unique=True) name_en = models.CharField(max_length=55) ... history = HistoricalRecords() def save_without_historical_record(self, *args, **kwargs): print(kwargs, 'from save without ') try: ret = self.save(*args, **kwargs) finally: pass return ret I get nothing in the console when I use .save_without_historical_record() it saves the instance but doesn't print anything. How can I do this? -
DRF-Object of type ManyRelatedManager is not JSON serializable
I am trying to post many-to-many fields data, it returns Object of type ManyRelatedManager is not JSON serializable. models class Professionals(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key = True, related_name='professional') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) profilePicture = models.ImageField(upload_to='professional/profiles', default='default_img.png') skill = models.ManyToManyField(Skill) serializer class ProfessionalSerializer(serializers.ModelSerializer): profilePicture = serializers.ImageField(allow_empty_file=True, use_url='professional/profiles', required=False) skill = SkillSerializer(many=True,read_only=True) class Meta: model = Professionals fields = fields = ['first_name', 'last_name', 'profilePicture', 'skill'] views class ProfessionalProfileUpdateView(APIView): permission_classes = (IsAuthenticated,IsProfessionalUser,) def put(self, request): serializer = ProfessionalSerializer(data=request.data, instance=request.user.professional) data = {} if serializer.is_valid(): professional = serializer.save() professional.save() data['skill'] = professional.skill return JsonResponse({ 'message': "your profile hans been updated", "success" : True, "result" : data, "status" : status.HTTP_200_OK }) else: data = serializer.errors return JsonResponse(serializer.data) posting data using postman { "first_name":"jhon", "last_name":"doe", "skill":[{ "id":1 }], } -
Heroku does not find my Django app module when local version does
The problem So, I have made a website with multiple homemade apps. I now want to deploy this website using Heroku. This doesn't work, however, as I keep getting errors relating to Heroku not being able to find the apps. When I run the website locally with python manage.py runserver everything behaves as expected. When I, however, try to deploy this website using Heroku I get an error (stack trace provided underneath). Project structure towima | .gitignore | Procfile | README.md | requirements.txt | runtime.txt | tree.txt | +---media_cdn | | .DS_Store | | | \---products | \---towima | .DS_Store | db.sqlite3 | manage.py | pharma_locations.json | __init__.py | +---accounts | | admin.py | | apps.py | | forms.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations +---api | | admin.py | | apps.py | | models.py | | serializers.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | +---orders | | admin.py | | apps.py | | forms.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | +---pharmacies | … -
pk is passed but data not dsiplayed
I have a model that contains some judgments along with their title. Now i want to display the judgement when the related title is clicked. i have written the following code: models.py class Laws(models.Model): date= models.DateField(default=timezone.now) title= models.CharField(max_length=225, help_text="judgement title") judgements= RichTextField(blank=True, null= True) law_type= models.CharField(max_length=40, choices= type_of_law) law_category= models.CharField(max_length=60, choices= category) views.py class DocView(ListView): model= Laws template_name = 'doc.html' class Doc1DetailView(DetailView): model= Laws template_name = 'doc1.html' urls.py urlpatterns=[ path('doc', DocView.as_view(), name='doc' ), path('doc1/<int:pk>', Doc1DetailView.as_view(), name='doc1' ), ] and the html files are doc.html {% for data in object_list %} <div class="tab"> <a href="{% url 'doc1' data.pk %}">{{data.title}}</a><br/> </div> {% endfor %} doc1.html <p style="color: black;">{{data.judgements}}</p> I refered to a video in youtube and wrote this code his was working and mine not. i have chamged nothing from that code still the data doesn't show up in doc1.html. No filed is empty here. please rectify my code and tell me what i am doing wrong here.