Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possitble to execute a python(django) function immediately on vs code?
I want to execute a python function in vs code directly when I set a breakpoint when debugging. Just like Immediate window on Visual Studio -
Django REST Framework Multiple OR'd Custom Permissions' Message Not Shown
I'm trying to write a RetrieveUpdateDestroyAPIView where the permission classes are set as follows: permission_classes = (IsUserCat | CanDogsRetrieveObject,) permissions.py: class IsUserCat(IsAuthenticated): def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and request.user.species == SPECIES_CAT def has_permission(self, request, view): return super().has_permission(request, view) and request.user.species == SPECIES_CAT class IsUserDog(IsAuthenticated): def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and request.user.species == SPECIES_DOG def has_permission(self, request, view): return super().has_permission(request, view) and request.user.species == SPECIES_DOG class CanDogsRetrieveObject(IsUserDog): message = "Some custom message." def has_permission(self, request, view): return super().has_permission(request, view) def has_object_permission(self, request, view, obj): return super().has_object_permission(request, view, obj) and obj.expiry_date >= timezone.now().date() So basically, the first permission class checks if the user is a cat, if so, the user can retrieve the object; if not, the second permission class checks if the user is a dog and if the object in question is expired. If it's expired, a custom error message must be displayed, but it doesn't. If I don't OR them, and instead just use CanDogsRetrieveObject then the issue gets resolved. Why is this the case? -
How to filter and count query set in django template?
I have this model: class Application(Model): is_paid = BooleanField(default=False) and this view: def my_view(request): template_name = 'my_template.html' context = {} applications = Application.objects.all() context.update({'applications': applications,}) return render(request, template_name, context) and have this template: <body> All: {{ applications.count }} <!-- Paid: I want to show the count of paid applications in here. --> <!-- UnPaid: I want to show the count of unpaid applications in here. --> </body> What I want to do is that filter the applications based on the is_paid field and count them. I do not want to do it in the view. I want to do it in the template to avoid making view complicated and big. How should I do it? -
Override e-mail header in form django-crispy-forms for django-allauth
I can not find a way to redefine the header and placeholder for the mail field in the form of a django-allauth created using django-crispy-forms. -
Model with manyToMany InvalidCursorName in admin
I have a problem with Django and Postres. Python 3.5 Django 2.2.7 psycopg2 2.8.4 postgres 9.5.19 Models: class Model1(models.Model): model1_name = models.CharField(max_length=20) class Model2(models.Model): model2_name = models.CharField(max_length=20) model_keys = models.ManyToManyField(Model1, blank=True) Postgress DB is empty: my_base=> \d No relations found. I do migrations... python3 manage.py makemigrations project/migrations/0004_model1_model2.py - Create model Model1 - Create model Model2 python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, engine_st, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying myproject.0001_initial... OK Applying myproject.0002_auto_20191129_1339... OK Applying myproject0003_auto_20191129_1340... OK Applying myproject.0004_model1_model2... OK Applying sessions.0001_initial... OK ... , but the admin panel has error (Page for create new object): Exception Type: InvalidCursorName Exception Value: cursor "_django_curs_140479737550592_1" does not exist Does anyone know a solution to this problem? There is no such problem on SQLite. -
My Django app is running after I deployed it
The link is Mejoshjones.com it was the passenger app will show what’s wrong with the app. I don’t know where to start for as debugging This is what I think is wrong from tinymce import HTMLField ImportError: cannot import name 'HTMLField' from 'tinymce' (/home/powevtec/virtualenv/mejoshjones.com/test/3.7/lib/python3.7/site-packages/tinymce/init.py) -
Language for allowing users to write simple mathematical functions with no state change?
I am writing a small simulation where users can trade assets and I want them to be able to trade options too. Options are basically mathematical functions f(Asset_price : [float]) -> float that should not need to make any state change. It would be optimal if the users could supply these functions themselves. The app is written in python/django but of course I cannot just let them upload python code and execute that. Is there some simple way to still let the users handcode these functions? My idea would be some very simplistic language that I can easily call from python that only allows the users to do some basic mathematical operations in the function f and not allowing any state change to the environment. Is there something like that out there? I am also open for different suggestions on how to achieve my goal. -
Django2.2.7 + Mysqlclient installation error + Ubuntu 16.04
I have successfully installed python3.6.* and Django2.2.*, MySQL-server However in the virtualenv I am getting error while installing the MySQL client. x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,4,4,'final',0) -D__version__=1.4.4 -I/usr/include/mysql -I/usr/include/python3.6m -I/var/www/venv/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o -lmysqlclient -lpthread -lz -lm -lrt -lssl -lcrypto -ldl -o build/lib.linux-x86_64-3.6/MySQLdb/_mysql.cpython-36m-x86_64-linux-gnu.so /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /var/www/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-fezj4ikj/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-fezj4ikj/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-kodyrb_q/install-record.txt --single-version-externally-managed --compile --install-headers /var/www/venv/include/site/python3.6/mysqlclient Check the logs for full command output. Does anyone have help guide to resolve this problem? -
Importing json files in models with field definition using Django admin
I am trying to import json data files by parsing into Django data models. I have defined a table with the "Entidad" where the json file is uploaded with the data. Through the actions of Django in admin I intend to upload the file, for example "Articles", launch the action, load the json and parse or match each field by importing the data into the models. class Entidad(TimeStampedModel): nombre = models.CharField(max_length=100) archivo = models.FileField(upload_to="importaciones/entidades/", help_text="Fichero formato *.json") Another "Relacion" table where the "origen" field (in the json) "destino" field of the model is indicated: class Relacion(TimeStampedModel): entidad = models.ForeignKey("importaciones.Entidad", related_name="relaciones", on_delete=models.CASCADE) origen = models.CharField(max_length=50, help_text="Nombre del campo de la columna del fichero.") destino = models.CharField(max_length=50, help_text="Nombre del campo de la base de datos.") modelo = models.CharField(max_length=50, help_text="Nombre tabla de datos.") The admin TabularInline: class RelacionInline(admin.TabularInline): model = Relacion class EntidadAdmin(admin.ModelAdmin): inlines = [ RelacionInline, ] actions = ['importar_datos',] def importar_datos(self, request, queryset): for entidad in queryset: with open(entidad.archivo.path) as f: data = json.load(f) importa(data, entidad.relaciones) self.message_user(request, "Se ha importado xxx") importar_datos.short_description = "Importar datos seleccionado(s)" admin.site.register(Entidad, EntidadAdmin) Example of the json file. It should be noted that there are related tables: { "root": { "Products": [ { "supplierCode": "34523", "date": … -
AttributeError: 'QuerySet' object has no attribute 'tags'
My views . this view contains error in news.tags class NewsDetailView(DetailView): model = News template_name='news/detail_news.html' context_object_name= 'news' def get_context_data(self, **kwargs): news=News.objects.all() tags=news.tags.all() context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(news=self.object) context['my_likes'] = Like.objects.filter(news=self.object) context['popular_news'] = news.order_by("-count")[:6] context['tags'] = tags # context["tags"] = TaggableManager().bulk_related_objects(self.object) self.object.count = self.object.count + 1 self.object.save() return context this is my models . i have created this to make a news . and i want to add tags in my news without TaggableManager() class Tag(models.Model): name = models.CharField(max_length=30) class News(models.Model): CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance")) title=models.CharField(max_length=250) story= models.TextField() count= models.IntegerField(default=0) tags = models.ManyToManyField(Tag) video_url = models.URLField(max_length=270, null=True) #makemigrations garna baki xa category= models.CharField(choices=CATEGORY, max_length=2) slug=models.SlugField(max_length=270,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) cover_image=models.ImageField(upload_to="uploads") author= models.ForeignKey(User, on_delete=models.SET_NULL,null=True) video_image = models.ImageField(null=True) def get_absolute_url(self): return reverse("detail_news",kwargs={"category":self.get_category_display(), "pk":self.pk, "slug":self.slug}) -
Doesn't appear the selected option in <select>
I'm trying to create dynamically some check-boxes in my django project, what I'm doing is: <form action="#" method="post" target="#"> {% for node in Last_val_nodes %} <input type="checkbox" name="{{node.0}}" value="#" class="nodos_check_ruta"> {{node.0}}<br> {% endfor %} </form> Where Last_val_nodes is a list of lists that comes from my views.py and I'm interested in the first value of this "sublists". Up to this point all is good, but now what I want to do is know what checkbox is selected. That's why I'm writing in name {{node.0}}, because my js do the next, if( $('.nodos_check_ruta').is(':checked') ) { var name = $(this).attr("name"); alert(name); } But the alert is undefined. Who can I know the selected check-boxes? If there more than one selected, how can I know it? I want to save all the selected in a list. Thank you. -
Django template tag doesn't see scope variable
I am trying to dynamically include Django template based on AngularJS scope variable. Variable contains "image", "audio" or "video" values in string format. And I am using 'with' tag and 'add' filter to get template path and name e.g. "record/audio.html": {% with template_name=record.filetype|add:".html" %} {% include "record/"|add:template_name %} {% endwith %} Unfortunately, I end up with error message: "TemplateDoesNotExist /record/.html". It looks like the variable doesn't exist even though when I try to print it with [[ record.filetype ]] it works just fine. I am guessing the scope is not loaded yet when the 'with/include' tags are executed. I load the scope with 'ng-init' in 'main' html tag which I am not sure is the best practice but I don't know how else I should do it. <main ng-controller="ProjectCtrl" ng-init="getRecord('{{ project }}')" ng-cloak> {% with template_name=record.filetype|add:".html" %} {% include "record/"|add:template_name %} {% endwith %} <!-- some other code --> -
How to populate a select list in a Django Template dynamically using Javascript?
I've recently been learning Django and HTML but I'm completely new to JS and I'm having a go at creating a database display page with a filter menu at the side. For this page I have the following code: Model.py: class Part(models.Model): PartID = models.AutoField(primary_key=True, unique=True) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True) Comment = models.CharField(max_length=255, blank=True) Subtype = models.ForeignKey('Subtype', on_delete=models.CASCADE, null=True) Location = models.CharField(max_length=255, blank=True) ConnectedTo= models.ManyToManyField('self', null=True) BatchNo = models.CharField(max_length=32, blank=False, null=True) SerialNo = models.CharField(max_length=32,blank=True) Manufacturer = models.CharField(max_length=32, blank=False, null=True) Length = models.FloatField(blank=True, null=True) InspectionPeriod = models.IntegerField(blank=True, null=True) LastInspected = models.DateField(blank=True, null=True) InspectionDue = models.CharField(max_length=255, blank=True) View.py: @login_required(login_url='/accounts/login/') def sites(request, site): siteselected = site warnings = 0 expired = 0 good = 0 PartsAtSite = Part.objects.filter(SiteID = siteselected) TypesList = Type.objects.values_list('TypeName', flat=True).distinct() InspectionList = Part.objects.values_list('InspectionPeriod', flat=True).distinct() LengthList = Part.objects.values_list('Length', flat=True).distinct() LocationList = Part.objects.values_list('Location', flat=True).distinct() ManufacturerList = Part.objects.values_list('Manufacturer', flat=True).distinct() for part in PartsAtSite: if part.LastInspected == None: part.InspectionDue = "Yes" expired = expired + 1 else: Deadline = part.LastInspected + timedelta(days=part.InspectionPeriod) if datetime.now().date() > Deadline: part.InspectionDue = "Yes" expired = expired + 1 elif datetime.now().date() > (Deadline - timedelta(days=30)): part.InspectionDue = "<30 Days" warnings = warnings + 1 else: part.InspectionDue = "No" good = good + 1 part.save() context = { … -
Cannot access to Django admin
If I do create a user with superuser status in django admin and I cannot log in to django admin. It says Please enter the correct phone and password for a staff account. Note that both fields may be case-sensitive. here is my code class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone, password, **extra_fields): user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(phone, password, **extra_fields) def create_superuser(self, phone, password, **extra_fields): if password is None: raise TypeError( 'Superuser must have a password' ) user = self._create_user(phone=phone, password=password, **extra_fields) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=50) phone = models.CharField(max_length=13, unique=True) USERNAME_FIELD = 'phone' verified = models.BooleanField(default=False) objects = UserManager() REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def __str__(self): return self.phone If I create user in terminal I can easily log in to django admin. If I do in django admin I cannot. Can anyone tell please if something is wrong or missing in my code? Thank you in advance! BTW it returns True of superuser status in terminal with created user in django admin but cannot have access. -
Is it possible to send multi-layered file inside json array in post request?
I have been trying to send multiple files along json objects in post request. { name:"Most recent", file:text.png, tracks:[{ name:"amber", file:amber.png, desc:"", }] } I want to save data of first file in one model and tracks file in different model. -
is it possible to render a editable table use django tables? if so how?
this is my models.py class bio_broken_eq(models.Model): bio_eq_id = models.IntegerField(primary_key = True) student = models.ForeignKey("chem_lab.student", verbose_name=("student"), on_delete=models.CASCADE) bio_eq_name = models.CharField(max_length=50) bio_eq_number = models.IntegerField() bio_eq_cost = models.IntegerField() class bio_eq(models.Model): bio_eq_id = models.IntegerField(primary_key=True) bio_eq_name = models.CharField(max_length=50) bio_eq_amount = models.PositiveIntegerField this needs to be rendered an editable table. how should i go about doing this? -
Getting error : Could not resolve URL for hyperlinked relationship using view name "user-detail" in django python
i am new here in django python, so pardon me for my silly mistake I am working on the Rest API, when i do run API http://127.0.0.1:8000/api/v1/users/ I am getting this error : Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured thelookup_fieldattribute on this field., below i have placed my whole file, can anyone please look my code and help me to resolve this issue ? thanks in advance views.py from django.shortcuts import render # Create your views here. import rest_framework.generics from rest_framework import generics from .models import Songs from .serializers import SongsSerializer from .serializers import UserSerializer from django.contrib.auth.models import User class ListSongsView(generics.ListAPIView): """ Provides a get method handler. """ queryset = Songs.objects.all() serializer_class = SongsSerializer class UserViewSet(generics.ListAPIView): #viewsets.ModelViewSet queryset = User.objects.all() serializer_class = UserSerializer serializers.py from rest_framework import serializers from .models import Songs from .models import UserProfile from django.contrib.auth.models import User class SongsSerializer(serializers.ModelSerializer): class Meta: model = Songs fields = ("title", "artist") class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', … -
Django models count children and grand children
In Django models I need help selecting count of children and count of grand children. My models: Parent: Child: parent = models.Foreignkey(Parent) GrandChild: child = models.Foreignkey(Child) I did Parent.objects.annotate(num_child =Count('parent'), num_grandchild=('child__grandchild')) With this, I get num_child is exactly same value as num_grandchild Can you please help -
Django ImageField - AttributeError 'PublicMediaStorage' object has no attribute 'generate_filename'
I'm getting the titled error, when trying to submit a Django form with an imageField. Following are the relevant code snippets: Settings DEFAULT_FILE_STORAGE = 'newt.storage_backends.PublicMediaStorage' Model from django_upload_path.upload_path import auto_cleaned_path class FoodLogging(models.Model): food_image = models.ImageField('Food Image', upload_to=auto_cleaned_path, null=True, blank=True, default="NA") Form class FoodLoggingForm(BetterModelForm): class Meta: model = FoodLogging fieldsets = ( ... ('Food Logging Report', { 'fields': ('food_image',), 'legend': "Food Logging Report", 'template_name': "fieldset_template.html" }), ... View class FoodLoggingCreate(PermissionRequiredMixin, CreateView): model = FoodLogging form_class = FoodLoggingForm success_url = reverse_lazy('foodloggings') permission_required = ('catalog.add_foodlogging') def form_valid(self, form): form.instance.user = self.request.user return super(FoodLoggingCreate, self).form_valid(form) def get_form_kwargs(self): kwargs = super(FoodLoggingCreate, self).get_form_kwargs() kwargs.update({'request': self.request}) return kwargs HTML <input type="file" name="food_image" accept="image/*" id="id_food_image"> Please support Thanks ahead, Shahar -
Is it possible to call a class instance by using a variable which has a valid instance name?
I am a newbie in Object Oriented Programming. The problem might sound silly. I have a class named Dogs(). And this class has some instances age, height, weight which are stored in the database. class Dogs(): age=IntegerField() height=FloatField() weight=FloatField() Now if I call the class in a variable and then call the instances with the name inside the class it works fine. dog=Dogs.objects.all()[0] dog.age #works fine dog.height #works fine dog.weight #works fine Now I have another variable which contains one of the instance's name say (temp='age'). I want to call the instance (which is in the variable temp) of the class Dogs using the variable. dog.temp #Does not work Is it possible to get the instance by calling with the variable? If yes then how should I do it? If no then what should be my approach? -
Format a FloatField column in the admin and display the formatted column value
Is there a way to format a FloatField (ideally directly in the model) or even create a new column and display the value with the formatted values (which I am trying to do): # Model: class MyModel(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. # ... price = models.FloatField(db_column='Price', blank=True, null=True) # Field name made lowercase. # Admin class MyModelAdmin(admin.ModelAdmin): list_display = ( 'id', # ... 'new_price' ) def new_price(self, obj): formatted_num = '{:,}'.format(int(obj.price)) print(formatted_num) return formatted_num # Currently, the formatted_num has a value such as: -1,012,010,000 but for some reason, the column 'new_price' in my admin model view is empty -
ImproperlyConfigured at /news/create/
class CreateNewsView(LoginRequiredMixin,CreateView,): login_url='/accounts/login' news_form_class=NewsCreateForm template_name='news/create_news.html' success_url=reverse_lazy('home') def form_valid(self,form): tag_list = [] news = form.save(commit=False) title= form.cleaned_data['title'] tags= form.cleaned_data['tags'] tag_list = [Tag.objects.get_or_create(name=tag)[0] for tag in tags.split()] # news_tag=form.cleaned_data['news_tag'] news.author = self.request.user news.slug = slugify(title) for tag in tag_list: news.tags.add(tag) news.save() return super(CreateNewsView,self).form_valid(form) def form_invalid(self,form): print (form.errors) return super(CreateNewsView,self).form_invalid(form) my models: its news website with tags in it to create and i have faced error while adding tag . I havent used TaggableManager() for tags rather i have created my own models class Tag(models.Model): name = models.CharField(max_length=30) class News(models.Model): CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance")) title=models.CharField(max_length=250) story= models.TextField() count= models.IntegerField(default=0) tags = models.ManyToManyField(Tag) video_url = models.URLField(max_length=270, null=True) #makemigrations garna baki xa category= models.CharField(choices=CATEGORY, max_length=2) slug=models.SlugField(max_length=270,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) cover_image=models.ImageField(upload_to="uploads") author= models.ForeignKey(User, on_delete=models.SET_NULL,null=True) video_image = models.ImageField(null=True) def get_absolute_url(self): return reverse("detail_news",kwargs={"category":self.get_category_display(), "pk":self.pk, "slug":self.slug}) -
getting invalid syntax error in python 3.8
guys, I am trying to make my first Django application but I keep seeing invalid syntax error at the second url. urlpatterns = [ url(r'^$',views.index, name='index') url(r'^details/(?P<id>\d+)/$',views.details, name ='details') ]; -
How to create an API endpoint in django to stop a Get/Post http request?
I am trying to allow the user to stop a get/post http request whenever he wants to during the process. -
Synonymous many to many model relationship in Django
I'm trying to achieve what you could call a "synonymous" relationship on a self referencing many to many field in Django. Take this model for example (in reality I don't use real words, but category tags instead): class Word(models.Model): name = models.CharField(max_length=30, unique=True) synonymous = models.ManyToManyField('self', blank=True, related_name='synonymous') def __str__(self): return self.name What I want to achieve, is when I have 3 objects, and add any combination of them to the synonymous field, I want all of them to be connected. # Create synonymous words bunny = Word.objects.create(name='bunny') hare = Word.objects.create(name='hare') rabbit = Word.objects.create(name='rabbit') # Set synonymous words to rabbit rabbit.synonymous.set([bunny, hare]) Now when I get the synonymous objects of rabbit, it has what I want: (Pdb) rabbit.synonymous.all() <QuerySet [<Word: bunny>, <Word: hare>]> But when I take the synonymous objects of bunny and hare, they only return rabbit. (Pdb) bunny.synonymous.all() <QuerySet [<Word: rabbit>]> (Pdb) hare.synonymous.all() <QuerySet [<Word: rabbit>]> What I'd like to achieve, is all the synonymous objects, to be "symmetrical". Now, the m2m field is already symmetrical, but it only stops at one object, not all given synonymous objects. So, the ideal result would be this: # Create synonymous words bunny = Word.objects.create(name='bunny') hare = Word.objects.create(name='hare') rabbit = Word.objects.create(name='rabbit') …