Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django abstract model with indices, constraints and permissions: attributes are not inherited by sub classes
I am using Django 3.2 I have the following models: app1 class IsPinnable(models.Model): is_pinned = models.BooleanField(default=False) pin_after_expiry_day_count = models.DurationField(default=0) class Meta: abstract = True indexes = [ models.Index(fields=['is_pinned' ]), ] class IsModeratable(models.Model): approved = models.BooleanField(default=False) target_count_trigger = models.PositiveSmallIntegerField() positive_pass_count = models.PositiveSmallIntegerField(default=0) negative_pass_count = models.PositiveSmallIntegerField(default=0) # Other fields and methods ... def save(self, *args, **kwargs): # TODO: Sanity check on pass_count and trigger sizes # ... super().save(*args, **kwargs) class Meta: abstract = True permissions = ( ("moderate_item", "can moderate item"), ("reset_moderation", "can (re)moderate a moderated item"), ) indexes = [ models.Index(fields=['approved' ]), ] class MyComponent(IsPinnable, IsModeratable): # some fields and methods ... class Meta(IsPinnable.Meta, IsModeratable.Meta): abstract = True # other stuff ... app2 from app1.models import MyComponent class Foo(MyComponent): # some fields and methods ... class Meta(MyComponent.Meta): abstract = False Now, I know that abstract model classes are not created in the database - so I was initially expecting Django to throw an exception when I attempted to makemigrations - to my surprise, I was able to makemigrations && migrate. However, when I inspected the database (via psql), I found that although table app2_foo had all the fields described in it's parent class, the indixes were not being carried up from … -
Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name [closed]
code I'm getting Reverse for 'signup' not found. 'signup' is not a valid view function or pattern name. -
Variable dictionary in django using javascript
I am passing a dictionary of variable size to an html, and in the html I have a script (javascript) that I need to make one for inside another. And by the code you can get a sense of what I need. I need to pass every "Exame" to especific "Cliente". HTML file: <p id="dependentes"></p> {% for obj in object3 %} <div> <ul><p>Exames de {{ obj.id_cliente1 }}: </p> <div id="iteracao"></div> </ul> </div> <script type="text/javascript"> var cliente1 = "{{ obj.id_cliente1 }}"; var teste = document.getElementById('teste'); cliente2 = teste.value; cliente2 = cliente2.replace(" ", "_"); document.getElementById('iteracao').textContent = "\{\% for obj2 in " + cliente2 + " \%\}" + "<li><a href='/exames/\{\{ obj2.slug \}\}/'>\{\{ obj2.nome \}\}</a></li>" + "\n" + "\{\% endfor \%\}"; //JSON.parse(document.getElementById('iteracao').textContent); var a = document.getElementById('dependentes`enter code here`'); if (cliente1 != "None"){ a.innerHTML = "Dependentes: "; } </script> {% endfor %} View file: class ClienteDetailView(DetailView): def get_queryset(self): self.slug = self.kwargs.get("slug") if self.slug: queryset = Cliente.objects.filter(slug__icontains=self.slug) else: queryset = Cliente.objects.all() print('ClienteDetailView') return queryset #, queryset2 #, queryset3, queryset4 def get_context_data(self, **kwargs): queryset = Cliente.objects.filter(slug__icontains=self.slug) cliente = Cliente.objects.get(slug__icontains=self.slug).id_cliente queryset2 = Exame.objects.filter(cliente_fk=cliente) queryset3 = Dependencia.objects.filter(id_cliente2=cliente) quantidade = Dependencia.objects.filter(id_cliente2=cliente).count() context = { "object": queryset, "object2": queryset2, "object3": queryset3, } if quantidade > 0: for i in queryset3: #cliente2 … -
django Rest frame work : token authentication
I have a table ('like') to like post class Likes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() i have a table course : class Courses(models.Model): title = models.CharField(max_length=100, null=True) description = RichTextUploadingField(null=True) like = GenericRelation(Likes) i use restman opera extension to send POST request to my api if i login with browser i get error "detail": "CSRF Failed: CSRF token missing or incorrect." but i use restman only(i dont login with browser) every thing is OK setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication' ] } -
Can't access a variable from django views.py to html pqge
I know you can show a variable from the views.py using the {{variable_name}} But my variable name is in a if statement: So even when I type {{variable_name}} it doesn't show. Rather it gets the else statement: variable_name = '' What could be the cause,m -
next or previous item within an ordered, filtered queryset in Django
How can I make transitions to the next article from the post_details(DetailView), so that both the next article and the previous one are available ? vievs.py class HomeView(ListView): model = Post #queryset = Post.objects.filter(status=1) cats = Category.objects.all() template_name = 'home.html' #ordering = ['-post_date'] paginate_by = 6 def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context class ArticleDetailView(HitCountDetailView): model = Post template_name = 'post_detail.html' count_hit = True def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(ArticleDetailView, self).get_context_data(*args, **kwargs) stuff = get_object_or_404(Post, id=self.kwargs['pk']) total_likes = stuff.total_likes() context["cat_menu"] = cat_menu context["total_likes"] = total_likes return context Sort by date and ID -
Django changing template_name in get_context_data dynamically
how do I override the template_name of a TemplateView based on the context in get_context_data? In other words, I would like to find a way to change the template rendered according to my context. The following is modified from my current code and it does not work: class FooPage(TemplateView): template_name = "folder/template1.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['myvariable'] = MyModel.objects.get(pk=kwargs['some_criterion']).variable if "text" in context['myvariable']: template_name = "folder/template2.html" # This line does get executed return context I can confirm that the line changing template_name is executed and it is indeed set to "folder/template2.html" at that point, but the actual page that gets rendered still looks like the original (template1.html) instead. Any helpful insight would be deeply appreciated. Thank you very much! -
Saving Multiple Objects from same Form - 'QuerySet' object has no attribute '_meta' Django
I am creating a post which will have gallery images, Views.py def tripUpdate(request, pk): trip = get_object_or_404(Trip, pk=pk) trip_images = TripImages.objects.filter(trip=trip).first() trip_form = AddTripForm(request.POST or None, request.FILES or None, instance=trip) trip_image_form = AddTripImageForm(request.POST or None, request.FILES or None, instance=trip_images) if request.method == 'POST': if trip_form.is_valid() and trip_image_form.is_valid(): trip_form.save() images = request.FILES.getlist('image') for photo in images: i = TripImages.objects.create( trip=Trip.objects.get( title=trip_form.cleaned_data['title']), image=photo, ) messages.success(request, 'Trip Updated') return redirect('dashboard') Models.py class Trip(models.Model): title = models.CharField(max_length=255, unique=True) fields.... class TripImages(models.Model): trip = models.ForeignKey( Trip, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField( upload_to='trip-images/%Y/%m/%d', null=True, blank=True) I am creating Trip and TripImages in same form, While uploading TripImages.image i use multiple file upload While updating i get the error 'QuerySet' object has no attribute '_meta' I want to get all the TripImages which i have uploaded for the particular Trip, .filter(trip=trip).first() only returns single image and only using .filter(trip=trip) gives the above error but i want all the images to show, How can i do that, Thank You! -
get student id when storing student mark -Django
im creating a small student management app using django, i wanna know how to get the student_id in student table to student_mark table without using GET request(when i clicked add marks) -
Dash App with Django gives an error of NolayoutExeption even though everthing seems to be correct
This is the dast app code file capi and ceda are jupyter notebooks downloaded and I am calling a function from the file import dash import dash_table import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go from django_plotly_dash import DjangoDash #import for dash file from website.dash_app import coronaAPI1 as capi from website.dash_app import CoronaEDA2 as ceda from flask import send_from_directory app1 = DjangoDash('india_plot') ################################################################### #######figure 1 ################# app1.layout = html.Div(style={"background-color":"rgb(17, 17, 17)"}, className='card', id='main-div', children=[ html.Br(), html.Div(className='card', id='div1', style={'text-align': 'center'}, children=[ dcc.Dropdown(className='dropdown',id='dropdown-1', options=[ {'label': 'Confirmed Cases', 'value':'confirmed'}, {'label': "Recovered Cases", 'value': 'recovered'}, {'label': "Deceased Cases", 'value': 'deaths'}, {'label':'Active Cases', 'value':'active'}, ], value='confirmed', ), html.Br(), dcc.Graph(id='india_map'), ]), ]) @app1.callback( Output('india_map', 'figure'), [Input('dropdown-1', 'value')] ) def figure1(status): return capi.india_cases(status) ################################################################# #########figure 2 ######################### app2 = DjangoDash('total_cases_india_line_graph') total_cases_india = ceda.total_cases_india() app2.layout = html.Div(className='card', children=[ html.Br(), html.Div(className='card', id='div1', style={'text-align': 'center'}, children=[ html.Br(), dcc.Graph(figure=total_cases_india), ]), ]) ######################################################### #################figure 3 ###################### app3 = DjangoDash('daily_cases') app3.layout = html.Div(className='card', id='main-div1', children=[ html.Br(), html.Div(className='card', id='div4', style={'text-align': 'center'}, children=[ html.H2(id='heading3', children=[ "Vizualization of India based on specific conditions of COVID-19 Cases Reported." ]), dcc.Dropdown(className='dropdown',id='dropdown-2', style={ 'width':'200px', # 'background-color':'rgba(70, 70, 70, 0.6)', # 'color':'black', }, optionHeight=35, options=[ {'label': 'Confirmed Cases', 'value':'dailyconfirmed'}, {'label': "Recovered … -
How to design relationship betwen these django models?
I have to make this Django Rest Framework API which can book Advisors from the available lists of advisors through the specific endpoint user/<user-id>/advisor/<advisor-id> Models i have(models.py) : #User class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' #Advisor class Advisor(models.Model): """Advisor object to be booked""" name = models.CharField(max_length=255) image = models.ImageField(upload_to=advisor_image_file_path) def __str__(self): return self.name #Booking class Booking(models.Model): """Booking the Advisor""" advisor = models.ForeignKey( Advisor, default = '' , on_delete = models.CASCADE ) date_time_field = models.DateTimeField(auto_now_add=False, auto_now=False) user = models.ForeignKey( User, on_delete = models.CASCADE, default = 1 ) def __str__(self): return "{}".format(self.date_time_field) I don't know if this logic is correct or not but i am getting error core.booking has no column advisor_id If this is not the correct logic, please suggest the correct one. -
How to use foreign key field in unique_together to validate?
I trying to make tournament_date, tournament_time and match_type must be unique entry. tournament_date and match_type is in MTournament table tournament_time is in Mtournament_Time table This how I implement unique_together in Mtournament_Time table. unique_together = ['mtournament__tournament_date', 'mtournament__match_type', 'tournament_time'] class BaseClass(models.Model): is_active insert_date updated_date class Game(BaseClass): # is_active, insert_date, updated_date # name, game_image name = models.CharField(max_length=16) game_image = models.ImageField(upload_to='game_images/', default='game_images/game_default.jpg') class GameMap(BaseClass): # is_active, insert_date, updated_date game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=64) class Tournament(BaseClass): CHECK = ( ("No", "NO"), ("Yes", "YES"), ) MATCH_TYPE = ( ("Solo", "SOLO"), ("Duo", "DUO"), ("Squad", "SQUAD"), ) # is_active, insert_date, updated_date # game, name, tournament_date, map, match_type, camera_type, country, country_base game = models.ForeignKey(Game, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=64) tournament_image = models.ImageField(upload_to='esports/tournament', default='esports/user/default.png') country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, default=99) country_base = models.CharField(choices=CHECK, max_length=8, default='NO') class MTournament(BaseClass): MATCH_TYPE = ( ("Solo", "SOLO"), ("Duo", "DUO"), ("Squad", "SQUAD"), ) # is_active, insert_date, updated_date # tournament, mtournament_date, map, match_type tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) tournament_date = models.DateField(verbose_name='Tournament Date') map = models.ForeignKey(GameMap, on_delete=models.SET_NULL, null=True) match_type = models.CharField(choices=MATCH_TYPE, max_length=32, default=1) class Mtournament_Time(BaseClass): # is_active, insert_date, updated_date mtournament = models.ForeignKey(MTournament, on_delete=models.SET_NULL, null=True) tournament_time = models.TimeField(verbose_name='Multiple Tournament Time') class Meta: db_table = 'tbl_mtournament_time' verbose_name = "Tournament Time" # Below is the code i want … -
Export a list of customers who completed registration but haven't performed any action (no invoice, expense, withdrawal)
This is the full task : Export a list of customers who completed registration but haven't performed any action (no invoice, expense, withdrawal) last week (3-9 May) I need to create this type of SQL, but I don't know how to check for actions, what I did for now is SELECT user FROM users_user WHERE completed_registration=False AND date_joined BETWEEN '2021-05-03 00:00:00' AND '2021-05-29 00:00:00' UNION SELECT user FROM invoice_invoice; Check for users who had completed the registration, check for the date, and then check the invoice. But as I check for invoice_invoice itself it's an empty table, why do I get one user when I launch this query? The completed_registration and the date fields which are in queryset right now are only for test. Only users This is when I check only for invoices This is the structure: Expense model: class Merchant(BaseModel): company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='merchants') name = models.CharField(max_length=255) company_code = models.CharField(max_length=255, default='', blank=True) def __str__(self): return f'{self.company} {self.name}' class Expense(Operation): category = models.CharField(choices=ExpenseCategories.get_choices(), default=ExpenseCategories.GENERAL.name, db_index=True, blank=True, max_length=255) merchant = models.ForeignKey(Merchant, on_delete=models.PROTECT, related_name='expenses', blank=True, null=True) amount = models.PositiveIntegerField(default=0, blank=True, help_text='Only taxable amount. In cents') full_amount = models.PositiveIntegerField( default=0, blank=True, help_text='Full amount. Most of the time same as amount or … -
Login alone is not working in django...I want what is wrong [closed]
the picture has the code that I have been used for login view which not working -
NoReverseMatch Error but couldn't find its source
I am relatively new to Django and started to create my first To-Do-List. However I get an error whenever I try to create an href that says: NoReverseMatch at /aufgabenzettel/ I have desperately tried to fix it for the last five hours and am very frustrated because the error just seems to be caused by a single line of code... Please help! It would be awesome and I really appreciate every hint! Here's the code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<int:aufgabenzettel_id>", views.details, name="details") ] views.py from django.shortcuts import render from .models import Aufgabenzettel # Create your views here. def index(request): return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all() }) def details(request, aufgabenzettel_id): aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id) return render(request, "aufgabenzettel/details.html", { "details":aufgabenzettel }) models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) def __str__(self): return f"{self.Aufgabeselbst}" layout.html <!DOCTYPE html> <html lang="de"> <head> <title>Aufgabenzettel</title> </head> <body> {% block body %} {% endblock %} </body> </html> index.html {% extends "aufgabenzettel/layout.html" %} {% block body %} <h1>Meine Aufgaben</h1> <ul> {% for Aufgabeselbst in Aufgabenliste %} <li> <a href="{% url 'details' aufgabenzettel.id %}"> Aufgabe {{ Aufgabeselbst }} </a> </li> {% endfor %} </ul> … -
Only one row is added from 2000+ rows in excel, while uploading it into django admin
I have around 2000+ row in my excel file and while uploading the selected files its show only last row added to the Django admin. How to fix it? Here is my import.html(HTML FILE) {% extends 'base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% endblock %} views.py def simple_upload(request): if request.method == 'POST': product_resource = ProductResource() dataset = Dataset() new_product = request.FILES['myfile'] if not new_product.name.endswith('xlsx'): messages.info(request,'Wrong Format') return render(request, 'Upload.html') imported_data = dataset.load(new_product.read(),format='xlsx') for data in imported_data: value = Product( data[0], data[1], data[2], data[3], data[4], data[5], data[6] ) value.save() return render(request,'import.html') resources.py from import_export import resources from .models import Product class ProductResource(resources.ModelResource): class Meta: model = Product admin.py admin.site.register(Product) class PersonAdmin(ImportExportModelAdmin): pass urls.py urlpatterns = [ path('',views.simple_upload), ] -
What is the best practice for retrieving data from backend and using them in frontend form using REST API? [closed]
I am developing a REST API for an application in Django. It's frontend is being created in AngularJS. In create forms, there are fields that are related fields. For example, if a Car model is related to Manufacturer model, I want to send the list of manufacturers from the backend while creating Car. But, the issue is there might be multiple relationships in Car model like MadeInCountry, Distributers, etc. Also, based on logged in users and other criteria, I want to send filtered objects to be displayed in the form. How do I accomplish this using REST APIs? I have come to two conclusions for achieving this: Send data to be populated in form using GET method of the Create API and ask frontend to call that API. Ask frontend to call list API of every related field and send filtered data to be used in the form. Which method should I use? Or, are there any more efficient and best practice for this? -
how to return json response from views.py instead of .html file in django
I am working on django project that is returning a template in its views.py with context as: return render_to_response('page.html', context) here context is a dictionary that is having keys and values from multiple model classes I need to just return the json response instead of html page. please help me out. -
Django: Receive data from form once
I don't know exactly how to name this question, but this is my problem. I have a calendar which behavior depends on get parameters. I have 2 basics GET params: month and year so it renders calendar for specific year and month. My problem: I need option to change month to next / previous. I can easily do that with JS using ajax, but now I want it to work for non-JS users as well. I tried: next_month / prev_moth GET param so I render calendar depending on that params, but here's the problem with this approach: if user refresh page, wrong calendar is rendered because refreshing is just repeating request so params will be saved so if user refresh page 10 times he will get calendar from 10 months before (if there is prev_month get param). I can't remove get params because QueryDict is immutable. -
How to pass image url to line_items.images field in Stripe API in django
In my project i'm trying to buy products and uses Stripe api for payment.So during payment time i would like to display product.name,product.price and product.image in the session. product.name and product.price works fine but instead of product.image alt section of the image (alt='product') is displaying. class in views.py class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs['id'] product = cake_list.objects.get(id = product_id) YOUR_DOMAIN = 'http://127.0.0.1:8000' checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': product.price*100, 'product_data': { 'name': product.name , 'images': [YOUR_DOMAIN +'/media/'+ str(product.image)], }, }, 'quantity': 1, }, ], mode='payment', success_url=YOUR_DOMAIN + '/myorders/', cancel_url=YOUR_DOMAIN + '/payment-cancelled/', ) return JsonResponse({ 'id' : checkout_session.id }) While printing product.image in console it displays the correct ImageField data which is images/filename.png. 'images' is the file which images are upload_to -
Problem locating media file using Django's static function in template
I am using Django 3.2 I am trying to integrate a blog app that has a slightly convoluted directory structure for its static assets. Here is the relevant part of the tree: Blog app static assets directory structure blog/static/blog/ ├── css │ ├── bona │ │ ├── comment.css │ │ ├── detail-page.css │ │ ├── prism.css │ │ ├── responsive.css │ │ ├── styles │ │ └── styles.css │ ├── common-css │ │ ├── bootstrap.css │ │ ├── fontawesome-free │ │ ├── ionicons.css │ │ ├── ionicons.min.css │ │ └── swiper.css │ └── tinymce │ ├── github.css │ └── tomorrow-night-blue.css ├── font │ ├── fontello.eot │ ├── fontello.svg │ ├── fontello.ttf │ ├── fontello.woff │ └── fontello.woff2 ├── fonts │ ├── Aileron │ │ ├── Aileron-Black.otf │ │ ├── Aileron-Bold.otf │ │ ├── Aileron-Heavy.otf │ │ ├── Aileron-Italic.otf │ │ ├── Aileron-Light.otf │ │ ├── Aileron-Regular.otf │ │ ├── Aileron-SemiBold.otf │ │ ├── Aileron-Thin.otf │ │ ├── Aileron-UltraLight.otf │ │ └── Gidole-Regular.ttf │ ├── Colaborate │ │ ├── ColabBol.otf │ │ ├── ColabLig.otf │ │ ├── ColabMed.otf │ │ ├── ColabReg.otf │ │ └── ColabThi.otf │ ├── ionicons.eot │ ├── ionicons.svg │ ├── ionicons.ttf │ ├── ionicons.woff │ ├── linea-basic-10.eot … -
filter ChoiceField dynamically based on another field
I have a Model Form that must be filled in by the user. in the form there are 3 drop-down menus (foreignkey in the model) which depend on each other. that is, when the user selects a value in the first field the results in the second must dynamically depend on that. i know i have to use ajax but i never used it and i don't know where to start I know that to filter I have to set the queryset e.g. form.fields['stabilimento'].queryset = Stabilimento.objects.filter(), but I don't know how to do it using ajax model.py class Ticket(models.Model): stabilimento = models.ForeignKey(Stabilimento, on_delete = models.RESTRICT) linea = models.ForeignKey(Linea, on_delete = models.RESTRICT) macchina = models.ForeignKey(Macchina, on_delete = models.RESTRICT) form.py class NewTicketForm(forms.ModelForm): class Meta: model = Ticket fields = '__all__' -
How to send iframe via Django email?
I have a HTML template of my e-mail message with embded google map, via iframe. How can I send email with iframe integration in django? -
How can a fill table with database query
Hello I want that when I select a div with certain data it is filled by taking the date of the data of the div. I hide select if is not selected but i do with js you can see the picture here: image I want to get this value before load a template for q in qs: rec_sistrade = q.rec_sistrade emp = request.user.user_sistrade ## sentencia = "exec [Empresa].[dbo].[PT_GET_ORDENES]" + str(rec_sistrade) + "," + emp cursor.execute(sentencia) results = namedtuplefetchall(cursor) order= "'FSAFSF'" (replace getting selected order) sentencia2 ="exec [Empresa].[dbo].[PT_GET_ORDENES_EVENTOS]" + str(rec_sistrade) + "," + emp + "," + op ## html <select id="select" class="form-control" name="select"> <option readonly selected>SELECCIONA UNA OPCI&Oacute;N</option> <option value="div1">{{ results.1.op_ser_codigo }}{{ results.1.op_num_codigo }} / ({{ results.1.data_ini }} - {{ results.1.data_fim }})</option> <option value="div2">{{ results.2.op_ser_codigo }}{{ results.2.op_num_codigo }} / ({{ results.2.data_ini }} - {{ results.2.data_fim }})</option> </select> <div id="div1"> <b><p class="black">ORDEN: </b><input type="text" class="sinborde date_tr" name="orden1" value="{{ results.1.orden }}" readonly/> </p> <b><p class="black">OP: </b><input type="text" class="sinborde" name="op1" value="{{ results.1.op_ser_codigo }}{{results.1.op_num_codigo}}" readonly/> </p> <b><p class="black">FECHA INICIO: </b><input type="text" class="sinborde date_tr" name="fecha_ini_1" value="{{ results.1.data_ini }}" readonly/> </p> <b><p class="black">FECHA FINAL: </b> <input type="text" class="sinborde date_tr" name="fecha_fin_1" value="{{ results.1.data_fim }}" readonly/> </p> <b><p class="black">CLIENTE: </b></p> <b><p class="black">ART&Iacute;CULO: </b><input type="text" class="sinborde date_tr" name="articulo1" … -
How to call model in Django
I'm writing a project with Django that can manage citizens with their passports. But today when I created an HTML page to represent the database, I have encountered an error. My purpose of this webpage is show to user the info includes (citizen name, citizen sex, the birthday of citizen, passport type, passport number, and valid time of citizen's passport). All of citizen information, I have put in Citizen table. With passport of citizen, I have put in Passport table. The HTML page have represented all the information of Citizen table, but cannot represent informations in Passport table and I don't know why. I don't know what I have wrong. Here is my code: models.py class Passport(models.Model): Number = models.CharField(max_length=8, default=1) pType = models.CharField(max_length=1) validTime = models.DateField() pLocation = models.ForeignKey(Manager, on_delete=models.CASCADE, null=True, default=None, related_name="passport", ) def __str__(self): return f"{self.Number} ({self.pType})" class Citizen(models.Model): sID = models.OneToOneField( Passport, on_delete=models.CASCADE, default=1, ) name = models.CharField(max_length=64) sex = models.CharField(max_length=1) year = models.DateField() code = models.BigAutoField(primary_key=True, default=None) def __str__(self): return f"{self.name} ({self.sex})" urls.py from django.urls import path from . import views app_name = 'citizens' urlpatterns = [ path("", views.index, name="index", ), path("<int:citizen_id>", views.citizen, name="citizen"), path("<int:citizen_id>/passport", views.passport, name="passport") ] views.py from django.shortcuts import render from django.http …