Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create custom view permission in django
I need to create a permission that allows the User to see the "Alumno" model, but I only , but I only need it to see the records of that model that have the same foreign key as "id_colegio"... for example, if my User has the foreign key of id_colegio = 1, I need him to be able to see all the records of "Alumno" whose foreign key "id_colegio" = 1 models.py class User(AbstractUser): profesor = models.BooleanField(default=False) rut_user = models.IntegerField(null=True) id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio', null=True,verbose_name="Colegio") class Alumno(models.Model): rut_alumno = models.IntegerField(primary_key=True) dv_alumno = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15 , verbose_name = "Primer nombre") s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) fecha_nac = models.DateField() genero = models.CharField(max_length=1) direccion = models.CharField(max_length=25, blank=True, null=True) nivel_socio = models.CharField(max_length=10) id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING, db_column='id_examenes') rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING, db_column='rut_apoderado') id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio') id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso') id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') def __str__(self): return f"{self.rut_alumno , self.p_nombre , self.ap_paterno}" class Meta: managed = True db_table = 'alumno' class Colegio(models.Model): id_colegio = models.IntegerField(primary_key=True,verbose_name="Colegio") nombre = models.CharField(max_length=20) telefono = models.IntegerField(blank=True, null=True) direccion = models.CharField(max_length=25) id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') -
What is the differences between django 1.11 and django 3.8?
So far I have been using Django 1.11.10. I learnt it on this version. But I should upgrade it to 3.8 . How can I do this. Which sites or documentation can I use? What kind of path should I follow? -
Form with image upload not working in Django
I am trying to get this form to work but I seem to be missing something. This is what I have so far. When I submit the form nothing happens, no error message, just a blank form. views.py here is my views file. It only has this one view def add_book_view(request): if request.method == 'POST': form = AddBookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('books:book_list') else: form = AddBookForm() return render(request, 'settings/add_book.html', {'form' : form}) form here is my form. I have stripped out the css because I apparently have too much code and not enough "description". I am really trying to get this solved. <form method="POST" enctype="multipart/form-data"> {% csrf_token %} Title: <input class="settings-form-input" type="text" name="title" maxlength="256" required="" id="id_title"> Author(s): <input class="settings-form-input" type="text" name="authors" maxlength="256" required="" id="id_authors"> Genre: <select name="genre" id="id_genre"> <option value="0" selected="">None</option> <option value="1">Action-Adventure</option> <option value="2">Autobigraphy</option> <option value="3">Biography</option> etc... </select> <br/> Book Cover: <input type="file" name="book_cover" accept="image/*" required="" id="id_book_cover"> <br/><br/> Description: <textarea class="settings-form-textarea" name="description" required="" id="id_description"></textarea> <input type="hidden" name="added_by" id="id_added_by" value="{{ user.first_name}} {{ user.last_name }}"> <input type="submit" class="form-button" value="Add Book"> </form> models.py This is my models file. This form isn't letting me post because it says I have too much code and not enough details so now I am … -
Django OneToMany Add to a specific ID
I got 3 models, OneToMany situation, "Patients => Hospitalized and Consult". I access the form for adding a consult from a DetailView(which is intended to the Patient, like a Profile). How can I add a consult for that specific Patient(specific ID)? Models are like: class Patient(models.Model): NameandLastName = models.CharField(max_length = 50) ... class Consult(models.Model) Patient = models.ForeignKey(Patient, on_delete = models.CASCADE) simptoms = models.CharField(max_length = 50) option_pay = models.CharField(max_length = 40, choices = pay_method) ... (...) - there are more fields. Thanks for your time. -
Add "All" choice to Django ModelForm
I have Django ModelForm to filter data by a certain field - 'model_name' with form method="get" class TruckTripForm(ModelForm): class Meta: model = TruckTrip fields = ['model_name'] This is my view: def table(request): trips = TruckTrip.objects.all() form = TruckTripForm() if request.GET.get('model_name'): models_query = request.GET.get('model_name') trips = trips.filter(model_name=models_query) form = TruckTripForm(request.GET) context = { 'form': form, 'trips': trips } return render(request, 'tripweight/index.html', context) The problem is that I want to add choice 'all' to my form, so i can disable all my filter and get all of my objects. But right now with this ModelForm I can only filter my queryset -
Error in authenticate a websocket with token authentication on django channels?
I face an error when calling the websocket url with passing a JWT token for authentication purpose: my websocket request is: ws://127.0.0.1:8000/chat/chat_2/?token= the error is: raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'chat/chat_2/'. I'm using a custom authentication middleware: middleware.py """ General web socket middlewares """ from channels.db import database_sync_to_async from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from rest_framework_simplejwt.tokens import UntypedToken from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication from channels.middleware import BaseMiddleware from channels.auth import AuthMiddlewareStack from django.db import close_old_connections from urllib.parse import parse_qs from jwt import decode as jwt_decode from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() @database_sync_to_async def get_user(validated_token): try: user = get_user_model().objects.get(id=validated_token["user_id"]) print(f"{user}") return user except User.DoesNotExist: return AnonymousUser() class JwtAuthMiddleware(BaseMiddleware): def __init__(self, inner): self.inner = inner async def __call__(self, scope, receive, send): # Close old database connections to prevent usage of timed out connections close_old_connections() # Get the token token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] # Try to authenticate the user try: # This will automatically validate the token and raise an error if token is invalid UntypedToken(token) except (InvalidToken, TokenError) as e: # Token is invalid print(e) return None else: # Then token is … -
Why Django Is fail to run when every thing looks fine, django.core.exceptions.ImproperlyConfigured?
When I Run : python3 manage.py runserver The Error Was : django.core.exceptions.ImproperlyConfigured: Cannot import 'CharacterCounter'. Check that 'FreeOnlineTools.CharacterCounter.apps.CharactercounterConfig.name' is correct. Settings are : Folder Structure : Apps File : Python Version : Python 3.10.4 Which Python is : /home/pythondev/Django/venv/bin/python Requirements.txt : What did i do wrong hear all files are just the default settings? -
Change the foreignKey id to another Field
I don't know if there is a logic for this, because i seen it before when I programed with C# and VB, but in Django, it's seems hard to get it. So what I want to ? I want the table in database save the name and not the id of the foreignKey. And this is the model.py from pyexpat import model from statistics import mode from venv import create from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from django.forms import IntegerField class Post(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Person(models.Model): post = models.ForeignKey(Post , on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) def __str__(self): return f"({self.name} is {self.post})" class Room(models.Model): name = models.CharField(max_length= 150, unique = True) def __str__(self): return str(self.name) class Classification(models.Model): name = models.ForeignKey(Person, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) date = models.DateField(auto_created=False) create_date = models.DateTimeField(auto_created=True) def __str__(self): return f"({self.name} Take {self.room} at {self.date})" The result in Database table: enter image description here What I want to see in the database table, is that Django replace the id's in name_id column with names, and room_id with room names is that possible ? Thank you -
Django request.user resets to AnonymousUser after redirect via url
I have a Django project that is used a basic authentication (django.contrib.auth). I am using a middleware to check if an user is authenticated to redirect to a login page if not. It works as expected until I am using site urls like the following path("edit/<int:id>/", netinventory_views.NodeEdit, name="edit"), path("nodes/<int:id>/", netinventory_views.NodeTest, name="test"), That cause request.user is reset to AnonymousUser. middleware.py: from django.utils.deprecation import MiddlewareMixin from django.shortcuts import redirect from django.conf import settings from django.core.cache import cache EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/')] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [url for url in settings.LOGIN_EXEMPT_URLS] class AuthRequiredMiddleware(MiddlewareMixin): def process_request(self, request): path = request.path_info.lstrip('/') if request.user.is_authenticated: user = request.user cache.set('_cached_user', user) return else: if path not in EXEMPT_URLS: return redirect('login') -
stand alone django script gets Lost connection to MySQL server during query
I have a standalone python script (i.e. not part of a web app) that makes use of the ORM. I call djago.setup(), make some queries, then call a function that can take 8 hours or more to run. When the function returns I want to make more queries, but they fail with Lost connection to MySQL server during query. My DB wait_timeout is set to 8 hours and if the function returns in less than 8 hours I don't get the error, so I thought I understood what was going on. But then I read about CONN_MAX_AGE which we do not set. If that is not set it should default to 0, which should mean that it gets a new connection for each request so we should not get the Lost connection message. Does that not work when using djago.setup()? Further reading I saw said to call close_old_connections() or connection.close() before calling the long running function. What is the difference between these 2 and is one a better practice than the other? -
prepopulate django formset with certain values
I've struggled for weeks with Django's ModelFormSet & co, head exploding. I searched hours,days on the internet to find a solution, but nothing really helpful for my special problem: I have 2 models (here simplified): class BaseSetting(models.Model): """This is a basic model which holds namespace and key of a setting.""" namespace = models.CharField(max_length=25) key = models.CharField(max_length=255) class ScopedSetting(models.Model): """Model class for all scoped MedUX settings. Settings are generally saved as strings, but are interpreted at retrieval and casted into their correct types. ScopedSettings knows about ``str``, ``int``, ``bool``""" base = models.ForeignKey(BaseSetting, on_delete=models.CASCADE) """The FK to the basic settings fields like namespace, key.""" tenant = models.ForeignKey( Tenant, verbose_name=_("Tenant"), on_delete=models.CASCADE, default=None, null=True, blank=True, ) group = models.ForeignKey( Group, on_delete=models.CASCADE, default=None, null=True, blank=True ) device = models.ForeignKey( Device, on_delete=models.CASCADE, default=None, null=True, blank=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True, ) scope = models.IntegerField(choices=Scope.choices) """The scope where this setting is valid.""" value = models.CharField(max_length=255, null=True) ATM I am using django-extra-views to get a simple ModelFormSetView - and it shows a form, but not what I want: For each BaseSetting (namespace,key) there exists up to 5 different ScopedSettings which could be applicable to the current user, depending on their scope: the vendor, the … -
HOW TO CHANGE THE FOREIGN KEY VALUE AND SAVE IN DB TROUGHT A FUNCTION (RESOLVED)
I WANTED TO CHANGE THE FOREIGN KEY VALUE TROUGHT A FUNCTION. SO HERE IS MY SOLUTION. I THNINK THIS WILL BE HELPFUL FOR SOMEONE ONE DAY. -
Cannot login to Agora RTM with Django and Javascript
I'm having difficulty logging in my RTM client and keep getting Error code 3: RTM:ERROR Error Code 3: login failed with args: {"UID":"l6T1ri6cqWCtEkmy","RTM_TOKEN":"006APP_IDIABVkygsLYuEGlBVKo+r7rsHsmQLZYt/gRZ4pezQayPmhJvA8okAAAAAEAAbLbcBPyeuYgEA6AM/J65i"}. Uncaught (in promise) RtmInvalidArgumentError: Error Code 3 - not a valid user id. A user enters a room name in the lobby page which is used to generate the RTC and RTM tokens. This is the lobby's JS code: <script> let form = document.getElementById('lobby__form') let handleSubmit = async (e) => { e.preventDefault() let room = e.target.room.value.toUpperCase() let response = await fetch(`/get_token/?channel=${room}`) let data = await response.json() let UID = data.userAccount let token = data.token let rtmToken = data.rtmToken sessionStorage.setItem('UID', UID) sessionStorage.setItem('token', token) sessionStorage.setItem('rtmToken', rtmToken), sessionStorage.setItem('room', room) window.open('/room/', '_self') } form.addEventListener('submit', handleSubmit) </script> I generate a random string which I use as a UID in a Django view which acts as my endpoint: from django.http import JsonResponse from agora_token_builder import RtcTokenBuilder from agora_token_builder import RtmTokenBuilder from django.utils.crypto import get_random_string import time def getToken(request): appId = 'APP_ID' appCertificate = 'APP_CERT' channelName = request.GET.get('channel') userAccount = get_random_string(length=16) role = 1 expirationTimeInSeconds = 3600 * 24 currentTimeStamp = time.time() privilegeExpiredTs = currentTimeStamp + expirationTimeInSeconds token = RtcTokenBuilder.buildTokenWithAccount(appId, appCertificate, channelName, userAccount, role, privilegeExpiredTs) rtmToken = RtmTokenBuilder.buildToken(appId, appCertificate, userAccount, role, privilegeExpiredTs) return JsonResponse({'token': … -
Send nested JSON data with image/file from postman: Django REST framework
I want to POST the following data: { "user": { "name": "user name", "email": "user@example.com", "phone_number": "01XXXXXXXXX", "user_type": "MGR" }, "img": "image_data", "manager_brands": [ 2, 1 ] } How can I pass this JSON data through postman? Challenges I am facing: This is a nested JSON data I am passing an image with it. Note: I wrote the nested serializers to GET/PUT/PATCH/DELETE requests. Everything works fine when I don't send an image (image is optional here). -
Django django.db.utils.ProgrammingError: syntax error at or near "None"
Context: I'm trying to do a simple CRUD app based on a visual studio tutorial and I'd like to add my own fields from my postgreSQL database. My models.py looks like this: from django.db import models # Create your models here. class Student(models.Model): student_id = models.CharField(auto_created=False, primary_key=True, serialize=False, verbose_name='student_id',max_length=100) gender = models.CharField(max_length=100) agegroup = models.CharField(max_length=100) year = models.FloatField() area = models.CharField(max_length=100) forms.py from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['student_id','gender','agegroup','year','area'] On my migrations folder I have a file called 0001_initial.py that looks like this: # Generated by Django 4.0.5 on 2022-06-17 00:57 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='a_student', fields=[ ('student_id', models.CharField(auto_created=False, primary_key=True, serialize=False, verbose_name='student_id')), ('gender', models.CharField(max_length=100)), ('agegroup', models.CharField(max_length=100)), ('year', models.FloatField()), ('area', models.CharField(max_length=100)) ], ), ] Installed apps on my settings.py script: # Application references # https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-INSTALLED_APPS INSTALLED_APPS = [ # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crudApp', ] My postgresql has this structure 5 relations called a_student, b_grades, c_lonely, d_stress, e_dinning a_student relation has attribures student_id(primary key, varchar), gender (varchar), agegroup (varchar), year (float), area (varchar) When running python manage.py … -
Got AttributeError when attempting to get a value for field `name` on serializer. 'QuerySet' object has no attribute 'name'
Djano Rest API serializer not returing the only dataset but also the field definitions. #Model: class Comp(models.Model): name = models.CharField(max_length=100) area = models.CharField(max_length=25,blank=True,null=True) #Serializer: from rest_framework import serializers class CompSerializer(serializers.ModelSerializer): class Meta: model = Comp fields = ('__all__') #View: @api_view(['GET']) def getComp(request,pk=None): co = Comp.objects.all() serializer = CompSerializer(co) print (serializer) return JsonResponse(serializer.data,safe=False) #Print Output: CompSerializer(<QuerySet [{'id': 1, 'name': 'My Company 1'}, {'id': 2, 'name': 'My Company 2'}]>): id = IntegerField(label='ID', read_only=True) name = CharField(max_length=100) area = CharField(allow_blank=True, allow_null=True, max_length=25, required=False) #API call error in Webbrowser: Exception Value: Got AttributeError when attempting to get a value for field name on serializer CompSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name' -
Django get next object given the current object in a queryset
I have a chapter model so in the chapter detail view i want the user to be able to navigate to the next and to previous chapter given the current chapter that he's viewing so what's is the most efficient way to that in django this is my chapter model class Chapter(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(blank=True,null=True,) module = models.ForeignKey(Module,on_delete=models.CASCADE,null=True,blank=True,) content = models.TextField() def __str__(self): return self.title i have seen some answers while they use the python list method to turn the queryset in to an array but i think maybe there is a better way -
Django-crontab doesn't execute tasks on Docker container
I've been working on this all week, and I don't seem to understand what I'm missing. The problem is simple, I've a container running a platform on Django, and I need to create a Cronjob for an smaller task, I created a test ask that executes every minute and just print a log just to test, but it is not working, while it installs cron, add the cronjobs, start the cron service, and I can see them in the crontab, they are just never triggered. When I first started, I had the Cron running in the same instance, but after reading this Question I found that I had to separate it in 2 instances, since apparently having Django running was afecting the cron service, so following that, this is how I have my files: docker-compose.yml version: '3' services: auth: build: context: ./ dockerfile: ./devops/Dockerfile args: [Bunch of parameters] container_name: auth volumes: - ./project:/app ports: - 8000:8000 environment: [Bunch of parameters] command: python manage.py runserver 0.0.0.0:8000 cron: build: context: ./ dockerfile: ./devops/Dockerfile args: [Bunch of parameters] container_name: cron volumes: - ./project:/app environment: [Bunch of parameters] command: cron -f Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY ./devops/requirements.txt . COPY ./project … -
Creating new data in a relational model with a fixed structure in rest_framwork - django
Suppose we want to create a new data This is the structure of JSON { x_t: "abc", x_p: 1234, o_t_1: "ert", o_t_2: "ersdfgt", o_t_n: "ertaa", } The ones that have the first o are stored in a separate table, and now when we have created the new data table X, we want to create the new data in table o, but we want to give the key of these X that were created at the same time to each of them. Now I will give a structure of the model that you can better understand model exp: class x (models.Model): x_t = models.CharField(max_length=100) x_p = models.IntegerField() class o (models.Model): x_Id = models.ForeignKey(x, on_delete=models.CASCADE) o_t = models.CharField(max_length=100) serializer.py: class create_x_serializer(serializers.ModelSerializer): class Meta : model = x fields = ["x_t","x_p"] # somthing here to creat O_t after x created and pass x_id to O Note : The request structure is immutable -
What is causing this error in my code 'unsupported operand type(s) for +=: 'NoneType' and 'int''
I am trying to create investment and also update the balance of the investment but I am getting this NoneType error. Below is my model and view code. class Investment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) amount = models.IntegerField(null=True) balance = models.IntegerField(null=True, blank=True) investment_id = models.CharField(max_length=10, null=True, blank=True) plan = models.ForeignKey(Plan, on_delete=models.CASCADE, null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return str(self.investment_id) def create_investment_view(request): if request.method == 'POST': investment_form = InvestmentForm(request.POST) if investment_form.is_valid(): investment = investment_form.save(commit=False) investment.balance += investment.amount investment.balance.save() investment.save() messages.success(request, 'your investment is successfull') else: messages.success(request, 'your investment is not successfull! Try again.') else: investment_form = InvestmentForm() context = {'investment_form': investment_form} return render(request, 'create-investment.html', context) -
Django admin cannot set form dynamically
I'm trying to set form fields dynamically and access it in admin.py in get_forms method, but unfortunately, dynamic data is not there. It seems like forms __init__ is being called after the get_form itself. Which would appropriate method in Django admin to retrieve already updated form fields? Here is simple example forms.py class MyForm(admin.ModelForm): title = forms.CharField(widget=forms.TextArea()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields.update({ 'some_field': forms.CharField(widget=forms.TextArea()) }) admin.py class AccountAdmin(admin.ModelAdmin): def get_form(self, request, **kwargs): form = super().get_form(request, obj, **kwargs) print(form.base_fields) return form -
how not to increase view count when someone sending more than one GET request
i am trying to count view of blog posts. here is my models.py class Blog(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE,related_name='post_author') blog_title=models.CharField(max_length=264,verbose_name='Put a Title') category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='category',default=None) slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True) blog_content=models.TextField(verbose_name='what is on your mind?') blog_image=models.ImageField(upload_to='blog_images',verbose_name='Image') publish_date=models.DateTimeField(auto_now_add=True) update_date=models.DateTimeField(auto_now=True) view_count=models.IntegerField(null=True,default=0,blank=True) class Meta: ordering = ('-publish_date',) here's how i am increasing the view count of a post for every GET request def blog_details(request, slug): blog = Blog.objects.get(slug=slug) if request.method == 'GET': blog.view_count =blog.view_count+1 blog.save() *skipping giving the whole(irrelevant to the question) code of the function* Now how can i increase view count of a post for the first GET request from a user(registered or anonymous) by 1. If they send more get request view count would not be increased. Pardom mistake and THANK YOU in advance -
Django admin give user permission on some records and linked foreign key records
In Django Admin Dashboard, I have to give access to a particular client such that he can view all related cases. But not all cases. In other words, give a user access control to some of the records and foreign key records. But not all. What is the easiest way in Django? class Client(models.Model): name = models.CharField(max_length=200) class Case(models.Model): client_name = models.ForeignKey(Client, on_delete=models.SET_NULL) name = models.CharField(max_length=200) -
how to click on a row in html table to open a page to edit that row's content
in my html code Ive created a table, I want to click on row specifically the id cell for it to direct me to my edit page in my views.py file. Im very new to django and im not sure how to go about this. please let me know. -
Show field many to many in django admin panel
I use this functions (cedi) but dont work.I want to show field nombre of Cedi model in panel admin of Campania model. The name of the column appear but the info or every instance doesn´t. @admin.register(Campania) class CampaniaAdmin(ImportExportMixin, admin.ModelAdmin): # conecta con CampaniaResource resource_class = CampaniaResource list_display = ('nombre', 'descripcion', 'cedi') list_filter = ('nombre', ) readonly_fields = ('fecha_creacion', 'fecha_modificacion') search_fields = ['nombre',] def cedi(self, obj): return ", ".join([i.nombre for i in obj.cedis.all()]) models class Campania(models.Model): nombre = models.CharField(verbose_name='campaña', max_length=200, primary_key=True) fecha_creacion = models.DateTimeField(auto_now_add=True) fecha_modificacion = models.DateTimeField(auto_now=True) descripcion = models.TextField() # campo manytomany cedis = models.ManyToManyField(Cedi) def __str__(self): return self.nombre class Cedi(models.Model): nombre = models.CharField(max_length=200, primary_key=True) fecha_creacion = models.DateTimeField(auto_now_add=True) fecha_modificacion = models.DateTimeField(auto_now=True) # campo ForeignKey pais = models.ForeignKey(Pais, on_delete=models.CASCADE) def __str__(self): return self.nombre