Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How lazy_model_operation in app register wait to run in Django?
I have read source code Django, and I get a stuck when reading method lazy_model_operation in module registry belong to apps package. def lazy_model_operation(self, function, *model_keys): """ Take a function and a number of ("app_label", "modelname") tuples, and when all the corresponding models have been imported and registered, call the function with the model classes as its arguments. The function passed to this method must accept exactly n models as arguments, where n=len(model_keys). """ # Base case: no arguments, just execute the function. if not model_keys: function() # Recursive case: take the head of model_keys, wait for the # corresponding model class to be imported and registered, then apply # that argument to the supplied function. Pass the resulting partial # to lazy_model_operation() along with the remaining model args and # repeat until all models are loaded and all arguments are applied. else: next_model, *more_models = model_keys # This will be executed after the class corresponding to next_model # has been imported and registered. The `func` attribute provides # duck-type compatibility with partials. def apply_next_model(model): next_function = partial(apply_next_model.func, model) self.lazy_model_operation(next_function, *more_models) apply_next_model.func = function # If the model has already been imported and registered, partially # apply it to the … -
raise ConnectionError(self._error_message(e)) kombu.exceptions.OperationalError: Error 111 connecting to localhost:6379. Connection refused
minimal django/celery/redis is running locally, but when deployed to heroku gives me the following error, when I run on python: raise ConnectionError(self._error_message(e)) kombu.exceptions.OperationalError: Error 111 connecting to localhost:6379. Connection refused. This is my tasks.py file in my application directory: from celery import Celery import os app = Celery('tasks', broker='redis://localhost:6379/0') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) @app.task def add(x, y): return x + y Requirements.txt: django gunicorn django-heroku celery redis celery-with-redis django-celery kombu I have set worker dyno to 1. Funny things is i could have sworn it was working before, now it doesnt work for some reason. -
AttributeError: Cutome User model object has no attribute 'password'
I have a Profile model customizing the User model by having a one to one relationship to the User model, the code for the model is the following class Profile(models.Model): user = models.OneToOneField(User, parent_link=True, on_delete=models.CASCADE) bio = models.TextField() slug = models.SlugField(unique=True, blank=True) avatar_thumbnail = ProcessedImageField(upload_to='images/', default='/images/default.png', processors=[ResizeToFill(300, 300)], format='JPEG', options={'quality': 60}) location = models.TextField() tags = models.ManyToManyField(Tag) contact_information = models.TextField() verified = models.BooleanField(default=False) counter = models.IntegerField(default=0) def __str__(self): return self.user.username def save(self, *args, **kwargs): print('self.username') print(self.user.username) self.slug = self.user.username super(Profile, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('infrastructure:edit-user-profile', kwargs={'slug': self.slug}) whenever I enter the shell with python manage.py shell and get the Profile queryset Profile.objects.all() I get the error AttributeError: 'Profile' object has no attribute 'password' and whenever I enter the admin panel and click on the Profiles section I get the same error saying the same thing what's wrong ? my admin.py code from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User # Register your models here. from . import models class SubjectTagAdmin(admin.TabularInline): model = models.SubjectTag.tags.through class TagAdmin(admin.ModelAdmin): inlines=[SubjectTagAdmin, ] admin.site.register(models.Tag, TagAdmin) admin.site.register(models.SubjectTag) admin.site.register(models.Profile) admin.site.register(models.Organization) -
Is there a default file upload size limit in django?
I am using django FileField and ImageField in my models but I am wondering is there any default upload size limit for files.I researched about it and I found that we can limit the file upload size to some size by configuring MAX_UPLOAD_SIZE in the project's settings.py but what If i didn't handle any validation for the Image/file field?Then will the user be able to upload image of any unlimited size or is there any default size limit for this ? -
How can i customize login api from djoser package?
I just want to give a user details in a login response, currently, I'm getting 'token' and 'refresh' in http://127.0.0.1:8000/auth/jwt/create/ JWT login API response. I want to return with login user details here is the response snapshot of jwt/create/, JWT Response Image -
django: getting error in django registration, in _wrapped_view() missing 1 required positional argument: 'request'
I want to use django's registration form, for that i installed django-registration-redux.i have changed my settings.py accordingly. im new to django so by reading this error message i can not resolved this. plz help settings.py """ import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'myregi.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myregi.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('accounts', include('registration.backends.default.urls')), ] blog.urls.py from django.conf.urls import url from .views import index from django.urls import path urlpatterns= [ url(r'', index, name="index"), ] views.py from django.shortcuts import render from .models import Detail from django.utils.decorators import method_decorator from django.contrib.auth.decorators … -
DRF: custom update method not being executed in ModelSerializer class
I am writing a REST API using Django Rest Framework. I'm encoutering a wierd problem here. I have an app called user. Models.py: @python_2_unicode_compatible class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) profile_picture = models.ForeignKey(File, on_delete=models.DO_NOTHING, default=None, null=True, blank=True) email = models.EmailField('Email address', unique=True) name = models.CharField('Name', default='', max_length=255) phone_no = models.CharField('Phone Number', max_length=255, unique=True) company_name = models.CharField('Company Name', default='', max_length=255) verification_token = models.CharField('Verification Token', default='', max_length=255) address = models.CharField('Address', default='', max_length=255) address_coordinates = models.CharField('Address Coordinates', default='', max_length=255) country = models.CharField('Country', default='', max_length=255) pincode = models.CharField('Pincode', default='', max_length=255) pan_number = models.CharField('Pan Number', default='', max_length=255, blank=True) gst_number = models.CharField('GST Number', default='', max_length=255, blank=True) is_advertisor = models.BooleanField(default=False) is_signage_owner = models.BooleanField(default=False) phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now_add=True) from_time = models.TimeField(blank=True, default='00:00') to_time = models.TimeField(blank=True, default='00:00') category = models.CharField('Category', default='', max_length=255, blank=True) reset_token = models.CharField(max_length=255, default='') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email Views.py: class UserViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = User.objects.all() permission_classes = (AllowAny,) filter_backends = [DjangoFilterBackend] filterset_fields = ['id', 'email', 'phone_no'] def get_serializer_class(self): if self.action == 'create': return CreateUserSerializer elif self.action == 'update': return UpdateUserSerializer else: return UserSerializer Serializers.py: class CreateUserSerializer(serializers.ModelSerializer): def create(self, validated_data): token = account_activation_token.make_token(validated_data['email']) validated_data['verification_token'] = token user = User.objects.create_user(**validated_data) subject = 'Account … -
How to generate a magic number and populate it to the database upon user registration?
I am in search of a way to assign a random generated number-letter combination to a user upon registering on my page. So if a user registers on my site, there shall be a random generated number-letter combination (let's call it magic number) assigned to this user and populated to the PostgreSQL users table. Is there a common approach to do so? Would I have to define such function within the existing class or is there a different workflow? This is my model (inherited from Djangos AbstractUser model): from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass first_name = models.CharField(max_length=500, blank=False) last_name = models.CharField(max_length=30, blank=False) def __str__(self): return self.username -
Return posts and projects with the same category (in 2 different table) to be handled in one view function
I want to return all blog posts and projects with the same categories and display it in one page. I have 2 Django apps with 2 different models. What these two models has in common is a Category class, I understand that this will create 2 different tables in the db, 1 for blog category and 1 for project category. These are my models: Blog models.py class Category(models.Model): category_name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='category_name', always_update=True, max_length=500, unique=True) class Meta: verbose_name_plural = 'categories' # to make sure a human readable string is returned and not Object def __str__(self): return self.category_name class Post(models.Model): title = models.CharField(max_length=500, unique=True) slug = AutoSlugField(populate_from='title', always_update=True, max_length=500, unique=True) summary = models.CharField(max_length=500) body = MarkdownxField() image = models.FileField() date_posted = models.DateTimeField(default=timezone.now) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField(Category, related_name='posts') status = models.CharField(max_length=10, choices=STATUS, default='draft') author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-created_on'] def __str__(self): return self.title Project models.py class Category(models.Model): category_name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='category_name', always_update=True, max_length=500, unique=True) class Meta: verbose_name_plural = 'categories' # to make sure a human readable string is returned and not Object def __str__(self): return self.category_name class Project(models.Model): project_title = models.CharField(max_length=500, unique=True) slug = AutoSlugField(populate_from='project_title', always_update=True, max_length=500, unique=True) summary = … -
Data not getting replicated in my django master slave database architecture
I have been working on setting up multiple databases for a django project. I have one master database and four slave. I want to replicate data saved on master(which is my write database) to all my slaves, from where i read my data. But my data is not replicating in my slaves after I save it is getting written in master which is correct but if it does not update on slaves well then I will be reading empty data always. I fixed this by overriding save method, But I don't It is correct or not. Also please go through my settings and routing code below and suggest the better way if any to do replicate data into readonly slaves. and what to do if master goes down due to some reason. Overriding save class MultiDbModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): for dbname in settings.DATABASES: super(MultiDbModel, self).save(using=dbname) Below are my settings and database router. Settings DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'USER': '---', 'NAME': 'main_db', 'HOST': 'localhost', 'PORT': '', 'PASSWORD': '---' }, 'slave_1': { 'ENGINE': 'sql_server.pyodbc', 'USER': '---', 'NAME': 'slave_1', 'HOST': 'localhost', 'PORT': '', 'PASSWORD': '---' }, 'slave_2': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'slave_2', 'USER': '---', … -
Cannot connect to redis://localhost:6379/0: Error 111 connecting to localhost:6379. Connection refused
I've deployed a minimal django/celery/redis project to heroku, and I'm trying to test it in the python shell: heroku run python >>> import tasks >>> tasks.add.delay(1, 2) The problem is tasks.add.delay(1,2) doesn't produce any output, it just hangs there whereas in local it gave an Async message. Also when i try to see the task running in application logs with "heroku logs -t -p worker" it gives me this error: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 111 connecting to localhost:6379. Connection refused.. -
I deployed the django website "rpa-berater.de". On localhost it works fine but on linux server with apache2 it is very slow
Does somebody have hints to optimize the Speed of the Website "rpa-berater.de". many thanks -
How can we Display and store a binary search tree in Django
I have written the program for Binary Search Tree but does not know how can i save it in the Django Database. How can i store it in the models: from __future__ import print_function class Node: # Constructor to initialize data # If data is not given by user,its taken as None def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # __str__ returns string equivalent of Object def __str__(self): return "Node[Data = %s]" % (self.data,) class BinarySearchTree: def __init__(self): self.root = None While inserting values in a binary search tree, we first check whether the value is greater than, lesser than or equal to the root of the tree. We initialize current node as the root. If the value is greater than the current node value, then we know that its right location will be in the right subtree. So we make the current element as the right node. If the value is lesser than the current node value, then we know that its right location will be in the left subtree. So we make the current element as the left node. If the value is equal to the current node value, then we … -
Issue with Jquery Datepicker in Django app
I am new to django and trying to build my first booking app. I have working forms for reservation but having trouble in implementing the query form to retrieve the booking results based on date. I am using Jquery date picker and using POST method to fetch the booking info (following is the code). I am not able to pass date from jquery date picker to views, when I print request.POST I only get None response. I have been looking over for solution but couldn’t get through. Kindly suggest the workaround. Thanks in advance. HTML CODE: <head> <meta charset="utf-8" /> <title>Form</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <script> $(document).ready(function() { $('#datepicker').datepicker(); }); </script> </head> <body> <form action="" method="post">{% csrf_token %} <!--{{ form.date }} --> <p>Date: <input type="text" id="datepicker"></p> <!-- The rest of my form --> <input type="submit" value="submit" /> </form> {% for rom in qdate%} {{rom.room}} {{rom.Purpose}} {{rom.start_time}} {{rom.end_time}} </br> {%endfor%} {% else %} Forms: My forms.py code to show Jquery datepicker widget and pass the date input from functools import partial DateInput = partial(forms.DateInput, {'class': 'datepicker'}) # import django_filters class DateFilter(forms.Form): date_input = forms.DateField(input_formats=['%m/%d/%Y',], required=False, widget=forms.DateInput(format = '%m/%d/%Y')) Views: My view.py code to dynamically query and show the … -
I have a problem with python Django 'Login' has no attribute 'filter'
I made a website with python Django. My models are two which called 'Login' and 'Ch'. And my website has 'signup' and 'home' page. The 'signup' page is literally signup page. User can register his/her ID and password. Then these information save in 'id' and 'pw' in the 'Login' model. Now, Typing his/her ID and password, user can login through 'home' page. This is my plan. However, the login process consistently happen problem with the sentence 'Login' has no attribute 'filter'. My partial code is log = Login.objects.all() try: ch = log.filter(id = request.POST["login_id"], pw = ghv(request.POST["login_pw"])) #ghv is user definition function for get hash value of password if (ch): id = request.POST["login_id"] return render(request,'pdg/home2.html') else: return render(request, "pdg/home_e.html") except ObjectDoesNotExist: return render(request, "pdg/home_e.html") Signup process has no problem. I think that after signup process complete, Being added the user data in 'Login' model is cause the problem. Because restarting the runserver is effective for solving this error. However I want to find a solution for this error without restarting the runserver. Please help me.. And THANK YOU. -
Method or something to run a complex query in a model
I would display some fields from a remote table according a common field (emails) between my models. I resume: My Django project displays a main table Prospect, related to another table Email (ForeignKey). Stored in my default Django DB (Postgres). Then I can display in another app a remote table from a third emailing tool, stored in a MySQL database, thanks to Django databases router system. All this coexists very well in my Django admin. Now I would display in my Prospect admin forms some fields from my remote table, in read only of course. In SQL/PHP, simplifying, I would do something like that: SELECT myfield FROM MyRemoteTable WHERE email = {EmailValue} But where and how can I do that with Django? I think to a special method in my Email model, but... not easy! THX -
How to retrieve data from database with autocomplete (Django)
I need to get data from database and put it on input field but I can't do it. This is my code. template.html <script type="text/javascript"> $(function () { $("#tags").autocomplete({ source: "/autocomplete/", minLength: 2, }); }); </script> <div class="ui-widget"> <input id="tags"> </div> urls.py path('autocomplete', views.autocomplete, name='autocomplete'), views.py def autocomplete(self, request, *args, **kwargs): data = request.GET product = data.get("term") if product: products = Product.objects.filter(product_name__icontains=product) else: products = Product.objects.all() results = [] for pd in products: pd_json = {} pd_json['id'] = pd.id pd_json['label'] = pd.product_name pd_json['value'] = pd.product_name results.append(pd_json) data = json.dumps(results) mimetype = 'application/json' return HttpResponse(data, mimetype) models.py class Product(models.Model): product_name = models.CharField(max_length=255) def __str__(self): return self.product_name Or maybe because I didn't import something? (such as something about 'json') -
Django modules to prevent scraping
Could you please recommend existing django applications(modules) intended to prevent scraping(crawling) of website? I have found this: https://github.com/litchfield/django-sentinel (but it seems too old) and https://djangopackages.org/grids/g/anti-spam/ (it's more about antispam) I am seeking for application that is able to analyze user behavior and block web-scrapers. -
Why does django Unittest throw an assertion error when comparing two instances of numpy.float64?
I'm writing some unit tests, one of which checks that the data provided in a dataframe is of the correct type (float). When I run the test assertIsInstance(type(foo), np.float64) the test fails with the following error message: AssertionError <class numpy.float64> is not an instance of <class numpy.float64> I would have expected this to pass. test_dataframe_functions.py import numpy as np from django.test import TestCase import pandas as pd from myapp import dataframe_functions class DataframeFunctionsTest(TestCase): dataframe_to_test = dataframe_functions.create_dataframe #passes def test_dataframe_is_definitely_a_dataframe(self): self.assertIsInstance(self.dataframe_to_test, pd.DataFrame) #passes def test_dataframe_has_the_right_columns(self): column_headers = list(self.dataframe_to_test.columns) self.assertEquals(column_headers, ['header1', 'header2', 'header3']) #fails with AssertionError <class numpy.float64> is not an instance of <class numpy.float64> def test_dataframe_header1_is_correct_format(self): data_instance = self.dataframe_to_test['header1'].iloc[1] self.assertIsInstance(type(data_instance), np.float64) I've checked that type(data_instance) does equal "class numpy.float64" with the following line of code: print(type(dataframe_to_test['header1'].iloc[1])) -
Python doesn't recognise Django app folder
I am new to Django and was following the tutorial here (https://simpleisbetterthancomplex.com/series/2017/09/04/a-complete-beginners-guide-to-django-part-1.html#hello-world) to get my first application running. I could not reference my application so I decided to name everything exactly as is in the tutorial in another Python project. I am unable to import view from boards no matter what I do (change it to projectname.appname and a number of different variations that I found on here). I have tried this tutorial on another computer I do not have access to at the moment and can confirm that it works usually. Is this an issue with PyCharm/my Python environment? Project Structure Error I am receiving -
from celery import Celery ModuleNotFoundError: No module named 'celery'
I've managed to get Django/celery/redis running on my local. I've then pushed this to heroku and am trying to run it there. However when i try to run my tasks.py file in python, it gives me the error: from celery import Celery ModuleNotFoundError: No module named 'celery' I've tried installing celery and redis on heroku using the "heroku run" command. But it does not seem to recognise this. Here is my tasks.py file: from celery import Celery app = Celery('tasks', broker='redis://localhost:6379/0') @app.task def add(x, y): return x + y -
How to display values that are less than a particular number in Django
I have created a model named Product containing these fields ('prod_name', 'company', 'quantity', 'price', 'units', 'prod_type') I want to display those products in the webpage that have less than 2 units remaining I tried using Model.Objects.filter(units__lte=2) but I am not getting the desired output Here is my views.py file: from django.shortcuts import render, redirect, get_object_or_404 from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import * from .forms import * def get_stock(request): items=Product.objects.filter(units__lte=2) context={ 'items':items } return render(request, 'UpdateStock.html', context) here is my urls file: from django.conf.urls import url from django.urls import path from .views import * urlpatterns=[ url(r'^get_stock$', get_stock, name='get_stock'), ] here is my HTML file for the same {% extends 'base.html' %} {% block body %} <br> <h3>Update Stocks</h3> <br> <table class="table table-hover"> <thead> <tr> <th>Sr. No.</th> <th>Product Name</th> <th>Company</th> <th>Quantity</th> <th>Price</th> <th>Units</th> <th>Product Type</th> </tr> </thead> <tbody> {% for item in object_list %} <tr> <td>{{item.pk}}</td> <td>{{item.prod_name}}</td> <td>{{item.company}}</td> <td>{{item.quantity}}</td> <td>{{item.price}}</td> <td>{{item.units}}</td> <td>{{item.prod_type}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} But the results are not getting displayed -
Django (REST Framework) Returns Empty List Every Other Call
I have a simple function that generates a random sample list of items from the outer dictionary. def get_random_product_feed_for(mid, n=DEFAULT_AMOUNT_ITEMS_RETURNED): assert mid is not None, 'Merchant ID cannot be null while retrieving products feed' n = min(n, MAX_FEED_ITEMS_RETURNED) if mid in ADVERTISERS_PRODUCT_FEEDS: # check if merchant is present in the outer dict feeds = ADVERTISERS_PRODUCT_FEEDS[mid] # retrieve merchant's items # Sample list if len(feeds) >= n: random_feeds = random.sample(feeds, n) else: random_feeds = feeds return random_feeds return [] Where ADVERTISERS_PRODUCT_FEEDS = defaultdict(list). However, when I use this function in REST Framework API call, it returns empty list half the time; every other call. I don't think, however, the problem is in views or serializers. The setup is a little bit more complex than this. ADVERTISERS_PRODUCT_FEEDS is fetched asynchronously, because it is processed from large files that need to be downloaded. threads = [] # to keep only one active thread for the process def fetch_products_feed(): for thr in threads: if not thr.is_alive(): threads.remove(thr) if len(threads) > 0: logging.warning( 'Attempted to create multiple threads for product feeds fetching process. ' 'Wait until it is done!' ) return thread = threading.Thread(target=fetch_products_feed_sync, name='Fetch-Products-Thread') threads.append(thread) thread.start() So far I can only assume that fetch_products_feed_sync … -
NoReverseMatch at /friend/add_friend_link/PHByb3BlcnR5IG9iamVjdCBhdCAweDdmY2RlMTkwZjI3OD4/
No reverse match error: my urls.py : urlpatterns = [ url(r'^add_friend_link/(?P<uidb64>[0-9A-Za-z_\-]+)/$', add_friend_link, name='add_friend_link'), re_path(r'^accept_friend_request(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<status>[\w-]+)/$', accept_friend_request, name = 'accept_friend_request'), ] my view.py : def add_friend_link(request, uidb64): """Adding a link in email which is sent to friend through which one can accept or reject friend request""" status = "Pending" try: uid = urlsafe_base64_decode(uidb64).decode() # print(uid) user = User.objects.get(pk=uid) # print(user) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None return render(request, 'users/accept_friend.html', {"uidb64": uid, 'user':user}) This view will send email to friend for requesting in hyperlink: def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" uid= urlsafe_base64_decode(uidb64).decode() status = 'Pending' friend_user = User.objects.get(id=Friend.to_user.id) print(friend_user) f = Friend.objects.filter(friend_id = friend_user) if f: f.status=status f.save() return request, "users/friend_list.html", {"uidb64": uid, "status": status} else: return render(request, 'blog/base.html') This view will be redirected to a template which has 2 buttons: Accept and reject and based on that it will be redirected to next page. my template.html: <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Confirm Friend Request</legend> <h5>Are you sure you want to confirm the friend request of {{ user.id }}</h5> <div class="form-group"> <a class="btn … -
How can I perform this join in django?
I have the following two models in django that represent a post and the post's likes: class Post(models.Model): title = CharField(max_length=200) content = TextField() num_comments = PositiveIntegerField(default=0) class Like(models.Model): LIKE_CHOICES = [('L', 'Like'), ('D', 'Dislike')] user = ForeignKey(User, on_delete=models.CASCADE) post = ForeignKey(Post, on_delete=models.CASCADE) state = CharField(default='L', max_length=1, choices=LIKE_CHOICES) created_at = DateTimeField(auto_now_add=True) updated_at = DateTimeField(auto_now=True) How can I perform a join in my view that would get all the posts and then perform a join to get the like state of the user sending sending the request for each of the posts (None if user hasn't liked or disliked)? The only way I can think to maybe do this would be to use select_related() but I don't know how I would use it in my case since Post doesn't have a reference to Like.