Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to run migrate in Django using jython
i am using jython 2.7. when i am trying to migrate using the command Jython manage.py migrate APP_NAME the following error is showing. Please provide a CPython 2.7 bytecode file (.pyc) to proceed, e.g. run python -m py_compile /scratch/code/Stayflexi/StayflexiApp/idb_platform/migrations/0001_initial.py and try again. Alternatively provide proper CPython 2.7 execute command via cpython_cmd property, e.g. call jython -J-Dcpython_cmd=python or if running pip on Jython: pip install --global-option="-J-Dcpython_cmd=python" <package> -
how to make youtube dl download to the user's browser
I have this code that allows th user to search a video then it grabs the youtube video, after that i want the user to be able to download the video they search for to their system, but instead it is downloading to the project file. here is the code: from __future__ import unicode_literals import youtube_dl options = {'outtmpl': '%(title)s'+'.mp4'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download(['https://www.youtube.com/watch?v=GD64pQOs1FQ']) thanks!!! -
Django override custom admin site's templates
I have two admin sites in my django app. One named admin and the other named owneradmin. I want to override their templates separately. Is there a way to do it ? -
ParseError at /landing_page not well-formed (invalid token):
Im working in django application to connect db im using mysql version 8.0, so my application is i created a UI if i upload a XML file it will generate a pdf. in that my application is working well. justnow i changed mysql server version 5.7. i connected my db, if i run my application while submit my xml file it showing a error ParseError at /landing_page not well-formed (invalid token): line 2060, column 70 tree = ET.parse(filename) #getting error in this line root = tree.getroot() -
Django FormView dont redirect on successfull POST
I'm currently writing a Chat-Application. In order to take User-Input, I use a Form and thus a FormView and a custom Form, following the Django-Docs. I have to set a success_url, but neither want to be redirected to another page on a successful POST, nor want i to reload the chat-page. How Do i go about that? I've read the following Post: Django FormView, Return without redirecting, but I dont really understand the Point of the Answer. Should I really avoid not redirecting? And if not, can I really achieve this with JQuery-Ajax? Doesn't that conflict with Django's success_url? Thanks for your Answers! -
Django with MySQL cluster
I was about to move my Django DB to a MySQL cluster. I have configured mysqlrouter and tested the connection to the db from the command line using the following command mysql --user=matrix --password --host=localhost --port=6446 --protocol=tcp and when I tried the same configuration (except protocol) on django it fails. And i'm unable to find a way to add protocol as an option in django. following is the django db configuration 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'matrix_db', 'USER': 'matrix', 'PASSWORD': 'matrix', 'HOST': '127.0.0.1', 'PORT': '6446', }, any help will be highly appreciated. Thanks in Advance. -
Django create a dropdown from a database model and save in another model
So I am new to Django and Python and would like to attempt the following. Create a dropdown list from the data in a model and save the data in another model . However everytime i render the form , it is invalid and does not display the template, Any help would be greatly appreciated. Please help where I am going wrong Models.py class Part(models.Model): category = models.TextField(default = ' ') def __str__(self): """String for representing the Model object.""" return self.category class UserItem(models.Model): name= models.CharField(max_length = 50, null=True) category = models.ForeignKey(Part, on_delete=models.SET_NULL, null=True) def __str__(self): """String for representing the Model object.""" return self.category Forms.py class DropDown(forms.ModelForm): name = forms.CharField() parts = forms.ModelChoiceField(queryset=Part.objects.values_list('category', flat=True).distinct()) class Meta: model = UserItem fields = ('name', 'category',) Views.py def index(request): query_results = Part.objects.all() #part_list = DropDown() if request.method == 'POST': form = DropDown(request.POST) if form.is_valid(): form.save() return render(request,'index.html', {'query_results': query_results }, {'form': form } ) else: print("invalid") print (DropDown.errors) form = DropDown() return HttpResponseRedirect(reverse('genre_create') ) -
How can i write unit test for class based view in django?
DISCLAIMER: I'm new to Django development. Say I have an ApplicationForm page view in my application as follows class Application(View): def get(self, request, *args, **kwargs): ... ... ... response = TemplateResponse(request, self.template_name, self.context) response.delete_cookie(conf.TRANSACTION_COOKIE_NAME) return response def post(self, request, *args, **kwargs): ... ... ... context.update({ 'error': 1, 'error_status': de_status_id, 'error_msg': error_msg, 'channel': channel, 'form': self.get_form_for_channel(channel)(self.post_params, channel=channel), }) return render(request, get_landingpage_template(channel, request.path, version), context) How can I write the unit test for this using django.test What I have tried is class BaseViewTest(object): longMessage = True # More verbose messages view_class = None def setUp(self): self.client = Client() def tearown(self): del self.client def is_callable(self, path): resp = self.client.get('/{0}'.format(path)) self.assertEqual(resp.status_code, 200) def is_returning_correct_view(self, path, view): resp = resolve('/{0}'.format(path)) self.assertEqual(resp.func.__name__, view) def is_correct_template(self, path, template): resp = self.client.get('/{0}'.format(path)) self.assertTemplateUsed(resp, template) And also unit test for checking correct template class TestApplicationPageView(BaseViewTest, SimpleTestCase): def test_application(self): self.is_callable('apply/') self.is_returning_correct_view('apply/', ApplicationPageHandler.as_view().__name__) self.is_correct_template('apply/', 'application.html') How can I write unit tests for get and post methods? -
Not displaying the popups and markups in the leaflet for the already inserted map using leaflet?
Here I want to add the code for search bar and popups: Unfortunately , popups are not showing in the map. Separetly , it is working for popups and searchbar. In this project, I am using the django and retreiving the data and showing the popups.I will add the image for the popups which is worked individually. **Actually i merged the two files here but search bar is only working please provide the code ** Thank you in advance <html> <head> {%load static %} <meta charset="utf-8" /> <title>Searching map services</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" /> <!-- Load Leaflet from CDN --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script> <!-- Load Esri Leaflet from CDN --> <script src="https://unpkg.com/esri-leaflet@2.3.3/dist/esri-leaflet.js" integrity="sha512-cMQ5e58BDuu1pr9BQ/eGRn6HaR6Olh0ofcHFWe5XesdCITVuSBiBZZbhCijBe5ya238f/zMMRYIMIIg1jxv4sQ==" crossorigin=""></script> <!-- Load Esri Leaflet Geocoder from CDN --> <link rel="stylesheet" href="https://unpkg.com/esri-leaflet-geocoder@2.3.2/dist/esri-leaflet-geocoder.css" integrity="sha512-IM3Hs+feyi40yZhDH6kV8vQMg4Fh20s9OzInIIAc4nx7aMYMfo+IenRUekoYsHZqGkREUgx0VvlEsgm7nCDW9g==" crossorigin=""> <script src="https://unpkg.com/esri-leaflet-geocoder@2.3.2/dist/esri-leaflet-geocoder.js" integrity="sha512-8twnXcrOGP3WfMvjB0jS5pNigFuIWj4ALwWEgxhZ+mxvjF5/FBPVd5uAxqT8dd2kUmTVK9+yQJ4CmTmSg/sXAQ==" crossorigin=""></script> <style> body { margin:0; padding:0; } #map { position: absolute; top:0; bottom:0; right:0; left:0; width: 80%; height: 700px;} </style> </head> <body> <div id="map"></div> <script> var map = L.map('map').setView([16.91587, 82.159257999999], 10); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); var arcgisOnline = L.esri.Geocoding.arcgisOnlineProvider(); L.esri.Geocoding.geosearch({ providers: [ arcgisOnline, L.esri.Geocoding.mapServiceProvider({ label: 'States and Counties', url: 'https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer', layers: [2, 3], searchFields: ['NAME', 'STATE_NAME'] }) ] }).addTo(map); var … -
Unable to savedata to database in Django using Model and Forms
I trying to to create a database panel for a restaurant app where a user can add, remove, view and create a menu for the restaurant. In this the user can add the name, cuisine, category(veg/non veg) and cost as details of the menu item. Here is my Models.py: class Cuisine(models.Model): cuisine = models.CharField(max_length=15) def __str__(self): return self.cuisine class Meta: verbose_name_plural = 'cuisines' class Category(models.Model): category_type = models.CharField(max_length=9) def __str__(self): return self.category_type class Meta: verbose_name_plural = 'category type' class Item(models.Model): name = models.CharField(max_length=50) cost = models.IntegerField() cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.name Here is Forms.py: class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['name', 'cost'] class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ['category_type'] class CuisineForm(forms.ModelForm): class Meta: model = Cuisine fields = ['cuisine'] And below is my Views.py: @login_required() def add_item(request): if request.method == 'POST': itemform = ItemForm(request.POST or None) catform = CategoryForm(request.POST or None) cuisineform = CuisineForm(request.POST or None) if itemform.is_valid(): item = itemform.save(commit=False) ct = catform.save(commit=False) cui = cuisineform.save(commit=False) item.name = request.POST.get('name') cui.cuisine = request.POST.get('cuisine') ct.category = request.POST.get('category') item.cost = request.POST.get('cost') item.save() ct.save() cui.save() messages.success(request, 'Item added successfully!!') else: messages.warning(request, 'Unable to add the item.') return redirect('add_item') else: item_list … -
Updating instance of model in Django
I'm a beginner and trying to make a to-do list app. I want the app to display only the tasks that have not yet been marked completed (by the user). models.py: class Task(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) start_date = models.DateTimeField() end_date = models.DateTimeField() priority = models.BooleanField(default=True) completed = models.BooleanField(default=False) def __str__(self): return self.title View: def task(request): task = Task.objects.filter(user=request.user, completed=False) queryset = task.order_by('-start_date') context = { 'task': queryset, } return render(request, 'task-list.html', context) I want to display an option (a link/button) for the user, which upon clicking would update the instance 'completed' to True (and so the task will no longer be displayed). I would like to use an achor tag as the button. something like <a href="{% url 'complete' id=obj.id %}">completed</a> I have created this view: def task_completed(request, id): get_task = Task.objects.filter(id=id) get_task.instance.completed = True return redirect('task:task-page') The urls.py: app_name = 'task' urlpatterns = [ path('', home, name='home-page'), path('task', task, name='task-page'), path('complete', task_completed, name='complete'), upon loading the task-list page, it shows Reverse for 'complete' not found. 'complete' is not a valid view function or pattern name. any help would be appreciated! -
Display SQL results in Django Admin interface
I have set up a Django Admin Interface (django.contrib.admin) to see my data from my Mysql Database. I would like to know if it's possible to make specifics SQL queries ? So far, all my tables are registered to be displayee in the Django Admin Dashboard by doing for example : # Register your models here. @register(User) class User(ModelAdmin): list_display = ('name', 'city') list_filter = ('name',) search_fields = ('name',) @register(Object) class Object(ModelAdmin): list_display = ('name', 'object_description', 'owner', 'acquired_date') list_filter = ('name',) Let's say, I would like to display a specific table in the dashboard showing all the users with the appropriate object and the date of acquisition. How could I do that ? Or, better, how can I display data from multiple JOIN query ? I saw the querySet function but I did not see any examples to do this kind of things. Thank for your help -
Django image.url returning values appended with random text
I am quite new to Django. I have made a django project, where I upload some images through admin panel. And a template which takes values from the model and display the images accordingly. This is working fine on Localhost and after first commit. Then when I checked after next commit no images can be found! Later I realized, media directory is being overwritten, and then I added a .gitignore file which contains: *.log *.pot *.pyc __pycache__/ local_settings.py db.sqlite3 media .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ then, just for checking purposes, I edited some comments and recommitted. But same error happened again! Media folder is overwritten again! Could anyone highlight what I am missing here? my file structure: ├───media │ └───media ├───Personal_website │ ├───migrations │ └───templatetags ├───Resume │ └───migrations │ └───__pycache__ ├───templates │ ├───Personal_website │ ├───Resume │ └───Visitors ├───manage.py ├───requirements.txt ├───.gitignore ├───procfile ├───db.sqlite3 -
Django - itertools.chain on different models with different cols
I have two different models each with different columns connected by one id. I want to create a searh page that would search the result from both the models, joining them with the id and show the results. This is the simple sql i want to execute: 'SELECT "SSDatabase_metadataform".*, "SSDatabase_uploadmeta"."datafile", CASE WHEN "SSDatabase_metadataform"."Embargo_Time" <= current_date THEN "SSDatabase_uploadmeta"."path_id" END AS link from "SSDatabase_metadataform" INNER JOIN "SSDatabase_uploadmeta" ON "SSDatabase_metadataform"."id" = "SSDatabase_uploadmeta"."path_id" order by "id"' I creates a search query, and it works fine showing the data from one of the model and it does not show the col form the second model. I am not sure how to write a join statement to fetch the corresponding data from the second model class SearchResultsView(ListView): template_name = 'searchresults.html' def get_queryset(self): # new query = self.request.GET.get('q') meta_list= Metadataform.objects.filter(Q(id__icontains=query) | Q(Authors_Name__icontains=query) | Q(Affliations__icontains=query) | Q(Methods__icontains=query) | Q(Instruments__icontains=query) | Q(Software__icontains=query)| Q(Models__icontains=query)| Q(Device__icontains=query)) dataset_list = uploadmeta.objects.filter(Q(datafile__icontains=query)) object_list = list(chain(meta_list, dataset_list)) return object_list And this is my html page. The datafile from the other model is not fetched <table class="table table-striped"> <thead> <tr> <th>Meta ID</th> <th>Author</th> <th>Affiliations</th> <th>Methods</th> <th>Instruments</th> <th>Models</th> <th>Device</th> <th>Configuration</th> <th>Download</th> </tr> </thead> <tbody> {% if object_list %} {% for a in object_list %} <tr> <td><a id="idclicked" … -
how to set pagination in SQL query as per page?
how to set pagination as per page in SQL query, i tried with django default pagination but it didn't worked in my code and i am direct fetching data using SQL raw-query instead of ORM. i think the another way is set pagination using SQL query LIMIT or OFFSET but i have no idea about url-endpoint when i am searching next-page. class Order_ListAPIView(APIView): def get(self,request,format=None): if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) ... ... #rest_code ... return Response({"order_data":order_data},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) -
How to disable suffix generated when upload on a FileField in Django?
I have a model which has a FileField. When I upload on that field, a suffix is generated. How do I disable adding this suffix? class RawFile(models.Model): file = models.FileField( upload_to=settings.RAW_IMAGE_UPLOAD_PATH, null=True, max_length=500 ) When I upload something like this: MFC_CAP190519_142958_976940_DEC190606_040944.rg3 It gets renamed to something like this: MFC_CAP190519_142958_976940_DEC190606_040944_gqHQEiE.rg3 -
How to make the documents downloadable from wagtail?
I have uploaded pdf's to my wagtail page but I cant work out how to get them to actually be downloadable from the web page itself. This is my code for the models.py file. What html code do I need to make these? class ArchitectPage(Page): pdf_files = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ ] # these are if adding a search to the website # content tab panels content_panels = Page.content_panels + [ MultiFieldPanel( [InlinePanel('architect_pdf', max_num=20, min_num=0, label="architect pdf")], heading="architect pdf" ), ] # what to call the panels on wagtail edit_handler = TabbedInterface([ ObjectList(content_panels, heading='Content'), ObjectList(Page.promote_panels, heading='SEO'), ObjectList(Page.settings_panels, heading='Settings', classname='settings'), # classname settings adds the cog ]) class ArchitectDownloads(Orderable): page = ParentalKey(ArchitectPage, on_delete=models.CASCADE, related_name='architect_pdf') architect_pdf = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ DocumentChooserPanel('architect_pdf'), ] -
Working on the same git with two different pc's. Two different postgresql settings in the settings.py file
I'm very new to databases and I'm trying to find out what the best practise for what I'm trying to achieve. I have the one repository which is a Django backend with a postgresql database attached. I'm working with this on my main pc but recently I've had to work on my laptop. My laptop has another postgresql database running on 5432, so I've had to change some of that info to be on port 54324. These changes I don't want pushed to the repository, but I would still like to track the settings.py file in the repository. So far I've just created a branch for each pc to maintain the separate settings, but I'm sure this is not a great way to do it. I've heard about setting up environment files, but I'm unsure about if this is the 'right way' to do it either. I'm a little confused with the best way I can do this, hopefully I'm making sense. Any help would be appreciated greatly. Thanks, Darren -
How can I generate Django static files on Windows properly?
For deployment of static files one uses usually the command python manage.py collectstatic like described in the docs. This will generate the static files into STATIC_ROOT = "/var/www/example.com/static/" (settings.py). I am developing under Windows right now. Means /var/www/example.com/static/ does not exist and I need a way to control into which directory the static files are generated. How can I get this done on Windows? -
Django Session Cookie won't work in Safari (subdomain)
In my Django Webapp i have multiple Tenants (identifies by Subdomain). One User can have Access to multiple Tenants. This are my Cookies Settings in settings.py # Cookie Settings SESSION_COOKIE_DOMAIN = ".boncompagni.test" DOMAIN_NAME = "boncompagni.test" Work's fine on Google Chrome and Firefox, but Safari doesn't set the Session Cookie. Safari: Safari Dev-Screen Chrome: Chrome Dev-Screen Have anybody an idea why this won't work in Safari? -
Testing CreateView with JsonResponse
I want to test my CreateView but since I newly started to learn to test Django codes, I don't know how to test it. I use Ajax, therefore, I return JsonResponse, and before returning the response I save the form. I have tried a couple of methods but I was not able to write a successful test. Either it throws an error or could not post the data successfully to the URL. my CreateView: class MyCreateView(generic.CreateView): template_name = 'template.html' model = my_model form_class = my_form success_url = reverse_lazy('my_url') def get_request_page(self, page): page = self.request.POST[page] page = page.split('/')[-2] if page == '': page = 'Main Page' return page def form_valid(self, form): if self.request.is_ajax(): obj = form.save(commit=False) obj.page = self.get_request_page("page") obj.save() redirect_url = self.success_url return JsonResponse({'info': 'Successfully sent', 'redirect_url': redirect_url, }) def form_invalid(self, form): super(ArrangementFormView, self).form_invalid(form) return JsonResponse({'info': form.errors}) -
django class based view pass url parameter in create post to current category
lets's say that i have three categories (tutorials, news, jobs). and i have class based views to list all posts, list posts by category and create new posts. and sure post is the same model and fields to all categories. my problem is : if user was in category list template (let's say tutorial) .. i want the user when he create new post .. it is saved directly to tutorial category .. and if user was in list template (let's say news) .. he will create new post which will be saved directly to news category. i mean create new post saved directly to current category. i believe i will use (pass url parameter to class based views) but actually i failed to do that .. and i searched tonnage of questions without got what i want. can any body help .. with sample please. models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def save(self, *args, **kwargs): if not self.slug and self.name: self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) views.py def PostListView(request, category_slug=None): category = None posts = Post.objects.all().prefetch_related().annotate(commentscountperpost=Count('comments')) categories = … -
Django disable low level caching with context manager
One of my methods in a project I'm working on looks like this: from django.core.cache import cache from app import models def _get_active_children(parent_id, timestamp): children = cache.get(f"active_seasons_{parent_id}") if children is None: children = models.Children.objects.filter(parent_id=parent_id).active( dt=timestamp ) cache.set( f"active_children_{parent_id}", children, 60 * 10, ) return children The issue is I don't want caching to occur when this method is being called via the command line (it's inside a task). So I'm wondering if there's a way to disable caching of this form? Ideally I want to use a context manager so that any cache calls inside the context are ignored (or pushed to a DummyCache/LocalMem cache which wouldn't effect my main Redis cache). I've considered pasisng skip_cache=True through the methods, but this is pretty brittle and I'm sure there's a more elegant solution. Additionally, I've tried using mock.patch but I'm not sure this works outside of test classes. -
Django view demands an item not on form
I have extended the Django user model with some extra fields models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) telephone = models.CharField(max_length=15, blank=True) date_of_birth = models.DateField(null=True, blank=True) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('telephone', 'date_of_birth') widgets = { 'date_of_birth': forms.DateInput(attrs={'type': 'date'}), } user_update.html <form action="/user-updated/{{ user.pk }}/" method="post"> {% csrf_token %} <table> <tr><td>User:</td><td>{{ user.username }}</td></tr> <tr><td>First Name:</td><td>{{ user_form.first_name }}</td></tr> <tr><td>Last Name:</td><td>{{ user_form.last_name }}</td></tr> <tr><td>Email:</td><td>{{ user_form.email }}</td></tr> <tr><td>Telephone:</td><td>{{ profile_form.telephone }}</td></tr> <tr><td>Date of birth:</td><td>{{ profile_form.date_of_birth }}</td></tr> </table> <input type="submit" value="Submit" /> </form> views.py form(request, user_pk): user = User.objects.get(pk=user_pk) if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) print(profile_form.errors) if user_form.is_valid() and profile_form.is_valid(): profile, created = Profile.objects.get_or_create(user=request.user) user_form.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) date_of_birth = profile_form.cleaned_data['date_of_birth'] user = profile_form.cleaned_data['user'] context = {'user': user,} template = loader.get_template('user_updated.html') return HttpResponse(template.render(context, request)) else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm() profile_form = ProfileForm() context = {'user': user, 'user_form': user_form, 'profile_form': profile_form } return render(request, 'user_details.html', context) On submit, the profile_form throws an error in views.py: <ul class="errorlist"><li>user<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Can someone please suggest how I might correct this? -
Can't use the python output formatting in Django db models
I am testing a very simple class in Django db : class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" However, when makemigrations, it returns syntax error on the use of return f"{self.city} ({self.code})" : Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/jello/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/jello/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/jello/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jello/.local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/jello/.local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 661, in exec_module File "<frozen importlib._bootstrap_external>", line 767, in get_code File "<frozen importlib._bootstrap_external>", line 727, in source_to_code File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/mnt/c/Users/green/desktop/project3/orders/models.py", line 11 return f"{self.city} ({self.code})" ^ SyntaxError: invalid syntax When I modify the line with : return '{} ({})'.format(self.city, self.code) or return self.city + "(" + self.code + ")" Both works well. Anyone knows why the return f"{self.city} ({self.code})" gives error? I am using …