Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting 'cannot unpack non-iterable int object' when creating a model in Django
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=0) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) class RegisteredClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'RegisteredClass' unique_together = ['class_details', 'user'] def __str__(self): return 'Registered Class' + str(self.class_details) serializers.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' … -
fliter onto a prefetch django
Hello I want to know why my queryset don't work. models.py: class Category(models.Model): category = models.CharField(max_length=60) slug = models.SlugField(unique=True) class Product(models.Model): categories = models.ManyToManyField(Category, related_name="products") ... my queryset: Category.objects.prefetch_related( Prefetch( "products", queryset=Product.objects.annotate( effective_stock=... ), ) ).filter(products__effective_stock__gt=0) I get: Related Field got invalid lookup: effective_stock Thank you -
We have detected that you have triggered a build from source code, remote: ! at least twice
I found this error I tried log but couldn't find the solution, please let me know if anyone having the solution to this problem, actually two repositories is crated how to remove one so my code push on Heroku server ........ (tmenv) C:\Users\ok\Desktop\Django\Django_project\taskmate>git push heroku master Enumerating objects: 346, done. Counting objects: 100% (346/346), done. Delta compression using up to 4 threads Compressing objects: 100% (336/336), done. Writing objects: 100% (346/346), 1.50 MiB | 329.00 KiB/s, done. Total 346 (delta 58), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: Heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote:! Push failed remote:! remote: ! ## Warning - The same version of this code has already been built: f6098f48382cfe82018384a09a28f785eb546aae remote: ! remote: ! We have detected that you have triggered a build from source code with version f6098f48382cfe82018384a09a28f785eb546aae remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! … -
Not Found: / Error while deploying project on pythonanywhere
I'm deploying python django website on pythonanywhere. I added favicon.ico in static files and settings in my project and after running the web app I'm seeing Not Found The requested resource was not found on this server. and in error log getting : 2021-06-19 04:39:55,391: Not Found: /favicon.ico 2021-06-19 04:42:25,484: Not Found: / 2021-06-19 06:03:44,307: Not Found: / 2021-06-19 06:04:05,420: Not Found: / I have added code in urls.py : path( "favicon.ico",RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))) header.html : <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}"> and also install django-favicon package. how do I get rid of it? -
nested categories in Django and usage in template
I followed some instructions given by stackoverflow's answer for nested categories( by making the category model reference itself in the field called "parent"), but while implementing it, I came across the template tag problems where I can't really iterate the object since the error message says I can't. I tried to avoid this problem by trying using {% for i in c.c_set.all %}(where c stands for the for iterator in my template for loop) but just in vain. How can I loop through the nested categories in my html template using Django? thank you so much for your answer in advance! ###It's my models.py's Category model. class Category(models.Model): parent = models.ForeignKey('self', default=None, null=True, blank=True, related_name='nested_category', on_delete=models.CASCADE) nesting_level = models.IntegerField() name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=60) def __str__(self): return self.name ##This is my context_processors.py's function that returns "Category" querysets. def categories(request): Category = Category.objects.all() return { 'Category':Category, } ###This is my base.html's nav bar tags. <nav> <ul>{% for c in Category %} <li><a href="{{c.get_absolute_url}}">{{c.nesting_level}}{{c}}</a> <ul> {% for i in c %} <li><a href = "#">{{ i.name}}</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> </nav> -
how can i insert html code from database into django template?
i tried to insert it via dtl variables but there were html tags on the page models.py html code in desciption field class Vacancy(models.Model): title = models.CharField(max_length=100) specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE, related_name="vacancies") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="vacancies") skills = models.TextField() description = models.TextField() salary_min = models.FloatField() salary_max = models.FloatField() published_at = models.DateTimeField() html <a href="#"><img src="/media/company_images/{{ vacancy.company.logo }}" width="130" height="80" alt=""></a> <div class="d-flex align-items-baseline align-content-baseline"> <h1 class="h2 mt-4 font-weight-bold" >{{ vacancy.title }}</h1> <p class="m-0 pl-3">{{ vacancy.salary_min }}р – {{ vacancy.salary_max }}р</p> </div> <p class="mt-2">{{ vacancy.skills }}</p> <p class="text-muted mb-4">Primal Assault (15-30 человек), Рязань или удаленно</p> <div style="line-height: 1.8;"> {{ vacancy.description }} </div> -
Unable to recover Postgres server after power outage
I lost power to my Debian sandbox server running Django/Postgres. Now Django can't connect to Postgres: > python manage.py runserver 0:8000 [...] django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Searching for the exact error I understand this is a postgres error. I verified the postgresql server is running: > sudo systemctl status postgresql ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; **enabled**; vendor preset: enabled) Active: **active** (exited) since Wed 2021-06-16 21:15:49 EDT; 2 days ago I found this post from 6 years ago, django.db.utils.OperationalError Could not connect to server(2015) with a solution; however, the accepted answer wants a file and directory my installation of Postgres on Debian does not have /usr/local/var... or postmaster.pid: > find . -iname '*postmaster*' /postgresql/11 ./lib/bitcode/postgres/postmaster ./lib/bitcode/postgres/postmaster/postmaster.bc ./bin/postmaster The error message is somewhat misleading to my objective. Database settings are configured as default (localhost:5432)--the firewall is not configured for remote connections (sudo ss -tulpn | grep 5432 shows nothing; sudo lsof -nP -iTCP -sTCP:LISTEN has no setting … -
How can I change/update field value in my User model by button?
I'm using django-cookiecutter User model (added VideoTape ManyToMany connection). I've created my own model VideoTape. I want to create the option of adding a VideoTape for the user (by updating? videotapes field in User) by clicking the "RENT" button on page VideoTape details: models.py: class User(AbstractUser): name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore videotapes = models.ManyToManyField(VideoTape, blank=True, null=True) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) class VideoTape(models.Model): title = models.CharField(max_length=256, verbose_name=_("VideoTape Title")) slug = models.SlugField(max_length=256, unique=True, editable=False) description = models.TextField(verbose_name=_("VideoTape Description")) genres = models.TextField(verbose_name=_("VideoTape Genres"), null=True) thumbnail = models.URLField(null=True) def save(self, *args, **kwargs): if not self.slug: base = self.title.strip() for candidate in generate_slug(base): if not VideoTape.objects.filter(slug=candidate).exists(): self.slug = candidate break else: raise Exception("Can't create new VideoTape object") super().save(*args, **kwargs) def get_absolute_url(self): return reverse("videotapes:detail", kwargs={"slug": self.slug}) def __str__(self): return self.title videotape_detail.html {% extends "base.html" %} {% block content %} {% if request.user.is_superuser %} <div> <a href="{% url 'videotapes:update' slug=videotape.slug %}" class="btn btn-outline-primary"> <i class="fa fa-edit"></i>Edit </a> <a href="{% url 'videotapes:delete' slug=videotape.slug %}" class="btn btn-outline-danger"> <i class="fa fa-times"></i>Delete </a> </div> {% endif %} <div class="card"> <div class="card-horizontal"> <div class="img-square-wrapper"> {% if videotape.thumbnail %} <img class="" src="{{ videotape.thumbnail }}" alt="Card image cap" … -
How to prevent Django Post_Save signal fire twice? (dispatch_uid="my_unique_identifier" DOES NOT WORK for me)
How to prevent Django Post_Save signal fire twice? (dispatch_uid="my_unique_identifier" DOES NOT WORK for me) @receiver(post_save, sender=Session, dispatch_uid="my_unique_identifier") def post_save_session_email_to_manager(sender, instance, created, **kwargs): print('hihi') Why print('hihi') is fired twice when model (sender) Session is updated ? Any workaround ? -
In Django Todo App how can each user have a distinct set of the task?
I am making a todo app using Django. Currently, the problem I am facing is that no matter which user logs in, the same set of tasks appears, i.e. if a user adds some task for himself, they appear in every other user's todo list. How can I modify my code so that each user can have a distinct set of tasks? Here's some of my code: Here is my Code: Models from django.db import models # Create your models here. class TodooModel(models.Model): fd = models.TextField() cr_dt = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render,redirect from .models import TodooModel # Create your views here. def home(request): if request.user.is_authenticated: return render(request,"home.html") else: return redirect("user_login") def create(request): if request.user.is_authenticated: if request.method == "POST": fdk= request.POST.get("task") data = TodooModel(fd=fdk) data.save() return render(request,"create.html",{"msg":"Added Succesfully"}) else: return render(request,"create.html") else: return redirect("user_login") def views(request): if request.user.is_authenticated: data = TodooModel.objects.get() return render(request,"views.html",{"data":data}) else: return redirect("user_login") def delete(request,id): if request.user.is_authenticated: de = TodooModel.objects.get(id=id) de.delete() return redirect("views") else: return redirect("user_login")''' > `Blockquote` -
*name* is not defined
I am making a webpage using React frontend and Django backend. I have trouble running my backend because things supposedly aren't defined. E.g. I get this message when trying to run "python manage.py makemigrations": "name 'api_view' is not defined". All the yellow underlines says that name is not defined, except the one on line 1. I did not have this problem the last time a run my code (a month ago). Everything was working fine then. What can I do to fix it? -
I want to create a relational Database in Django with user_auth table which is created automatically in postgreSQL
I want to create a Relational database with auth_user table which is automatically created in django after migrations(database is postgresql). I have created a table with class named order. My models.py looks like this Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.CharField(max_length=50) price = models.IntegerField() now I want to link the user id with table order with user_id. And my views.py looks like this. views.py def order_Data(request): product = request.POST['product'] price = request.POST['price'] orders = order(product=product,price=price) orders.save() messages.info(request,'Data saved') return render(request,'home.html') I think I have linked tables properly but in user_id of order table is setting as null and giving me error. I dont know what to do now. Please Help me out (Iam also a learner in Django). Thank you in advance. -
Delete view for combined models
What I am trying to do is to delete the instance from a combined list from more than one models, I am getting the error 'list' object has no attribute 'filter' here is my class based delete view class NotificationDeleteView(LoginRequiredMixin, DeleteView): template_name = 'gym_admin/confirm_delete.html' success_url = reverse_lazy('notification_dash') success_message = 'Notification deleted successfully!' def get_queryset(self): subscription = Subscription.objects.filter(user=self.request.user).last() if subscription.status == 'active': promo_notification = PaidPromoNotification.objects.all() program_notification = PaidProgramNotification.objects.all() blog_notification = BlogPaidNotification.objects.all() video_notification = VideoPaidNotification.objects.all() qs = list( chain(promo_notification, program_notification, blog_notification, video_notification) ) return qs elif subscription.status == 'trialing': promo_notification = PromoNotification.objects.all() program_notification = ProgramNotification.objects.all() blog_notification = BlogNotification.objects.all() video_notification = VideoNotification.objects.all() qs = list( chain(promo_notification, program_notification, blog_notification, video_notification) ) return qs -
Django DetailView and FormView on same URL, how to handle form validation errors?
I'm creating a page where a question (DetailView) is asked and the user can answer (FormView) using the same URL. I've basically followed the advice from the docs here - https://docs.djangoproject.com/en/3.2/topics/class-based-views/mixins/#an-alternative-better-solution class QuestionView(View): def get(self, request, *args, **kwargs): view = QuestionDetailView.as_view(template_name='question_detail.html') return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = AnswerFormView.as_view() return view(request, *args, **kwargs) My DetailView is something like this where you can see I am adding the form to the context. In addition I do some extra validation in my AnswerForm.clean() method. class QuestionDetailView(DetailView): model = QuestionModel def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AnswerForm return context It can be displayed properly and when the user submits the Answer (via a POST) it can work when my form validation passes. The problem is how to handle this when the form validation fails because the get_context_data() belongs to the GET, not the POST. I tried just adding the same get_context_data() to the POST related code but then the form errors do not show up on the form, so the user doesn't know what is wrong. Any advice welcome, thanks. -
How can I pass multiple parameters into the API url in Django Rest Framework?
kindly guide me in this matter I'm a beginner looking forward to you -
Adding post creater user instead of request.user
I am building a BlogGroup App and I am stuck on an Error. I am trying to add users in database from the Post Detail Page in template. BUT when i try to add post creater User then it is adding request.user. I have no idea what is wrong in the code. models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') class GroupPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') class BannedMembers(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) views.py def ban_user(request,pk): groupss = Group.objects.get(id=pk) posts = get_object_or_404(GroupPost,pk=pk) if request.method == 'POST': form = BannedMembersForm(data=request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.user = request.user new_post.group = groupss new_post.save() new_post.banned_members.add(posts.user) return redirect('mains:home') else: form = BannedMembersForm() context = {'form':form} return render(request, 'ban_user.html', context) def PostDetailView(request,pk): data = get_object_or_404(GroupPost,pk=pk) context = {'data':data} return render(request, 'Postdetail.html', context) Postdetail.html {% block content %} {{ data.user }} <b>User :</b> <a href="{% url 'ban_user' data.user.id %}">Ban {{ data.user }}</a> {% endblock content %} I am trying to save the post owner to add in banned_members but it is adding request.user everytime. Any help would be much Appreciated. Thank You in Advance -
django nginx gunicorn application showing apache2 default page - only on ip request not domain name
Very odd behavior from my Ubuntu 18.04 LTS server I have followed this tutorial here (twice) and it is all working properly except a couple odd things firstly, when I use my browser to visit the IP of my VPS, the django default application page shows up throughout the tutorial however accessing it through the domain name results in a time out error secondly, now that I have completed the tutorial and configured nginx to proxy pass to gunicorn, the apache2 ubuntu default page is now displaying instead of the django default page on a visit to the ip address and still no response from the domain name, even though there is no installation of apache2 on this server... $ whereis apache2 apache2: here is my gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target here is my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=trends Group=www-data WorkingDirectory=/trends_dir ExecStart=/trends_dir/trendsvenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ trends.wsgi:application [Install] WantedBy=multi-user.target here is my /etc/nginx/sites-available config file for the site, which has been properly symlinked to /etc/nginx/sites-enabled server { listen 80; server_name www.trendsontheblock.com trendsontheblock.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /trends_dir; … -
Addinng a string utilizing a quote in django raw query
I want to include a string as a query and the string would contain spaces so I would need to make use of quotes. But this is giving me error that it is expecting another parameter. ModelName.objects.raw("select * from tablename where city='%s' and state=%s",params=['San francisco', 'Los Angeles']) This the error that is produced error: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied. -
Django multiple annotate with Sum get wrong answer
I'm trying to use .annotate() with multiple Sum() But i got wrong calculations. I've read that I should use Subquery but I didn't get it done with it maybe I use it in wrong way (because it is first time) or it doesn't solve my issue. class DonationQuerySet(QuerySet): def completed(self): return self.with_donations_stats().filter( amount__lte=F('total_donation'), deleted_at=None) def not_completed(self): return self.with_donations_stats().filter( amount__gt=F('total_donation'), deleted_at=None) def with_donations_stats(self): return self.annotate( wallet_donation=Coalesce(Sum('wallet_transaction__amount'), 0), normal_donation=Coalesce(Sum('transactions__amount'), 0), total_donation=F('wallet_donation') + F('normal_donation')) class DonationManager(Manager): def get_queryset(self): return DonationQuerySet(self.model, using=self._db) def completed(self): return self.get_queryset().completed() def not_completed(self): return self.get_queryset().not_completed() def with_donations_stats(self): return self.get_queryset().with_donations_stats() How could I solve it? -
how to create relation between existing data in case of OneToMany relation in Django?
Let assume there are two table custom_users and sub_products and there is one-to-many relation between them i.e, a user can have multiple products . Bellow is the code:- Sub_Products:- class Sub_Products(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() pic = models.ImageField(upload_to="sub_products") products = models.ForeignKey(Products, on_delete=models.CASCADE) custom_user = models.ForeignKey(CustomUsers, null=True, on_delete=models.SET_NULL) CustomUsers:- class CustomUsers(AbstractBaseUser): username = models.CharField(max_length=40, unique=True) email = models.EmailField() password1 = models.CharField(max_length=10, blank=False) # is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] Now table created by these two models are containing data except custom_user field in sub_products table. Data in CustomUsers Table:- >>> allusers = CustomUsers.objects.all() >>> print(allusers) <QuerySet [<CustomUsers: admin@gmail.com,True,TrueTrue,Truepbkdf2_sha256$260000$eRZ8K8QIVKL9hpyMlyr0n0$5L+P3/2o1vSx4kN6mne5YCANDry0LmAOx6kHEHtBIDM=>, <CustomUsers: at harva@gmail.com,False,FalseTrue,Falsepbkdf2_sha256$260000$jyc9eK0V3Dr0roJFZG1GJU$27COkzOdmiOd4NuGpZu/zp9O5d4qOeVE5zAMSwt9jPs=>]> And Data in Sub_Products table:- >>> allproducts = Sub_Products.objects.all() >>> print(allproducts) <QuerySet [<Sub_Products: Tshirt>, <Sub_Products: HRX tshirt>, <Sub_Products: Tshirt>, <Sub_Products: Nike Tshirt>, <Sub_Products: Shirts>, <Sub_Products: RoadStar Ts hirt>, <Sub_Products: Nike Tshirt>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Jeans>, <Sub_Products: Slipers>, <Sub_Products: Sandel>, <Sub_Products: Slipers>]> Now my real question how should we create relation between existing user and products such that a user can have multiple products. I really appreciate your help. Thanks in advance. Hope to … -
I deployed a site for trial using GitHub zeet and Django website and my css files and images is showing not found
I did deploy a Django site using GitHub hosted with zeet and its not showing the css and images and javascript i need help. I did try many ways it does work if I make it with just html css and javascript but not working with Django. -
how can i update a filed in django after the time ends?
my projects is bidding site, i wanted to close the bid after some specific date. but i don't know how to implement it. please any one suggest me anything models.py class products(models.Model): produtname=models.CharField(max_length=255) productdesc=models.CharField(max_length=255) amount=models.FloatField() image=models.ImageField(upload_to='pics') featured=models.BooleanField(default=False) enddate=models.DateTimeField() soldout=models.BooleanField(default=False) after the end date the field soldout should be automatically set to true -
Django Admin list_filter and ordering on annotated fields
I'm trying to filter in Django Admin on an annotated field, but getting a FieldDoesNotExist error. class Event(models.Model): name = models.CharField(max_length=50, blank=True) class EventSession(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) start_date = models.DateTimeField() end_date = models.DateTimeField() @admin.register(Event) class EventAdmin(admin.ModelAdmin): ordering = ["event_start_date"] list_filter = ["event_start_date", "event_end_date"] def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate( event_start_date=Min("eventsession_set__start_date"), # start of first day event_end_date=Max("eventsession_set__start_date"), # start of last day ) return qs The resulting error in Django Admin is: FieldDoesNotExist at /admin/events/event/ Event has no field named 'event_start_date' I need to filter on event_start_date rather than eventsession_set__start_date because filtering on the latter causes multiples rows per event (one for each session) to show up in the list view. The error comes from the get_field method of django/db/models/options.py: try: # Retrieve field instance by name from cached or just-computed # field map. return self.fields_map[field_name] except KeyError: raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) I'm on Django 3.2. Any ideas? -
When I define a custom manager .. Error:Manager isn't accessible via Post instances
I defined a custom manager inheriting models. Manager put in in my model 'Post'. The error says that you cant call manager through a instance but i have not called it through a instance it works fine when i remove the custom manager. models.py: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='Published') class Post(models.Model): STATUS_CHOICES = [ ('draft','Draft'), ('published','Published'), ] id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200) created = models.DateTimeField(auto_now_add=True) published = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='Published') author = models.ForeignKey(CustomUser,on_delete=models.CASCADE) body = models.TextField() objects = models.Manager() published = PublishedManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("detail", kwargs={"slug":self.slug,"id": self.id}) views.py: class PostListView(ListView): model = Post template_name = 'blog/index.html' context_object_name='posts' Error image -
I want to restrict a particular user from creating a saved class object if the current user id is different from the id in the live class object
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=2.5) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_registered = models.BooleanField(default=False) is_attended = models.BooleanField(default=False) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) my views.py from django.shortcuts import render from rest_framework import mixins from rest_framework import generics from django.contrib.auth.mixins import LoginRequiredMixin from rest_framework import status from django.contrib.auth.models import User from rest_framework.response import Response from django.contrib.auth import authenticate from . import serializers from . import models # Create your …