Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Authentication credentials were not provided": how can I make all the views to require log in in DRF?
I'm trying to restrict the post view to only those who have logged in, however after I added the permission to only 'IsAuthenticated' I get this when I go to the url: { "detail": "Authentication credentials were not provided." } Of course, when I go there I have already logged in so something is not working but I'm not sure what. How can I make it so that users can see the posts only if the logged in? This is the view of the post and the log in: class UserLoginAPIView(generics.CreateAPIView): permission_classes = (permissions.AllowAny, ) serializer_class = serializers.UserLoginSerializer def post(self, request, *args, **kwargs): serializer = UserLoginSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({"status": status.HTTP_200_OK, "Token": token.key}) class PostAPIView(generics.ListCreateAPIView): """PostViewSet Post API will be used to creating new discussion, listing, and replying to a post """ queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = (IsAuthenticated,) def pre_save(self, obj): obj.created_by = self.request.user def get_queryset(self): """ """ return Post.objects.filter(reply_to__isnull=True) def get(self, request, format=None): content = { 'user': str(request.user), # `django.contrib.auth.User` instance. 'auth': str(request.auth), # None } return Response(content) The URL: urlpatterns = [ path('login/', views.UserLoginAPIView.as_view(), name='login'), path('post/', views.PostAPIView.as_view(), name='post'), ] I have these in my settings: REST_FRAMEWORK = … -
Heroku refused connection error 111 for xhtml2pdf to work in Heroku
I have a Django app, with a postgresql database and I have been using xhtml2pdf to render some pdfs. Everything works in production mode but when I deployed to Heroku, the pdf function is not working. I'm guessing it's something to do with BytesIO but I'm stumped. I'm using this code: def print_release(self, request, queryset): print(queryset) queryset=queryset.all().order_by('customer') files =[] for q in queryset.all(): customer=q.customer order=Order.objects.get(customer=customer) firstname = q.customer.first_name lastname = q.customer.last_name data = {'order':order,'firstname': firstname, 'lastname': lastname, } if order.customer.staff_participant =="Participant": pdf=admin_render_to_pdf('accounts/release_pdf_template.html', data) files.append(("Participant "+lastname + "_" +"_release" + ".pdf", pdf)) else: pdf=admin_render_to_pdf('accounts/release_pdf_template.html', data) files.append(("Staff "+lastname + "_" +"_release" + ".pdf", pdf)) full_zip_in_mewmory = generate_zip(files) response = HttpResponse(full_zip_in_mewmory, content_type='application/force-download') download_name = "Releaseforms_" + ".zip" response['Content-Disposition'] = 'attachment; filename="{}"'.format(download_name) return response def generate_zip(files): mem_zip = BytesIO() with zipfile.ZipFile(mem_zip, mode = "w", compression=zipfile.ZIP_DEFLATED) as zf: for f in files: zf.writestr(f[0], f[1]) return mem_zip.getvalue() and get these errors: Environment: Request Method: POST Request URL: https://****** Django Version: 3.1.5 Python Version: 3.9.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = … -
Formatting multiple BooleanFields as a single Select widget
The database im working with has several boolean fields where only ever one of them should be true at a time. I want to format these as a Select widget, so that I can list the choices and False will be returned for all of the boolean fields except for the selected option. I got each of them individually working as checkboxes (I commented those out), and I was able to make a select widget that is displaying correctly in the view (client_type), but I cannot accomplish the above. Here's the relevant section of my models.py: class DomCase(models.Model): plaintiff = models.BooleanField(default=False, blank=True) defendant = models.BooleanField(default=False, blank=True) class DomCaseForm(ModelForm): client_type = ChoiceField(choices=(('', '----'),('plaintiff', 'Plaintiff'),('defendant','Defendant')), widget=Select(attrs={'class': 'form-control', 'id': 'client_type'})) class Meta: model = DomCase widgets = { #'plaintiff': CheckboxInput(attrs={'class': 'custom-control-input', }), #'defendant': CheckboxInput(attrs={'class': 'custom-control-input', }), } # Dynamically Create Form Fields based on widget details fields = [] for widget in widgets: fields.append(widget) fields = tuple(fields) -
Filtering a django Prefetch based on more fields from the root object
This is similar to other questions regarding complicated prefetches but seems to be slightly different. Here are some example models: class Author(Model): pass class Book(Model): authors = ManyToManyField(Author, through='BookAuthor') class BookAuthor(Model): book = ForeignKey(Book, ...) author = ForeignKey(Author, ...) class Event(Model): book = ForeignKey(Book, ...) author = ForeignKey(Author, ...) In summary: a BookAuthor links a book to one of its authors, and an Event also concerns a book and one of its authors (the latter constraint is unimportant). One could design the relationships differently but it's too late for that now, and in my case, this in fact is part of migrating away from the current setup. Now suppose I have a BookAuthor instance and want to find any events that relate to that combination of book and author. I can follow either the book or author relations on BookAuthor and their event_set reverse relationship, but neither gives me what I want and, if I have several BookAuthors it becomes a pain. It seems that the way to get an entire queryset "annotated" onto a model instance is via prefetch_related but as far as I can tell there is no way, in the Prefetch object's queryset property, to refer to … -
Need help understand the message from upgrading Django
Can someone help me understand what I need to do in response to this error message--or whether anything needs to be done at all? This happened when I decided to upgrade Django from 3.1x to 3.2 (no need to delve into the reasons--a learner's mistakes). I followed the official instructions to test for dependency issues, $ python -Wa manage.py test, and nothing showed up. Then python -m pip install -U Django yielded the following long message. The last line declares Successfully installed Django-3.2 asgiref-3.3.4, but why the long message. python3 -m pip install -U Django WARNING: Value for scheme.headers does not match. Please report this to <https://github.com/pypa/pip/issues/9617> distutils: /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9/UNKNOWN sysconfig: /Library/Frameworks/Python.framework/Versions/3.9/include/python3.9 WARNING: Additional context: user = False home = None root = None prefix = None Requirement already satisfied: Django in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (3.1.7) Collecting Django Using cached Django-3.2-py3-none-any.whl (7.9 MB) Requirement already satisfied: sqlparse>=0.2.2 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from Django) (0.4.1) Collecting asgiref<4,>=3.3.2 Using cached asgiref-3.3.4-py3-none-any.whl (22 kB) Requirement already satisfied: pytz in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from Django) (2020.5) Installing collected packages: asgiref, Django Attempting uninstall: asgiref Found existing installation: asgiref 3.3.1 Uninstalling asgiref-3.3.1: Successfully uninstalled asgiref-3.3.1 Attempting uninstall: Django Found existing installation: Django 3.1.7 Uninstalling Django-3.1.7: Successfully uninstalled Django-3.1.7 WARNING: Value for scheme.headers … -
this model register the first item and leave the rest of the items
if user ordered multiple items, the model only register the first item. the model: class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) item = models.ForeignKey(Item, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity -
How to set up Django permissions for a custom user?
Good evening! I have the following, a table containing my custom users (our dear Fellows) which will serve to login our users (by using the custom model). ◢ The custom backends with it's custom user model for the Fellows table. from django.contrib.auth.hashers import check_password from django.contrib.auth.models import User from .models import CustomUser class FellowBackend: def authenticate(self, request, **kwargs): '''Authenticates the user (custom model).''' # Parameters user_id = kwargs['username'] password = kwargs['password'] # Tentatives. try: user = CustomUser.objects.get(id = user_id) # If the password matches. if check_password(password, user.password): return user else: # Triggers default login failed. return None except CustomUser.DoesNotExist: return None def get_user(self, user_id): '''TODO: Test if this override is required.''' try: return CustomUser.objects.get(pk = user_id) except CustomUser.DoesNotExist: return None ◢ The custom user model. class Faction(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=64) # Field name made lowercase. class Meta: managed = False db_table = 'Faction' class CustomUser(AbstractBaseUser): id = models.PositiveBigIntegerField(db_column='ID', primary_key=True) # ID. display_name = models.CharField(db_column='Name', max_length=64, db_collation='utf8mb4_general_ci') password = models.CharField(db_column='User_Password', max_length=256, blank=True, null=True) gold = models.IntegerField(db_column='Gold') # Credits. faction = models.ForeignKey('Faction', models.RESTRICT, db_column='Faction', default=1) # ID Faction. last_login = models.DateTimeField(db_column='Last_Login', blank=True, null=True) # Last Login. # Admin Panel Abstract Fields active … -
Pass 2 values to validator
In Django I try in forms create validator with compare password and confirm_password and I don't want do it in clean method. I want my do cystom validator and put him to widget confirm_password field. I don't know ho pass two values password and confirm_password to my Validator. def validate_test(): cleaned_data = super(UserSignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") print(f'password:{password}\nconfirm_password: {confirm_password}') if password != confirm_password: raise ValidationError( _('%(password)s and %(confirm_password)s does not match - test'), params={'password': password, 'confirm_password': confirm_password}, ) class UserSignUpForm(forms.ModelForm): password = forms.CharField( label="Password", validators=[MinLengthValidator(8, message="Zbyt krótkie hasło, min. 8 znaków")], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) confirm_password = forms.CharField( label="Confirm password", validators=[MinLengthValidator(8, message="Zbyt krótkie hasło, min. 8 znaków"), validate_test()], widget=forms.PasswordInput(attrs={'style':'max-width: 20em; margin:auto', 'autocomplete':'off'})) class Meta: model = User fields = ("username", 'first_name', 'last_name', "password") help_texts = {"username": None} widgets = { 'username': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'first_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), 'last_name': forms.TextInput(attrs={'style':'max-width: 20em; margin:auto'}), } -
Django guardian with million of records
I want to build ERP system (You are know that ERP Systems have 200-300 tables and more in database) so I want some advice about django guardian with huge number of records. I look for django guardian documentations I found that all objects permission for every table recorde store in single table with Indexes. Could I force problems If I use it to manage records permissions? -
Django unable to locate modules
I set up a Django project using pipenv and have the virtual environment running using pipenv shell. I have been trying to add a few modules to my project including django-acl. However, whenever I $ pipenv install django-acl and then attempt to migrate I get the following message. ModuleNotFoundError: No module named 'djangoacl' At first I thought that django-acl just didn't work but it's done this same thing with every module that I've tried to add since. How do I fix this so that I can add django-acl and other modules to my project? -
Django query from multi PostgreSQL Schema
I want to know the following about multi PostgreSQL schema in Django: Is the query from non public schema required to establish connection or not. How to query from other Schema using Django "Using()" method. Is eligible in Django to make one database with multi schema. I was searching about that topic a lot of programmers make duplicated for single database in Django settings and change only option for each one. -
Module missing when deploying on Heroku
I'm trying to deploy a Django app with React frontend on Heroku but it keeps getting stuck at the error message "ModuleNotFoundError: No module named 'corsheaders'". I have corsheaders in my requirements.txt as django-cors-headers==3.7.0 and I have it in installed apps in settings.py as INSTALLED_APPS = ['corsheaders', ...] I also have it installed on the venv I'm using for this project. While running my app in heroku local everything is chill. What could be the problem here? -
DAL ( Django Autocomplete Light ) - How to open the select on page load
Trying to open the select2 on page load using document.ready doesn't work because "autocomplete_light.js initialize function" is tied to same event and at document.ready, the componente isn't initialized yet. How can I open the select2 after it has been initialized by autocomplete light? -
Performing operations when data is added from admin site in django web application
I have the following models class Order_Ingredient(models.Model): day = models.DateField(auto_now_add=True,blank=True) ingredient = models.ForeignKey(Inventory, on_delete = models.CASCADE) amount = models.IntegerField(help_text = "in grams") class Inventory(models.Model): ingredient_name = models.CharField(max_length=100,unique=True) quantity = models.IntegerField(help_text = "in grams") min_quantity = models.IntegerField(help_text = "in grams") cost_price = models.IntegerField(help_text = "cost per gram") I have registered both the models to the admin site. Now I want to implement the fuctionality that whenever I insert data from the admin site in the Order_ingredient model, I can perform some additional operations like updating the quantity of ingredient referenced by foreign key. One way to do this was to override __init__ in model. But everywhere I searched, it was advised to avoid this method. Is there a workaround to this problem? -
Hidden input field didnot show the correct value which was access from views.py in Django
Before I asked this question, I have searched online and found similar solutions. However, it does not work for my case. I would like to pass the hidden input value in views.py but it didn't show the right value. when I hardcoded the value it passes the correct one but when I passed the value which was access from one of the functions of views.py it didn't show the correct value in the console. here is my html template where i access the value in hidden input tag <label > <h1>All grade:</h1></label> <form action="show_topics" method="post" > {% csrf_token %} {% for cat in show_grades %} <div class="col-sm-4"> <div class="card"> <div class="card-body"> <label><h5 class="card-title" style="color: hotpink">{{cat.grade}}</h5></label> <!-- <input type="hidden" name="gradeid" value="{{to.grade}}"> --> <button class="btn btn-outline-success" type="submit" name="classname" value="{{cat.grade}}" ><h4>View Class</h4></button> <input type="hidden" name="ids" id="idss" value="{{cat.id}}"> <!--<a href="#" class="btn btn-primary">Go somewhere</a>--> </div> </div> </div> {% endfor %} </form> view.py (from that function retrieved the value which is used in hidden input field) def add_grade(request): if request.method == "POST": teacher_id=request.POST.get('submit') #tech_id=int(teacher_id) print("teacher id retrieved") print(teacher_id) print("===") #print(tech_id) grade = request.POST.get('addgrade') # classes=request.POST.get('class') grade = Add_Grade(grade=grade, username_id=teacher_id) grade.save() show_grades = Add_Grade.objects.raw("Select * from Add_Grade where username_id = %s",teacher_id) context={ 'show_grades':show_grades, } #allgrade=Add_Grade.objects.all() return render(request,'teacher_dashboard.html',context) … -
'ArticleSerializer' object has no attribute 'get'
The article serializer: class ArticleSerializer(serializers.ModelSerializer): class Meta: model=Article fields='__all__' settings: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } model: class Article(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) email=models.EmailField() date=models.DateTimeField(auto_now=True) def __str__(self): return self.title view function: def article_list(request): if request.method== 'GET': article =Article.objects.all() serializer = ArticleSerializer(article,many=True) return JsonResponse(serializer.data,safe=False) if request.method == 'POST': data = JSONParser.parse(request) serializer = ArticleSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status=400) i just created a simple serializer but whenever i try to get the response it says that the ArticleSerializer i created has no attribute 'get'. Error -
Pass extra_context directly to django.contrib.auth.urls?
I created this url pattern and I hoped the extra context would be passed on to the views. But the views, which use the correct templates, seem to ignore the extra context. path('accounts/', include('django.contrib.auth.urls'), {'extra_context': {'home_title': settings.HOME_TITLE, 'domain': settings.HOSTNAME}}), I wonder if is is possible at all to pass extra context to the django.contrib.auth.urls or whether I have to create my own views for login/signup/logout in order to use the extra context? -
How I can get log of all objects accessed in Django in a simple way?
I need request log in database with additional information about objects, that used during request processing. Now I have a middleware and function, that I call every time, when I load object from database. class LogMiddleware(MiddlewareMixin): def process_response(self, request, response): project_id = request.accessed_objects.get('project_id', None) Log.objects.create( user_id=request.user.id, request_url=url[0:256], request_method=request.method, project_id=project_id, ) def custom_get_object(request, queryset, **filter_kwargs): obj = get_object_or_404(queryset, **filter_kwargs) project = get_project(obj) # all objects connected to some project via foreign key of through other object request.accessed_objects['project_id'] = project.id return obj I want to make the same things without calling custom_get_object in every place, switch to some ORM hook on loading objects from db, or something like that. -
Django can't find the URL pattern
I'm new to Django and I'm making wiki website based on markdown. I am having one problem. Django can't match the path in html to urls.py. It happens when I try to open wiki entries. It gives me the following error. I have already passed the parameter to 'page', I honestly have no idea what to do. Using the URLconf defined in wiki.urls, Django tried these URL patterns, in this order: admin/ [name='index'] wiki/<str:page> [name='page'] search [name='search'] create [name='create'] addentry [name='add_entry'] nomatches [name='nomatches'] results [name='results'] edit/<str:page> [name='edit'] random [name='random'] The current path, { url 'page' entry }, didn't match any of these. Please, tell me how can I fix this. index. html: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <a href="{ url 'page' entry }"><li>{{ entry }}</li></a> {% endfor %} </ul> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:page>", views.viewpage, name="page"), path("search", views.search, name="search"), path("create", views.create, name="create"), path("addentry", views.add_entry, name="add_entry"), path("nomatches", views.search, name="nomatches"), path("results", views.search, name="results"), path("edit/<str:page>", views.edit, name="edit"), path("random", views.random, name="random") ] part of views.py: def index(request): return render(request, "encyclopedia/index.html", … -
update DateTimeFIeld Django from post request
I want to update Datetime field on Django, but not with now() datetime but with the datetime given by post method. views.py serializer = PlantationSerializers(plantation, data=datum) theDate = datetime.strptime(datum['updated_at'], '%a %b %d %H:%M:%S GMT+02:00 %Y') if plantation.updated_at < theDate: serializer.save() WIth print I can saw that when theDate is more recent, I go in, that change every fields but not the field updated_at ... models.py class Plantation(models.Model): # Some other fields updated_at = models.DateTimeField(auto_now_add=True) I need that auto_now, but I want to edit it when I update it from post method. Sorry for my bad english :/ -
Undo changes in VS Code?
Well, this is a bit embarrassing. I was able to push/commit a functioning version of my web app files to git from VS Code. But then I made some very drastic changes and need to revert back to everything I had since my last commit. Is there a way to do that? Pretty new to this, my apologies. -
how can i query another schema using Django tenancy Schemas
I'm working on a CRM project using Django / Multi-Tenancy Schema, I would like to know how a user can access another schema ( how I can query another schema ) I googled my query but I couldn't find any answer -
Optimize collection of paginated REST API data
I need to collect several thousand records from a 3rd party REST API, but each call is limited to 99 records at most. Additionally, the API doesn't return any information about the total number of records or page count, it only returns a boolean "more_records". Having to make several hundred API calls to collect data for a page is obviously very slow, and it's causing one of my routes to timeout. My first thought for optimization is to split out the API calls into asynchronous tasks, but because there's no stopping information besides "more_records" I'm not sure how to handle calling those tasks. I'm using Django for this and I already have Celery set up for other purposes. The route that times out collects and manipulates this and other data and returns it as JSON to populate a gross report. One idea I had was to break down this JSON route so that my gross report's Javascript makes many smaller API calls and manipulates the data itself, but that only solves the timeout since no one call takes too long. The only ways I see to optimize the response time is to reduce the number of API calls or handle … -
Unable to resolve `Bad file descriptor` from django logging
I'm trying to add Papertrail logging to a Django app, which is build alongside an older Falcon app. Due to some of the v1 to v2 transition, this is how it's setup (a lot of code removed for simplicity): import logging import logging.config logger = logging.getLogger('api') ... logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'logstash': { 'level': 'INFO', 'class': 'logstash.TCPLogstashHandler', 'host': LOGSTASH_HOST, 'port': LOGSTASH_PORT, 'version': 1, 'message_type': 'django', 'fqdn': True, }, { 'level': 'INFO', 'class': 'logging.handlers.SysLogHandler', 'address': ('logs.papertrailapp.com', int(CREDENTIALS_PAPERTRAIL_ADDRESS)) } } 'loggers': { 'api': { 'handlers': ['console','SysLog'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, "gunicorn.error": { 'handlers': ['console','SysLog'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, "gunicorn.access": { 'handlers': ['console','SysLog'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True, }, 'access_logs': { 'handlers': ['logstash'], 'level': 'INFO', 'propagate': False, }, }, }) The gunicorn stuff comes from https://github.com/benoitc/gunicorn/issues/2016 In a test file, I have logger.warning('test asdf'), which I see get spit out to the console, however, it also throws: Traceback (most recent call last): File "/usr/local/lib/python3.7/logging/handlers.py", line 940, in emit self.socket.sendto(msg, self.address) OSError: [Errno 9] Bad file descriptor Thing is, the access logs stuff works; we're seeing that stuff go to logstash, but I cannot seem to figure out this socket issue for … -
AJAX not rendering on django template
So I am trying to render some text dynamically on a webpage using AJAX. I created an empty div and attempted to fill it with some data but it renders nothing. Firstly, my question is how do I pass extra data to the AJAX call? Below is the HTML <div> {% for user in searched_users %} <p>{{ user.user.username }}</p> </div> <div id = "links"> <a id = "follow" href="{% url 'add' name=user.user.username %}">Follow</a> <a id="unfollow" href="{% url 'unfollow' name=user.user.username %}">Unfollow</a> <a href = "{% url 'match' name=user.user.username %}">Perform Match?</a> </div> <div id = "display"> </div> {% endfor %} <script> element = document.getElementById("follow"); target_element = document.getElementById("display"); data = user.user.username element.onclick = () =>{ $.ajax({ url : "/follow/", data : data, success: display } )}; function display (data) { if (data) { console.log(data); // Add the http response to element target_element.innerHTML = data; }} </script> {% endblock %} it has a couple of href-s used for following, unfollowing a user. When a user clicks on the follow href, I want to display the HTTPresponse of this view. def follow(request, name): sender = User.objects.get(username = request.session["username"]).userprofile display = User.objects.get(username=name) receiver = User.objects.get(username= name).userprofile if receiver not in sender.get_friends() and sender != receiver: relationship …