Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble in using Postgresql database in django 2
I have just installed postgresql database in my system. I successfully set postgresql as my default database in django and it worked too. now the problem is i want to create new database to use. i know how to create it from pg4admin but not sure what password and username should i use for that database. and what this command means (psql -U postgres) ? what is superuser ? how to create new one? what password should i use for newly created database ? I might sound crazy and stupid but thats how much i confused. Help me guys pls... -
Django formset : Save multiple forms from formset
I spent several days in order to add dynamically forms to formset and I find a way to do that. But I have a little issue with forms saving because it just saves the first form and not all forms from formset. This is my template : <fieldset> <legend class="title"><span class="name">{% trans 'Document form' %}</span></legend> {{ DocumentFormSet.management_form }} <div id="form_set"> {% for form in DocumentFormSet.forms %} <div class='formset-document'> <table class='no_error'> <div class="row"> <div class="col-xs-3"> {{ form.title|as_crispy_field }} </div> <div class="col-xs-3"> {{ form.language|as_crispy_field }} </div> <div class="col-xs-3"> {{ form.format|as_crispy_field }} </div> <div class="col-xs-3"> {{ form.upload|as_crispy_field }} </div> </div> </table> </div> {% endfor %} </div> <br> <input type="button" class="btn btn-default" value="Add More" id="add_more"> <div id="empty_form" style="display:none"> <table class='no_error'> <div class="row"> <div class="col-xs-3"> {{ DocumentFormSet.empty_form.title|as_crispy_field }} </div> <div class="col-xs-3"> {{ DocumentFormSet.empty_form.language|as_crispy_field }} </div> <div class="col-xs-3"> {{ DocumentFormSet.empty_form.format|as_crispy_field }} </div> <div class="col-xs-3"> {{ DocumentFormSet.empty_form.upload|as_crispy_field }} </div> </div> </table> </div> </fieldset> This is my JS part : $('#add_more').click(function () { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); And this is my views.py file : def form_valid(self, form): context = self.get_context_data() document = context['DocumentFormSet'] if document.is_valid(): self.object = form.save() document.instance = self.object document.save() return super(PublicationCreateView, self).form_valid(form) I know I have to loop over … -
Pass Model Variable to url() in background attribute in style html tag Django
I am trying to pass the location of a static image to the url() attribute of a background image contained in the style property of a jumbotron div tag. I've tried a few different things as shown below: This is in my park_detail.html {% extends 'full_base.html' %} {% load tags %} {% load static %} {% block main_content %} <div class = "jumbotron" style ="background-image:linear-gradient(rgba(255,255,255,.6), rgba(255,255,255,.6)), url({% static {{park.imageloc}} %});background-size:100%;background-position:left center; background-repeat:no-repeat"> This attempt returns an error: TemplateSyntaxError at /waittimes/park/2/ Could not parse the remainder: '{{park.imageloc}}' from '{{park.imageloc}}' I also attempted this as the bottom line: <div class = "jumbotron" style ="background-image:linear-gradient(rgba(255,255,255,.6), rgba(255,255,255,.6)), url({% static '{{park.imageloc}}' %});background-size:100%;background-position:left center; background-repeat:no-repeat"> and it could not find the image at location: /static/%7B%7Bpark.imageloc%7D%7D Thanks in advance -
How can I import a markdown file into Djano Zinnia?
I'm using Django 2.0 and latest install of Zinnia. I have a blog built elsewhere and am using markdown files. I'd like to copy those markdown files to the new blog (in zinnia). Is there a way to do this? -
django AbstractBaseUser
I've been working on a Django project and playing around with the AbstractBaseUser, I've been able to set the attributes I need reading the documentation, but there's a BooleanField a can't make happen which is the most important, because is the one that would differentiate that type of user from the others. class User(AbstractBaseUser): username = models.CharField(_('username'), max_length=30, help_text=_('Required. 30 characters or fewer. Letters, digits and ' '@/./+/-/_ only.'), validators=[ validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username. ' 'This value may contain only letters, numbers ' 'and @/./+/-/_ characters.'), 'invalid'), ], error_messages={ 'unique': _("A user with that username already exists."), }) #first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), blank=True, unique=True) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_admin = models.BooleanField(_('superuser status'), default=False) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) is_UserTypeB = models.BooleanField(_('typeB or not'), default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) objects = UserManager() In the migration folder I can see the code adding the staff/admin/active booleans, but not the usertypeB, I'm even using a DB software to see the tables being … -
Django modeltranslation slug problem. When i change language dont go right url
modeltranslation... i change title, content and slug sections on my translation.py. Everything work is fine but i have a problem. let me try to explain; i have one post in my website and this post "slug" like this; slug_en = some_en_slug slug_fr = some_fr_slug And i have one language changer on my navbar. {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <form action="{% url "set_language" %}" method="post" class="navbar-form navbar-right"> {% csrf_token %} <div class="form-group"> <select name="language" class="form-control" onchange="this.form.submit()"> {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %}selected="selected"{% endif %}> {{ language.name_local }} </option> {% endfor %} </select> </div> </form> Actually this lang. changer working fine. This is change all slug href url's on outside post... But this didnt change slug url in post page. when i go https://example.com/en/en_slug and after try change language my browser is go https://example.com/fr/en_slug and i see 404 page.. i need to go https://example.com/fr/fr_slug link after change language ... I dont have any idea for this. I would like your help. urls.py from django.urls import path from . import views from django.utils.translation import gettext_lazy as _ app_name = "article" urlpatterns … -
How to use a local API with a Vue app served at a different port?
I'm helping someone get a Django + Vue app up and running and one issue we're running into is how to have the Vue app hot-reload while also being able to interact with the local Django server. In production the Django server will serve the Vue app, and npm run build puts the Vue app's assets in the Django project's templates/ and static/ folders. When we run the Django server (python manage.py runserver), the server is running at localhost:8000. When we run npm run serve (to get the benefits of hot reloading), the Vue app is being served at localhost:8080. If I do a GET request from the Vue app to /exampleEndpoint, it goes to localhost:8080/exampleEndpoint, thus not hitting the Django server. -
ecommerce seller payout - Advantages of monthly payment over immediate payment
I see that for every transaction, payment gateways normally charge 1-2% on the total amount. Even though the payment gateways commission is going to be the same, why do most of the ecommerce websites like flipkart, amazon, etc. prefer monthly payouts to the sellers as against the immediate payment (once the product is delivered and the product-return period is over)?. I am using spring framework to develop our ecommerce website and we are planning to use @async annotation to create a background task that will be invoked at the last day of the month and pay the amounts to the sellers. Is this the correct design to pay the sellers on monthly basis or there exists any better options for monthly payment? -
Django - Retain Search Parameters between Server Round Trips
I have a list page with some filter, sort and search functionality (which basically creates a QuerySet in the view that then returns the adjusted (filtered, sorted, searched) data). On this list page, I also have a detail view that displays the object details. This all works fine, but when I navigate to another detail object, the search, filter, sort parameters get reset to their default. How can I retain the search parameters beyond a server round trip? Thanks! -
Sending x-csrf-token with axios request (Django/Reactjs)
I'm trying to send an x-csrf-token with an axios delete request to my django api. Here is the function: export const deleteTripReport = (tripReport) => { return dispatch => { dispatch(deleteTripReportsPending()); axios.delete(`http://localhost:8000/api/v1/reports/${tripReport}`) .then(response => { dispatch(deleteTripReportsFulfilled()); }) .catch(err => { dispatch(deleteTripReportsRejected(err)); }) } } I've tried adding axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' below my import. The django server returns 'Forbidden (CSRF Cookie not set'. I've tried adding headers {headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': "mkTF7lcI4BVl42lJcFzqNbfeVvoVfLSH7e01kznsEQLYFEoWdchL0tuKZ5HeGnOa", }} with my actual cookie. Then the django server returns OPTIONS instead of DELETE, and the console logs missing 'x-csrf-token'. I'm running the django server on port 8000 and the react server on 3000 for hot reloads, but I can run build, and both will run on 8000, but currently that is failing as well. -
Django custom form registration
I have this form html template. auth.html <form id='registration-form' method='post' action={% url 'accounts:register' %}> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control input-upper" id="fullname" placeholder="John Doe" name="fullname" required><br> <input type="text" class="form-control input-upper" id="username" placeholder="Username" name="username"><br> <input type="email" class="form-control input-upper" id="email" placeholder="Email" name="email" required><br> <input type="text" class="form-control input-upper" id="organization" placeholder="Organization" name="organization" required><br> <input type="password" class="form-control input-upper" id="password" placeholder="Password" name="password" required><br> <input type="password" class="form-control input-upper" id="password" placeholder="Confirm Password" name="password" required><br> <small>By registering you agree to our <a href="{% url 'tos' %}">terms and conditions</a></small> <button type="submit" value='register' id='reg-submit-btn' class="btn btn-primary btn-block btn-signup-form">SIGN UP</button> <button type="button" class="btn btn-primary btn-block btn-sign-linkedin" href="{% url 'social:begin' 'linkedin-oauth2' %}?next={{ next }}">Sign up with LinkedIn</button> <p class="text-already">Already have an account? <a href="" >LOGIN</a></p> </div> </form> MOdel Userprofile.py class UserProfile(models.Model): """ Profile for the User Model """ user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile', verbose_name='other Details', ) phone = models.CharField(max_length=11, default='', blank=True, null=True) organization = models.CharField(default='', max_length=300, blank=True) referral = models.OneToOneField( Referral, on_delete=models.CASCADE, related_name='profile', verbose_name='profile Details', null=True) email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username + '\'s profile' def activate(self): """" Activates account after email is confirmed """ self.email_confirmed = True self.user.is_active = True self.save() self.user.save() Views.py @transaction.atomic def register(request): """Process registration of new users""" if request.user.is_authenticated: return JsonResponse({'status': 'loggedin'}) status = … -
XOAUTH2 Invalid SASL argument in Django
I create Django project and in this project i have one moment, it authenticate in gmail by XOAUTH2. This code work local(if i create python project and run it): is_authenticate = False imap_conn = imaplib.IMAP4_SSL(host='imap.gmail.com', port=993) imap_conn.debug = 4 try: imap_conn.authenticate(mechanism='XOAUTH2', authobject=lambda x: auth_string) is_authenticate = True except BaseException as e: print(e) return is_authenticate but in django project i have exception: AUTHENTICATE command error: BAD [b'Invalid SASL argument. n1mb22847377ltj'] this is debug information: 06:55.79 > b'HLKK1 AUTHENTICATE XOAUTH2' 06:55.86 < b'+ ' 06:55.86 write literal size 304 06:56.05 < b'+ eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==' 06:56.05 write literal size 304 06:56.24 < b'HLKK1 BAD Invalid SASL argument. n1mb22847377ltj' 06:56.24 BAD response: b'Invalid SASL argument. n1mb22847377ltj' -
django order_by beside one value
I'm not sure there's a django way to do it. I need to do an order_by in an ascending order, but objects with a specific value (-1) need to be last. The model: class OrderOption(models.Model): # fields.. sort_order = models.IntegerField(default=-1) I want: OrderOption.objects.all().order_by("sort_order") while objects with sort_order=-1, should be last in the queryset. Is there a django (or even SQL) way to do it? -
django SelectDateWidget formating month as 3 alpha characters
When, in settings, I have {USE_L10N = True} SelectDateWidget displays as {j F Y} When, in settings I have {USE_L10N = False}, and {DATE_FORMAT = 'j N Y'} the SelectDateWidget format does not change. It still displays the full month name (e.g. November) instead of the abreviated (e.g. Nov) Is there a way to make SelectDateWidget to display the dropdown boxes in j N Y format? I beleived from this previous post that it should follow DATE_FORMAT -
"OperationalError: no such table: django_site" when running makemigrations with empty database
I have inherited a Django 1.11.6 application from another developer. Now after I have made a lot of changes to the code and data model, I want to re-create the sqlite database from scratch. But when I run manage.py makemigrations in the project directory (no migration files and database present), I am getting the following error message: django.db.utils.OperationalError: no such table: django_site 'django.contrib.sites' is present in the INSTALLED_APPS and there is a SITE_ID defined. Every solution I found on stackoverflow and other sources didn't fix the problem. How can I get past this and continue developing the application with a empty database? -
What are the typical use cases for pre-save, post-save, pre-delete, post-delete signals in Django?
Could not find much in the docs here regarding use cases. However, I assume something along these lines: Pre-Save: Used for calculated fields, example, we might want to calculate the age from date of birth and save that in the database. Post-Save: Used for operations that involve other objects in the database, for example, updating a review might require a re-calculation of the average rating for the movie. Pre-Delete: Honestly, no idea. Post-Delete: Probably similar to post-save, in that it affects other models. What are the most common use cases for these signals in general? Thanks. -
DRF + DREST : how to ensure during tests, the serializer is compiled with the setUp test data?
Using Django: 1.11 Python 3.6 DRF: 3.7 DREST (aka dynamic rest): 1.8 I have a serializer written like this: class SubProjectAsFKWithAttachedFieldsSerializer(DynamicModelSerializer): # attached_fields = AttachedFieldSerializer(embed=True, many=True) try: scope_object = UgField.objects.get(dotted_path='global.scope') scopes = DynamicRelationField( AttachedFieldWithDirectValuesSerializer, source='attached_fields', many=True, embed=True, read_only=True, queryset=AttachedField.objects.filter(ug_field=scope_object) ) except ObjectDoesNotExist: scopes = DynamicRelationField(AttachedFieldWithDirectValuesSerializer, source='attached_fields', many=True, read_only=True, embed=True) Currently, in almost all my tests.py in the setUp method, I have self.global_scope_field = UgFieldFactory(dotted_path='global.scope', name='Scope') For some reason, this line scope_object = UgField.objects.get(dotted_path='global.scope') keeps failing despite that I have "instantiated" using a DjangoModelFactory What should I do to ensure that line always passes when I run tests? -
Django admin change list hide checkbox
Is it possible to hide some checkboxes in the admin change list. I would rather not extend it. I am after something like this if obj.name == 'read only': #hide the checkbox of that row Thanks Grant -
How do I make a table in HTML static so it does not move when the window resizes?
I have a table that re positions itself to fit when the window size changes. I want it so the table never changes positions. Normal: Overlaps when window is smaller: html: <div style="float:left; margin-left:-440px"> <h4> Search Files </h4></div><br><br> <input id="myInput" type="text" name="myInputSearches" placeholder="Search.." title="Search for documents" style="margin-left:-440px"><br> <div class="noResults" align="left" style="float:left; display:none; margin-left:-440px; color:red"><b><i>No Match Found</i></b></div> <div style="padding-top:20px"> <div style="float:left; margin-left: -450px; width:50%; padding:10px"> <h4>Uploaded Files</h4> <table class="newtable" style="overflow-y:scroll; height:430px; width:1300px; display:block"> <thead> <tr> <th><div style="width:350px">Document name</div></th> <th><div style="margin-left:10px; width:100px">Client</div></th> <th><div style="margin-left:10px; width:120px">Date uploaded</div></th> <th><div style="margin-left:10px">File</div></th> </tr> </thead> <tbody id="myTable"> {% for file in docs %} <tr> <td><div style="width:350px"><a href="/media/{{ file.Filename }}">{{ file.Document_name }}</a></div></td> <td><div style="margin-left:10px; width:110px">{{ file.Client }}</div></td> <td><div style="margin-left:10px; width:120px">{{ file.Date }}</div></td> <td><div style="margin-left:10px">{{ file.Filename }}</div></td> </tr> {% endfor %} </tbody> </table> </div></div></div> </div> -
DRF serializer.save() not saving to database
I have an api that will do a patch on a resource (MyUser). It validates ok and seems to save the object, however when querying the database the changes have not been saved. class UserSignupView(generics.UpdateAPIView): serializer_class = MyUserSerializer def get_object(self, email): obj = MyUser.objects.get(email=email) self.check_object_permissions(self.request, obj) return obj def patch(self, request): print(request.user) user = self.get_object(request.user.email) print(user.street) serializer = MyUserSerializer(user, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() savedUser = MyUser.objects.get(email=request.user.email) print(savedUser.street) print(serializer.data) return Response(serializer.data) class MyUserSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ( 'id', 'first_name', 'last_name', 'email', 'phone_number', 'street', 'locality', 'city', 'county', 'postcode') Looking at the print statements I get: user@example.com None 123 Fake Street MyUser object It returns the correct serialised data which contains the changes but the database does not have the changes. The database connection is ok as I can query it and make other reads/writes/etc. It's pretty much the same as the UpdateModelMixin except I've had to override the get_object with a passed in parameter. -
Error with importing module named middleware
After transfering a django project(working) from one server to another, when trying to run the application on the new server I face up the error: Django version 1.11.16, using settings 'geolocator.settings' Starting development server at http://example.example.com:2000/ Quit the server with CONTROL-C. Unhandled exception in thread started by <function wrapper at 0x7f23d7ab3668> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 146, in inner_run handler = self.get_handler(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 67, in get_handler return get_internal_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 44, in get_internal_wsgi_application return get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 14, in get_wsgi_application return WSGIHandler() File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 151, in __init__ self.load_middleware() File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 80, in load_middleware middleware = import_string(middleware_path) File "/usr/local/lib/python2.7/dist-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named middleware In settings.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'intranet', 'bootstrap3', 'registration', 'crispy_forms', 'fm', 'dal', 'dal_select2', 'rest_framework', 'django_filters', 'django_crontab', 'request', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'request.middleware.RequestMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] It seems having to do with WSGI but I am not sure what exactly goes wrong. Any suggestion? -
'using' is an invalid keyword argument for this function (serializer.save(using='tableNew'))
Im trying to save a record in a table (here the selection of table is dynamic). I'm able to pull the records from the respected table's dynamically. where as while saving the data ended with an error {'using' is an invalid keyword argument for this function} below is the code. Views.py def create(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save(using='users_1') And my Serializer.py contains class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields = ('id','firstname', 'lastname', 'mobile_number') def create(self, validated_data): return JobSeekers.objects.create(**validated_data) -
form clean method vs model clean method vs model field validator
I have a model with the field facebook_link. With the help of a regular expression I want to validate if this link is really a facebook link. The user can enter the facebook link in a form. Should I place my validation in the clean method of the form field, in the clean method of the model field or should I use a a custom validator -
Django ValueError: Cannot assign "False": "User.partner" must be a "Partner" instance
Hello I am working on a Django project but after a few modifications I have come unstuck with an error. This is the error I get when I make my Partner model live ValueError: Cannot assign "False": "User.partner" must be a "Partner" instance. This is my model class Partner(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key='True') username = models.CharField(max_length=25) password = models.CharField(max_length=25) company = models.CharField(max_length=25) key_contacts = models.CharField(max_length=50) primary_service = models.CharField(max_length=50) secondary_service = models.CharField(max_length=50) def __str__(self): return str(self.user.username) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Partner.objects.create(user=kwargs['instance']) Any tips on how to resolve please -
Is it possible to serialize the same field twice?
In my Django Rest Framework, my models look like this: class Country(models.Model): ''' Describes the countries, as well as territories of the world. ''' name = models.CharField(max_length=255, null=True, blank=True) top_level_domain = JSONField(null=True, blank=True) alpha2code = models.CharField(max_length=255, null=True, blank=True) alpha3code = models.CharField(max_length=255, null=True, blank=True) calling_codes = JSONField(null=True, blank=True) capital = models.CharField(max_length=255, null=True, blank=True) alt_spellings = JSONField(null=True, blank=True) region = models.CharField(max_length=255, null=True, blank=True) subregion = models.CharField(max_length=255, null=True, blank=True) population = models.IntegerField(null=True, blank=True) latlng = JSONField(null=True, blank=True) demonym = models.CharField(max_length=255, null=True, blank=True) area = models.FloatField(null=True, blank=True) gini = models.FloatField(null=True, blank=True) timezones = JSONField(null=True, blank=True) borders = JSONField(null=True, blank=True) native_name = models.CharField(max_length=255, null=True, blank=True) numeric_code= models.CharField(max_length=255, null=True, blank=True) currencies = models.ManyToManyField(Currency) languages = models.ManyToManyField(Language) flag = models.CharField(max_length=255, null=True, blank=True) regional_blocs = models.ManyToManyField(RegionalBloc, blank=True) cioc = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.name and class TripReport(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) countries = models.ManyToManyField(Country, blank=False, related_name='trip_countries') title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title I've got a serializer that looks like this: class TripReportSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField(slug_field='username', queryset=User.objects.all()) class Meta: model = TripReport fields = ('__all__') One of the fields is 'countries'. Right now it displays the pk of my country object associated with my Trip Report. It is very easy …