Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failed at step EXEC spawning /var/www/loveIt/env/bin/gunicorn: No such file or directory
I have a problem with gunicorn. I followed this guide to run website hosting on my raspberry on debian. But I got this error: gunicorn.service: Failed at step EXEC spawning /var/www/loveIt/env/bin/gunicorn: No such file or directory I don't understand why it don't create gunicorn. I watched a lot of guides but no one helped me. Here is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=anton Group=www-data WorkingDirectory=/var/www/loveIt ExecStart=/var/www/loveIt/env/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ lulu.wsgi:application [Install] WantedBy=multi-user.target And this is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target What I need to do to solve this problem? -
django application not working after i add watchtower logging
import boto3 boto3_logs_client = boto3.client("logs", region_name=AWS_REGION_NAME) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': logging.ERROR, 'handlers': ['console'], }, 'formatters': { 'simple': { 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'watchtower': { 'level': 'DEBUG', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_client': boto3_logs_client, 'log_group_name': AWS_LOG_GROUP, 'log_stream_name': AWS_LOG_STREAM, 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': False, }, # add your other loggers here... }, } Here i implemented watchtower logging in my django app My server is running but when i view http://127.0.0.1:8000/ This site can’t be reached what can be the error ? am i missing something please take a look. please take a look how can i fix this -
IntegrityError : null value in column of relation " violates not-null constraint
'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a " null value in column "customer_id" of relation "products_order" violates not-null constraint DETAIL: Failing row contains (21, null)." error : models.py class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) views.py : class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data() form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Product, name=self.kwargs['product_name']) customer = form.save() Order.objects.create(customer=customer) instance= Order.objects.create() instance.product.set(product) return super(TemplateView, self) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context -
i couldn't find out this script at all in django-form
would you please explain this scripts? why we used **def init(self, *args, kwargs): AND **super(ProfileForm, self).init(*args, kwargs) ? *from django import forms from django.forms import fields from .models import User class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = None self.fields['username'].disabled = True self.fields['email'].disabled = True self.fields['special_user'].disabled = True self.fields['is_author'].disabled = True class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'special_user', 'is_author' ] thanks.* -
SMTPAuthenticationError at /members/register after deployment in heroku ut works in local host
I am getting the below error when I aam trying to send an email to user. It is wroking fine in localhost, but after deploying it to heroku I am getting this error. My less secure app is turned on. SMTPAuthenticationError at /members/register (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 iREvsLOCGsSdIvQozvsLAI32usRkAKeN9zrVcpG8_5BPTE8Cid59meSrouoFeVL7uexVM\n5.7.14 9BeaQ5gSKAKohzILe4Nqyrn_p3OJhBZJVuJ3Nb36rtmD2h_Rb7TCpJRB6xMw87Ow>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 n7sm3256692wro.68 - gsmtp') settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' SERVER_EMAIL = EMAIL_HOST_USER -
How to intersect two query sets in django?
I have two queries. One of them has sold product id and sale amount, other one has product id and product price. query_product = Model1.objects.filter(...).values_list('ProductID', 'ProductPrice') query_sale = Model2.objects.filter(...).values_list('SaleProductID', 'ProductAmount') I want to calculate IF SaleProductID = ProductID, Sum(F('ProductPrice')*F('ProductAmount'). However, I could not find how to do that with query. Note: Model2 has foreign key to Model1. Do you have any suggestions? Thank you! -
FormData and Django: How to pass empty array
I have email_list field in my form If there are no emails entered as Json payload i can send it as: { email_list: [] } Where as with FormData how to send it. I am thinking something like this if (data["email_list"].length === 0) { formData.append("email_list", []); } data["email_list"].forEach((item) => { formData.append("email_list", item); }); Am i doing the right way I checked the data i recieved in the django backend print(request.POST.getlist('email_list')) it prints [""] i want it to be [] -
Not redirecting to next page after login in Rest Framework
I have been trying to redirect the user to the main page after successful login in API. Email id and password which will be comes from the Angular. However, the email and password which is already existed in the SQL server where I have called the Stored Procedure in the Django rest framework. All I just want to pass the user's input in the place of 'demouser@demo.com' and 'NewUser@1' into the Stored Procedure now I have hardcoded value of the email and password which I suppose to get it from the POST request. How could I able to pass the post request in the Stored Procedure. views.py @api_view(['GET', 'POST']) def CheckUserStatusView(request): if request.method == 'GET': users = Tblusers.objects.all() serializer = CheckUserStatusSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_CheckOneQUserStatus] @EmailId=%s, @Password=%s', ('demouser@demo.com', 'NewUser@1')) result_set = cursor.fetchall() for row in result_set: row[2] if request.data.get('EmailId') == row[2]: serializer = CheckUserStatusSerializers(data=request.data) if serializer.is_valid(): serializer.save() return HttpResponseRedirect(redirect_to='https://127.0.0.1:4200/#/dashboard') # return Response(status=status.HTTP_308_PERMANENT_REDIRECT) return Response(status=status.HTTP_201_CREATED) serializers.py class CheckUserStatusSerializers(serializers.ModelSerializer): class Meta: model = Tblusers fields ='__all__' models.py class Tblusers(models.Model): UserID = models.AutoField(db_column='UserID', primary_key=True) FullName = models.CharField(db_column='FullName', max_length=255) Emailid= models.CharField(db_column='AccentureID', max_length=255) Password = models.CharField(db_column='Password', max_length=200) -
Adding foreign key data through django rest framework serializer
I am new to django, I have two models User and Todo. User can have multiple todos, while creating the todos I want to pass user_id with it but while including user_id or user field along with request.data, I am getting validation error for Todo fields. Here is the User model and Todo model: class User(AbstractUser): email = models.EmailField(unique=True) password = models.CharField(max_length=128) username = None name = models.CharField(max_length=128) is_email_verified = models.BooleanField(null=True) mobile = models.CharField(max_length=13, validators=[RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}', message="Enter a valid mobile number")], default='+911234567890') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['mobile'] class Todo(models.Model): title = models.CharField(null=False, blank=False, max_length=100) description = models.TextField(max_length=500) user = models.ForeignKey(User, on_delete=models.CASCADE, default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: indexes = [ models.Index(fields=['created_at']), models.Index(fields=['updated_at']) ] Here is the Todoserializer: from rest_framework.serializers import ModelSerializer, CharField from todos.models import Todo from users.models import User class TodoSerializer(ModelSerializer): class Meta: model = Todo fields = '__all__' read_only_fields = ['id', 'created_at', 'updated_at'] Here is the view for creating todos: @api_view(['POST']) def create(request): user = request.user todo = TodoSerializer(data={ **request.data, 'user': user.pk }) todo.is_valid(raise_exception=True) todo.save() return Response(status=status.HTTP_200_OK, data={'todo': todo}) The serializer doesn't get validated any time -
Are "max_length" and "choices" in Model's class definition supposed to prevent from inserting invalid values into the database?
I have a situation where i have a model (in Django/python) like: ''' class Box(models.Model): BOX_CHOICES = [('L','Large'),('M','Medium'),('S','Small')] size= models.CharField(max_length=1,choices=BOX_CHOICES, blank=True, null=True) ''' I thought that this would insure that i couldn't add a string like "Humongous" into size field. And yet, i was able to accomplish just that using get_or_create function to insert. Could you please explain how come the max_length and choices did not restrict that from inserting. Thank you! -
How to visualize data in a Django (real-time)
The problem here is that, there are several options I can use in order to display real-time visualization in django. But which one of them is simple enough to be used in teaching a newbie? What I'm trying to do is visualize data which is fetched from an external API. -
how to group by with annotate in django?
I tried absolutely everything with values().annotate() or aggregate() , or by following tutorials with Subquery I cant get what I want, let me explain : There is what I get with QuizzUserItem.objects.filter(examuser=user_exam).values('item__question', 'item') {'item': 759, 'item__question': 429} {'item': 762, 'item__question': 430} {'item': 763, 'item__question': 430} {'item': 767, 'item__question': 431} What I want is to group by item__question and get this result : {'item': 759, 'item__question': 429} {'item': 762,763 'item__question': 430} {'item': 767, 'item__question': 431} I start to think there is absolutely no way :/ What I tried : QuizzUserItem.objects.filter(examuser=user_exam).values('item__question','item').annotate(items_number=Count('item__question')) I got : {'item': 759, 'item__question': 429, 'items_number': 1} {'item': 762, 'item__question': 430, 'items_number': 1} {'item': 763, 'item__question': 430, 'items_number': 1} {'item': 767, 'item__question': 431, 'items_number': 1} or QuizzUserItem.objects.filter(examuser=user_exam).values('item__question').annotate(items_number=Count('item__question')) This one is the closest result that I got : {'item__question': 429, 'items_number': 1} {'item__question': 430, 'items_number': 2} {'item__question': 431, 'items_number': 1} But I have not the item_ids 762,763... Thank you for reading -
TypeError: An asyncio.Future, a coroutine or an awaitable is required in the django-channels
Requirements Python 3.8 asgiref 3.2.0 channels 2.4.0 channels-redis 2.4.2 Django 3.0.9, gunicorn 20.1.0 redis 3.5.3 uvicorn 0.11.5 websockets 8.1 I run channels as gunicorn -w 5 -b 0.0.0.0:8000 --log-level debug -k uvicorn.workers.UvicornWorker config.asgi:application. Also I have nginx as proxy-server. Logs class TokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): return TokenAuthMiddlewareInstance(scope, self) class TokenAuthMiddlewareInstance: def __init__(self, scope, middleware): self.middleware = middleware self.scope = dict(scope) self.inner = self.middleware.inner async def __call__(self, receive, send): try: token_key = (dict((x.split("=") for x in self.scope["query_string"].decode().split("&")))).get( "token", None ) except ValueError: token_key = None if token_key is None: self.scope["user"] = AnonymousUser() else: token_data = await get_token_data(token_key) self.scope["user"] = await get_user(token_data["user_id"]) inner = self.inner(self.scope) return await inner(receive, send) -
What is the implication of using request.user over self.request.user
I want to know the major difference between self.request.user (when using generic view View) and request.user (when using a user defined view), at times when I use django's generic View (django.views.generic import View) which has access to the django User model, I'd interact with the authenticated user as request.user and self.request.user without having any problem. For instance, in a django views.py: from django.contrib.auth import get_user_model User = get_user_model() class GetUserView(View): def get (self, request, *args, **kwargs): user_qs = User.objects.filter(username=request.user.username) #Do some other stuffs here class AnotherGetUserView(View): def get(self, request, *args, **kwargs): user_qs = User.objects.filter(username=self.request.user.username) #Do some other stuffs here I realize that the two queryset works fine but I can't still figure out the best to use. -
python Bad Request: /emails
I am trying to make an email web app using python but when I try to press the submit button to send the email this is what I get: [08/Dec/2021 15:26:26] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails [08/Dec/2021 15:26:38] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails ``` Please help! -
How can I solve server error 500 which I am getting during django app deployment on heroku?
When I set debug equals to false my app doesnot work on both local n live env but when I set debug equals true it works all right in local env but gives same server 500 error on live env. This is the github repo for my django project: [https://github.com/Pran1001/HomeFinder] and settings.py file : https://github.com/Pran1001/HomeFinder/blob/main/HOMEFINDER/settings.py below are the logs which I am get from running heroku logs command 2021-12-08T15:01:27.896609+00:00 heroku[router]: at=info method=GET path="/" host=searchyourghar.herokuapp.com request_id=a4b3fa9d-2551-402e-b7ca-5c41c94fbb50 fwd="49.32.177.39" dyno=web.1 connect=0ms service=21ms status=500 bytes=409 protocol=http -
File upload returns no HTTP status
I have a Django / React application hosted in AKS. React's build is hosted statically with Nginx. The Nginx container is exposed through a ClusterIP, Ingress & Nginx-Controller. The In this app, I'm doing a file upload, which returns nothing. Not an error, not an HTTP status code, nothing. That makes debugging very hard. This doesn't happen locally, and it only happens with files bigger than approx 10mb. Already increased the client_max_body_size in the default.conf of the nginx host. Can't find anything in the Controller docs that indicates a too large filesize, and this would also result in a HTTP 413. Anyone familiar with this? In React I simply use axios with formData: let formData = new FormData(); axios.post(`${API_SERVER}/builds`, formData).then(response => { console.log(response); }).catch(error => console.log(error)); The HTTP response: undefined undefined undefined date: Wed, 08 Dec 2021 15:27:35 GMT content-type: text/html content-length: 176 strict-transport-security: max-age=15724800; includeSubDomains X-Firefox-Spdy: h2 -
Cannot successfully pass foreign_key reference to PUT request in Django REST
I am getting into Django REST and I am trying to use it for a backend of type of crypto currency tracker for my use. However I have been stuck on an issue for a few days.. I have the following models.py: class Coin(models.Model): sign = models.CharField(max_length=50, primary_key=True) # capitalize all entries name = models.CharField(max_length=50, null=False) amount = models.DecimalField(max_digits=20, decimal_places=2, null=False) price_each = models.DecimalField(max_digits=20, decimal_places=2, null=False) purchased_on = models.DateField(null=True) def __str__(self): return self.sign def save(self, *args, **kwargs): self.sign = self.sign.upper() return super(Coin, self).save(*args, **kwargs) class Price(models.Model): coin = models.ForeignKey(Coin, related_name="prices", on_delete=models.CASCADE) day_date = models.DateField(null=False) current_price = models.DecimalField(max_digits=20, decimal_places=2, null=False) def __str__(self): timestamp = self.day_date.strftime("%d-%b-%Y") return timestamp and serializers.py: class PriceSerializer(serializers.ModelSerializer): coin_sign = serializers.PrimaryKeyRelatedField(queryset=Coin.objects.all(), source='coin.sign') class Meta: model = Price fields = ['id', 'day_date', 'current_price', 'coin_sign'] def create(self, validated_data): return Price.objects.create(**validated_data) class CoinSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True, read_only=False) class Meta: model = Coin fields = ['sign', 'name', 'amount', 'price_each', 'purchased_on', 'prices'] def create(self, validated_data): return Coin.objects.create(**validated_data) I am having trouble defining a view with PUT to create a new price entry in view.py: class AddPrice(APIView): def put(self, request, sign, format=None): coin = get_object_or_404(Coin, sign=sign.upper()) request.data['coin_sign'] = coin serializer = PriceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the … -
How to get Todo items with today as deadline
so i'm still creating my todo list app, and i want to render all the items that has todays date as the deadline so as to remind the user of the pending tasks. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class ToDo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) todo = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True) created = models.DateField(auto_now=True) end = models.DateField() start = models.DateField() completed = models.BooleanField(default=False) def __str__(self): return f'{self.owner} - {self.todo}' views.py def index(request): activities = ToDo.objects.all() today = ToDo.objects.get(end=datetime.date.today) todo = ToDo.objects.count() complete = ToDo.objects.filter(completed=True).count() percent = complete * 100 // todo if request.method == 'POST': try: search = request.POST.get('todo') activities = ToDo.objects.filter(todo__icontains=search) except: search = request.POST.get('end') activities = ToDo.objects.filter(end=search) context = { 'activities' : activities, 'percent' : percent, 'today' : today, } return render(request, 'home.html', context) i imported datetime in my views.py -
Title cannot contain "Ask a public question". Please provide a title that summarizes your question. For assistance, see: How do I ask a good question?
A standard blockquote is indented A nested blockquote is indented more You can nest to any depth You can nest to any depth -
ManyToMany Model query
I have 2 models Project and Investor Project model has a field called project_investors with a ManyToMany to the Investor model. Models class Investor(models.Model): investor_name = models.CharField(max_length=50, blank=False, unique=True) investor_website = models.URLField(max_length=100, blank=True) investor_portfolio_website = models.URLField(max_length=100, blank=True) investor_description = models.TextField(blank=True) investor_investments = models.TextField(blank=True) def __str__(self): return str(self.investor_name) class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) project_investors = models.ManyToManyField(Investor, blank=True) def __str__(self): return str(self.project_name) I then have a page the shows the Investor details and im trying to show which projects have been linked to this investor. myview.py @login_required def show_investor_details(request,investor_id): investor = Investor.objects.get(pk=investor_id) form = InvestorForm(request.POST or None, instance=investor) project = Project.objects.all() project_list = get_object_or_404(Project, project_investors=investor_id) return render(request, 'pages/investor_details.html', {"investor": investor, "form": form,"project": project,'project_list':project_list}) Im not sure what is the correct query to pass in here project_list = get_object_or_404(Project, project_investors=investor_id) as this error is thrown: 'Project' object is not iterable Or maybe I have the model structure incorrect? -
Reverse for 'delete_post' with arguments '('',)' not found. 1 pattern(s) tried: ['article/(?P<pk>[0-9]+)/remove$']
i was creating a simple blog site and I created buttons to delete7edit , but as soon as I try to reset the app and go there I get this error ( title ) this is my code view.py: from django.views.generic import ListView from . models import Article from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import PostForm, EditForm from django.urls import reverse_lazy class ArticleListView(ListView): model = Article template_name = 'home.html' class ArticleDetailView(DetailView): model = Article template_name = 'detail.html' class AddPostView(CreateView): model = Article form_class = PostForm template_name = 'add_post.html' #fields = '__all__' #fields = ('title', 'body') class UpdatePostView(UpdateView): model = Article form_class = EditForm template_name = 'update_post.html' #fields = ['title', 'title_tag', 'body'] class DeletePostView(DeleteView): model = Article template_name = 'delete_post.html' success_url = reverse_lazy('home') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.ArticleListView.as_view(), name='home'), path('article/<int:pk>', views.ArticleDetailView.as_view(), name='detail'), path('add_post/', views.AddPostView.as_view(), name='add_post'), path('article/edit/<int:pk>', views.UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', views.DeletePostView.as_view(), name='delete_post'), ] help me please, I'm new on django and i don't know things yey -
Product matching query does not exist
i'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a Page Not Found error "No Order matches the given query." Bellow you can check the code Models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255, unique=True, ) description = models.TextField(max_length=1500) class Meta: verbose_name_plural = "categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) Views.py class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data() form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Order, product__name=self.kwargs['product_name']) customer = form.save(commit=False) Order.objects.create(product=product, customer=customer) form.save() return super(TemplateView, self) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context forms.py class OrderForm(forms.ModelForm): class … -
Django: I get: Cannot query "admin": Must be "Follow" instance in my code when trying to implement unfollow button
I'm a beginner and I'm trying to create a small network project in which users can follow each other. I have implemented the follow button right, so it updates my models and displays proper info to users, but I can't get unfollow to work properly. I'm guessing it's something to do with the way I implemented follow model (with many to many field), but I'd like to implement it this way for practice... Anyhow, here's the code: Models: class User(AbstractUser): pass class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_follow") following = models.ManyToManyField(User, blank=True, related_name="followers") And view: def users(request, username): """Displaying user profiles""" if request.method == "POST": user = request.user profile = User.objects.get(username=username) follow = Follow(user=user) follow.save() if "unfollow" in request.POST: profile.followers.remove(user) follow.following.remove(profile) return HttpResponseRedirect(reverse('users', args=(username,))) elif "follow" in request.POST: follow.following.add(profile) return HttpResponseRedirect(reverse('users', args=(username,))) This code yields in: "ValueError at /users/test Cannot query "admin": Must be "Follow" instance." at the profile.followers.remove(user) line... Playing with it in shell I found out (at least I think so) that the line under it (follow.following.remove(profile) - which by the way was there before I tried with the profile.followers.remove(user)) removes the profile from Follow model, but for some reason it is not by itself updated in the … -
How to fet a queryset for every object in queryset
Let's assume I have an Employees model. There are 3 different titles such as "Top manager", "Sales manager" and "Sales representative" and field "reports_to". Top manager doesn't report to anyone, Sales managers report to Top and Sales representatives report to Managers. I have a list view to see employees list, it shows employees who reports to higher employee as described above. Also I try to list employees who reports to those who report to me. Like (I'm logged in as a Top manager) --Here goes Sales manager ----Here goes this manager's Sales representatives So far I achieved getting manager's representatives, but only for the first manager in the queryset. The question is: how do I get separate querysets of Representatives for every Manager in queryset? Additional question: am I right in using prefetch_related() here? View: def get_current_users_employee(user): try: employee = Employees.objects.get(user=user) return employee except User.DoesNotExist: raise Http404("Employee doesn't exist for this user.") class EmployeesListView(LoginRequiredMixin, ListView): model = Employees template_name = 'employees/employees_list.html' context_object_name = 'employees_list' fields = ['last_name', 'first_name', 'title', 'birth_date', 'reports_to'] def dispatch(self, request, *args, **kwargs): handler = super().dispatch(request, *args, **kwargs) emp = get_current_users_employee(self.request.user) if (emp.title == "Sales representative"): raise PermissionDenied return handler def get_queryset(self): current_emp = get_current_users_employee(self.request.user) return super().get_queryset().filter(reports_to=current_emp) …