Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/PyCharm cannot open pickle file
I am using Django 3.1.2 Python 3.8 and PyCharm Professional on Ubuntu. I am at: djangoProject/djangoApp/views.py something.pickle is in the same directory I am trying to read it with "open('something.pickle', 'rb')" Response - no such file or directory. I am trying the same approach through the terminal - it reads it. Is it something with Django or PyCharm Professional?> Thanks, guys! Cheers -
Own method in CreateView
I want to use my own method, which will return JsonResponse, but this method isn't called in this View by default. So maybe i need to rewrite another method or? views.py: class CreatePostJS(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('post_message', 'post_image') model = models.Post select_related = ('user',) template_name = 'posts/post_list.html' template_name = 'posts/post_form.html' response_data = {} response_data['text'] = model.post_message response_data['posted'] = model.posted_at response_data['user'] = model.user def create_post(request): if request.method == 'POST': return JsonResponse(serializers.serialize('json', response_data), safe = False) def form_valid(self, form): self.object = form.save(commit = False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
Django template for many to many relationship with additional information
in my model i have services which has a many to many relation with articles plus the extra value amount where i store how many of the article instances are attributed to the services. My question regards the template: has anyone seen some sort of form that can show such a relationship or might even dedicated to such a relationship? I'm also open to suggestions on how to represent such a relationship? Currently i just used a MultiSelect Field widget where I can choose which articles to pass to the service and set the default amount to 1. I would have to go to the admin panel, and edit the amounts there which is not that cool. -
Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/']
I am a novice in Dejango and I want to have a shopping cart, but whatever I do, this error will not be fixed. and give me following eror. please help me. Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P[\w-]+)/'] cart model.py class Cart (models.Model): products=models.ManyToManyField("seabookapp.Book",null=True,blank=True) total=models.IntegerField( default=0) timestamp=models.DateTimeField(auto_now_add=True,auto_now=False) updated=models.DateTimeField(auto_now_add=False,auto_now=True) active=models.BooleanField(default=True) def __unicode__(self): return "Cart id : %s"%(self.id) book model.py class Book (models.Model): BookID= models.AutoField(primary_key=True) Titel=models.CharField(max_length=150 ) Author=models.ForeignKey('Author',on_delete=models.CASCADE) Publisher=models.ForeignKey('Publisher',on_delete=models.CASCADE) slug=models.SlugField(unique=True) GenerName=models.ForeignKey('category',on_delete=models.CASCADE) Price= models.IntegerField(null='true',blank='true') Discount= models.IntegerField(null='true',blank='true') AfterDiscount= models.IntegerField(null='true',blank='true') veiw.py def show_Book(request,BookID): template_name = 'showBook.html' showBook=get_object_or_404(Book,BookID=BookID) commentss = showBook.comments.filter(active=True) comments = showBook.comments.filter(active=True).order_by('-Created_on')[0:4] new_comment = None name = None book =None is_favorite=False if showBook.favorit.filter(id=request.user.id).exists(): is_favorite=True # Comment posted if request.method == 'POST': comment_form = BookCommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = comments # Save the comment to the database comment_form.instance.name = name comment_form.instance.book = request.book new_comment.save() else: comment_form = BookCommentForm() return render (request , 'showBook.html', { 'showBook':showBook , 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'commentss':commentss, 'book':book, 'is_favorite':is_favorite, }) def view (request): cart=Cart.objects.all()[0] products=Book.objects.all() context={"cart":cart,'products':products} template="view.html" return render (request,template, context) def update_cart(request,slug): cart=Cart.objects.all()[0] try: product=Book.objects.get(slug=slug) except Book.DoesNotExist: pass except: pass if … -
Password: "This field may not be blank." Error with React, ant design and django
Hi I just started learning react and decided to use ant design (version 3), so I created an API (Django Rest Framework) and I got it up an running, my login and sign up page was working fine, so I decided to upgrade ANT Design to Version 4, I had to read the documentation because somethings changed and managed to get it looking go but now when I fill the login form to submit, I get "Request failed with status code 400"... then checked the network and i see a response: {"password":["This field may not be blank."]} I tried to login from the API and it works perfectly, but keeps showing Request failed with 404 when i try to use the form. this is the Form.Js class LoginForm extends React.Component { state = { username: "", password: "" }; handleChange = e => { this.setState({ [e.target.name]: e.target.value }); }; onFinish = values => { console.log(values); // values.preventDefault(); const { username, password } = this.state; this.props.login(username, password); }; render() { const { error, loading, token } = this.props; const { username, password } = this.state; if (token) { return <Redirect to="/" />; } return ( <Layout> <Layout> <Layout style={{ padding: '0 … -
How to receive get parameter in viewset in django restframe work?
For the part of developing an API using restframe work and DJango, I need to receive few parameters through get method in 'list' function of my Viewset. In client side they are sending data as query prams, I somehow managed to get the data using 'request.query_params.get()' but received data is text format instead of bool, I had to convert this to boolean . see the code how I did this if 'status' in (request.query_params): """receiving input argument is string need to convert that to boolean for further processing""" input_status=(request.query_params.get('status', None)=='true') is there any better way to getting data without losing datatype. is it possible to receive 'bool' or 'int' values directly in get parameter? My model and view set classes are given below class ModuleType(models.Model): """ This module type class used to represent each module of the application. It is inherited from django content type which holds the complete model informations """ #this active field is true this module will be active on our user controller content_type = models.OneToOneField( ContentType, on_delete=models.CASCADE, related_name='status', null=True ) active=models.BooleanField(default=False) class Meta: db_table = 'module_types' My Viewset class ContentTypeViewSet(viewsets.ModelViewSet): """ This api deals all operations related with module management You will have `list`, `create`, `retrieve`, … -
Can i install specific sub package (logistic regression) from python package such as sklearn
I am developing a Django app, where I need TfidfVectorizer and LogisticRegression only. But I have to install the whole scikit-learn for this purpose. This take space and I want to make the app as light as possible. So is there a way to install TfidfVectorizer and LogisticRegression only) -
Save method conflict when using Django Admin feature
My model uses custom save method to add my own "primary key": class Z(models.Model): author = models.ForeignKey(K, on_delete=models.PROTECT) my_id = models.CharField(max_length=60, unique=True) ... def save(self, *args, **kwargs): counter = Z.objects.filter(author=self.author).count() + 1 self.my_id = str(counter) + "/" + self.author.name super(Z, self).save(*args, **kwargs) But when I'm trying to edit anything in Django Admin panel it still uses my save method- which causes a lot of problems (when I'm editing multiple items it gives it the same ID, etc). Is there any way that I can force Admin panel editing to not use my save method? -
Run one off commands via SSH in Elastic Beanstalk and Django
I'm trying to solve this problem for a while now and can't seem to solve it. There are various scenarios in which I would want to be able to run a custom command on Elastic beanstalk. I want to use this command after the server started (.ebextensions does not work here). E. g. python manage.py send_pending_emails_via_cronjob The problem here is that I'm not able to run any commands without the environment variables set. My app needs e. g. DJANGO_SECRET_KEY, RDS_DB_NAME... Out of the box, these variables are only available when the server starts up. They are not available when I enter the EC2 instance via eb ssh - they are also not present in the virtual python environment on the instance. I tried: finding the file that contains the variables at /opt/elasticbeanstalk/env to source it. But read access to the file is restricted to the root user (I haven't yet figured out how to access the server as root) - however, this feels very complicated and like an unintuitive thing to do. I suspect there to be a more elegant solution. Did someone solve this already? -
DRF - Paginated response - append list of all ids
I have a "next object" feature on my website but I use pagination. I would like add "ids" field that contains ids of all objects filtered and sorteded into the paginated response. Everything that I tried returns only a list of current page ids. class StandardResultsSetPagination(PageNumberPagination): page_size = 20 page_size_query_param = 'page_size' max_page_size = 20 def get_paginated_response(self, data, list_of_ids): return Response(OrderedDict([ ('count', self.page.paginator.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data), ('ids', list_of_ids) ])) class RealestateViewSet(ModelViewSet): ... pagination_class = StandardResultsSetPagination def get_paginated_response(self, data, list_of_ids): """ Return a paginated style `Response` object for the given output data. """ assert self.paginator is not None return self.paginator.get_paginated_response(data, list_of_ids) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data, list(queryset.values_list('id', flat=True))) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) This returns a list of 20 ids instead of all filtered objects ids. Do you know how to do that? -
SessionWizardView + Jquery Inline Formset - ValidationErrors Don't Display
I have a SessionWizardView where in one of the stages the user enters a number of name/value pairs. In the "clean()" method for the formset the sum of the values entered are checked against a value entered on a previous form. If not equal, a ValidationError is thrown. If I attach this error to a field instead using self.forms[0].add_error, then it displays as it should, but if I simply raise ValidationError("message") then "message" isn't displayed. The submit button, doesn't take the user to the next form, so the validation is there, but there must be something missing in my template. All other Q/A's I've seen on this general topic of ValidationErrors not displaying suggest adding a loop to display any {{ form.non_field_errors }} doesn't work for me. Here is the content block of the template currently: {% block content %} <p>Step {{ wizard.steps.step1 }}</p> <div class="col-md-4"> <form method="post"> {% csrf_token %} <table class="table"> {{ wizard.management_form|crispy }} {% if wizard.form.forms %} {{ wizard.form.management_form|crispy }} {% for form in wizard.form.forms %} {{ form.non_field_errors }} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="formset_row"> {% for field … -
Django Operation Error after saved objects
This keep popping up on web after save an object, not sure what happens: screenshot OperationalError at /admin/product/product/add/ no such table: product_product Request Method: POST Request URL: http://127.0.0.1:8000/admin/product/product/add/ Django Version: 3.1.2 Exception Type: OperationalError Exception Value: no such table: product_product My code: admin.py from django.contrib import admin # Register your models here. from .models import product admin.site.register(product) models.py from django.db import models # Create your models here. class product(models.Model): title = models.CharField(max_length=222) description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=333, decimal_places=2) summary = models.TextField(default = 'this is cool!') feature = models.BooleanField() apps.py from django.apps import AppConfig class ProductConfig(AppConfig): name = 'product' -
Syntax error using tags in django template with {{ }}
Using Pycharm Pro 2020.2 Python 3.8 Django 3.1.2 views.py from django.shortcuts import render # Create your views here. def truncate(request): name = 'Very long name' return render(request, "truncate.html", {'name': name} ) urls.py re_path(r'^test/$', truncate, name='truncate'), truncate.html {{ name }}<br /> {{ name|truncatewords:2 }}<br /> {{ name }}|truncatewords:2<br /> Output Very long name Very long … Very long name|truncatewords:2 Problem shows using Pycharm Code Inspect on the .html page. I get these 2 errors: Expected }} and {{ or {% expected an error pointing at the line with: {{ name|truncatewords:2 }} which gives the right output and no error at the line with: {{ name }}|truncatewords:2 which gives the wrong output. Thanks for any help. Gilles -
Psycopg2 error: undefined symbol: PQencryptPasswordConn
I try to start new django project on raspberry pi 3b+ but I can not establish the database connection. I using Python 3.7.2, Django==3.1.2, psycopg2-binary==2.8.6, Postgresql 9.6. I read and try different articles but..... My settings.py: DATABASES = 'default': #'ENGINE': 'django.db.backends.sqlite3', #'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'monastery', 'USER': 'SU', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', Error: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: /home/pi/django/monastery/env/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-arm-linux-gnueabihf.so: undefined symbol: PQencryptPasswordConn -
Nginx internal location ignores django completely and allows free access instead
I want to have a private media folder on my django website, accessible only to logged in users, so I got to know that I should handle authentication part on the django side, and file serving on the nginx side. However following internal location config examples I find it impossible to make it work. Nginx ignores django completely (only for the internal location case). Even if I don't have the url allowed in my urls.py and I have it listed as internal location in nginx, it will still be freely accessible to everybody. I am posting my nginx configuration in hope that someone can find a mistake in it. My expectation is that everything in /internal/ folder will not be accessible to anonymous users and it will only be accessible by the django application through X-Accel-Redirect header. Right now if I go to /internal/test.png in an incognito window it will show me the picture. I am not posting my django code for now, since it is ignored anyway by nginx, so it must be the nginx config problem. server { server_name XXX.XX.XX.XXX example.com www.example.com; location = /favicon.ico { access_log off; log_not_found off; alias /home/user/myproject/static/favicon4.ico; } location /static/ { root /home/user/myproject; … -
Use external APIs on Django or frontend
I want to use an API that response me the COVID19 cases on a certain country and I don't want to save them, I just want to show them. Should I make the request to the API on the backend (Django) and pass the response on a context variable or directly make the request on the frontend? I know this is actually the same in terms of request/response, but which one is a better practice? -
Django initial_forms.is_valid() returns false
My goal is to edit/update existing data. I am able to display existing data and add new data but not edit data. My model are Recipe and Ingredient. I am using modelformset_factory to add ingredients to recipe. Here is the forms.py: class RecipeModelForm(forms.ModelForm): class Meta: model = Recipe fields = ('name', ) labels = { 'name': 'Recipe Name' } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Recipe Name here' } ) } IngredientFormset = modelformset_factory( Ingredient, fields=('name', 'amount', 'unit'), labels={ 'name': 'Ingredient Name', 'amount': 'Amount', 'unit': 'Unit' }, extra=1, widgets={ 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Ingredient Name here' } ), 'amount': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Amount here' } ), 'unit': forms.Select( attrs={ 'class': 'form-control', 'placeholder': 'Enter Unit here' } ) }, can_delete=True ) views.py: @login_required def update_recipe(request, pk): template_name = 'recipe/create_with_ingredients.html' # template_name = 'recipe/update.html' recipe = Recipe.objects.get(id=pk, author=request.user) ingredients = Ingredient.objects.filter(recipe=recipe) if request.method == 'GET': recipeform = RecipeModelForm(instance=recipe) formset = IngredientFormset(queryset=ingredients) elif request.method == 'POST': recipeform = RecipeModelForm(request.POST, instance=recipe) formset = IngredientFormset(request.POST, queryset=ingredients) if recipeform.is_valid(): # and formset.is_valid(): recipe = recipeform.save(commit=False) recipe.author = request.user recipe.save() for form in formset.initial_forms: print(form.is_valid()) if form.is_valid(): data = form.cleaned_data for form in formset: if form.is_valid(): data = … -
CheckConstraint constantly throwing a FieldError
So I've been struggling with trying to implement a Following-system in my project. Something similar to how the Twitter following system works. I've looked around and come across a few ideas. Right now my models.py in it's entirety looks like this: models.py from django.contrib.auth.models import AbstractUser from django.db.models.fields import DateTimeField from django.utils import timezone from django.db import models # pylint: disable=no-member class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friend = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) class Post(models.Model): creator = models.ForeignKey("User", on_delete=models.CASCADE, related_name="post_creator") content = models.TextField(max_length=250, blank=True) created = models.DateTimeField(auto_now_add=True) likes = models.PositiveIntegerField(default=0) def serialize(self): return { "id": self.id, "creator": self.creator.username, "content": self.content, "created": self.created.strftime("%d %b %Y, %H:%M"), "likes": self.likes } The problem is right now, as is, a user can follow themselves which I do not want. So of course I tried to use CheckConstraint by adding a class Meta to my Profile model so it looks like this: class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE, primary_key=True) friend = models.ManyToManyField("User", related_name='following', blank=True, symmetrical=False) class Meta: constraints = [ models.CheckConstraint(check=~Q(user=F('friend')), name="user_cannot_be_following_themselves"), ] This keeps producing this error django.core.exceptions.FieldError: Cannot resolve keyword 'friend' into field. Choices are: id, user, user_id everytime I try to migrate the changes (after makemigrations). Even when … -
Writing a view to fetch user data and add it to the database
I make a project which generates a random book when the user press a button. The view that does that is: def random_book(request): cartile=Books.objects.all() random_item=random.choice(cartile) return render(request, 'carti/book.html', context={"random_item": random_item}) On the page were you are redirected to see the generated random book I want to add a button that says "add to read later". I know how to make a manyotmany relationship between profile model and books model, but I have no idea how to write a view that gets the generated random book, adds it to the profile view_later field in the database, delete it with another button, what html tag and what should I write inside for "add to read later" and the delete button. Some help would be appreciated! -
Django | AWS: How to get username?
I've deployed my django project on aws ec2-instance and I want to know the users system login username. My Django project doesn't have signin system. I know in python you can get system login username from getpass.getuser() But as I said that my project is hosted on ec-instance, hence when I use getpass.getuser() I am getting username as ec2-user Is it possible to get user's system username if project is hosted on ec2-instance. -
Django None Type object is not callable
I want to create an own usermodel, so I can login with email instead of using the username. For this I used this tutorial: https://testdriven.io/blog/django-custom-user-model/ I used the AbstractBaseUser. I also changed the model a bit, so I have some other fields. The problem is, that when I send the request I get an error: TypeError at / 'NoneType' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: TypeError Exception Value: 'NoneType' object is not callable Exception Location: ...\managers.py, line 18, in create_user Python Executable: ...\venv\Scripts\python.exe Python Version: 3.8.5 Traceback Switch to copy-and-paste view ...\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … :arrow_forward: Local vars ...\venv\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response response = wrapped_callback(request, *callback_args, callback_kwargs) … :arrow_forward: Local vars ...\views.py, line 7, in index user_creator.create_user(request.POST['email'], request.POST['username'], request.POST['displayname'], … :arrow_forward: Local vars ...\managers.py, line 18, in create_user user = self.model(email=email, user_name=user_name, display_name=display_name, extra_fields) I think the problem is, that it doesn't know what the self.model in the manager.py at line 11 should be. Here is my code: my views.py from django.shortcuts import render from .managers import CustomUserManager def index(request): if request.method == 'POST': user_creator = CustomUserManager() user_creator.create_user(request.POST['email'], request.POST['username'], request.POST['displayname'], request.POST['password1'], request.POST['password2']) return render(request=request, template_name='index.html') … -
why does my logger not inherit handlers from root logger
I have followed advice from django docs and other SO questions about how to configure logs in a django project. settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s.%(msecs)03d [%(levelname)s:%(name)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', 'level': 'INFO', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, } portfolio/models.py: logger = logging.getLogger(__name__) def testfunc(): print(logger) print(logger.handlers) when i run testfunc i get the following output: >>> testfunc() <Logger portfolio.models (INFO)> [] however if i add a logger explicitly to my config like so: 'root': { 'handlers': ['console'], 'level': 'INFO', }, 'loggers': { 'portfolio.models': { 'handlers': ['console'], 'level': 'INFO', }, } then the handler is picked up by the logger: >>> testfunc() <Logger portfolio.models (INFO)> [<StreamHandler <stderr> (INFO)>] I have also tried creating a 'catch-all' logger like based on another SO answer: 'loggers': { '': { 'handlers': ['console'], 'level': 'INFO', }, } but this didn't work. Any ideas why i can't get my logger to inherit from the root logger? -
How To Pass Value of Select Box as Foreign Key (Django)
Hi I am working on a Django web app - I have a select box which holds all objects from a particular model. The select box is created in the template, it is not a part of the form directly. When I submit, I am able to access the value selected by the user, but when I try to use the value as part of a queryset it does not return the expected values. models.py class TaskGroup(models.Model): name = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return self.name class TaskGroupDetail(models.Model): taskGroup = models.ForeignKey(TaskGroup, null=True, blank=True) taskType = models.ForeignKey(TaskType, null=False, blank=False) views.py def CreateShipmentView(request): if request.method == 'POST': shipment_form = CreateShipmentForm(request.POST) if shipment_form.is_valid(): new_shipment = shipment_form.save() group = request.POST.get('groups') #get the task group selected print(group) #this returns the expected value ..... #if a task group was added, create the tasks groupDetails = TaskGroupDetail.objects.get(taskGroup = group) #this returns a blank queryset print(groupDetails) #this returns a blank queryset return redirect('ShipmentListView') ... else: shipmentForm = CreateShipmentForm() groups = TaskGroup.objects.all() context = { 'shipmentForm': shipmentForm, 'groups': groups, } return render(request, 'create-shipment.html', context) create-shipment.html <form class="well contact-form" method="POST" action="{% url 'CreateShipmentView' %}"> {% csrf_token %} <div class="modal-content"> <div class="modal-header"> {% for error in form.Reference_Number.errors %} <P class='error'>{{ error … -
Django client tests requests wrong path
I am building django REST app with mixins: ModelViewSet(mixins.RetrieveModelMixin, mixins.CreateModelMixin) queryset = Model.objects.all() (...) and retrieve() is visible in localhost:8000/model/<uuid> Then I add a function for counting all Model instances: @action(detail=False, methods=["GET"], url_path="count") def get_model_count(self, request): queryset = self.get_queryset() data = {"count": queryset.count()} return Response(status=status.HTTP_200_OK, data=data) Then when I try to test it: def test_model_count(self): list_size = 10 for i in range(list_size): response = self.create_model() self.assertEqual(response.status_code, 200, response.content) response = self.client.get(reverse("model-get-model-count")) self.assertEqual(response.status_code, 200, response.content) I get this error: AssertionError: 400 != 200 : b"Invalid parameter robot_id value: 'all' is not a 'uuid'" Interesting part is that when I use web or curl, everything works fine, I can get count correctly, I can get model details, I can create new model. I tried changing the order, so count is implemented first, before retrieve but the error still exists. Hope I provided enough of information, thanks in advance -
Cannot resolve keyword 'user_following' into field. Choices are: id, user, user_id
I have just added a new model 'Profile' to my models.py. I do not have any views.py or forms.py for this model. I am hoping that Profile will act as a kind of extension to my AbstractUser model that is why I have used a OneToOneField for Profile.user. Initially I created the model like this: class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) user_following = models.ManyToManyField("User", symmetrical=False, related_name="following", blank=True) class Meta: constraints = [ models.CheckConstraint(check=~Q(user=F('user_following')), name="user_cannot_be_following_themselves"), ] @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except Profile.DoesNotExist: Profile.objects.create(user=instance) I did the usual manage.py makemigrations network and that was fine, it recognised my changes. I then went to migrate and got a traceback error ending with django.core.exceptions.FieldError: Cannot resolve keyword 'user_following' into field. Choices are: id, user, user_id. I assumed it had a problem with the name of the field 'user_following' so I changed it to 'following'. I then did makemigrations again and got this error: ERRORS: network.Profile.following: (fields.E302) Reverse accessor for 'Profile.following' clashes with field name 'Profile.following'. HINT: Rename field 'Profile.following', or add/change a related_name argument to the definition for field 'Profile.following'. network.Profile.following: (fields.E303) Reverse query name for 'Profile.following' clashes with field name 'Profile.following'. HINT: Rename field 'Profile.following', or add/change a …