Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect from resource not working
I have this in my resource: def after_import_instance(self, instance, new, row_number=None, **kwargs): ... base_url = 'https://account.box.com/api/oauth2/authorize' client_id = '[CLIENT_ID]' auth_url = f'{base_url}?client_id={client_id}&response_type=code' print(auth_url) return redirect(auth_url) the auth_url is being printed, but the redirect is not working. Here is the print: [2022-09-01 05:07:10,617: WARNING/MainProcess] https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code -
Django Rest Framework - SearchFilter
I need to try get a SearchFilter working for fields within a set within another set. class Fight(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="fights") class FighterStats(models.Model): fight = models.ForeignKey(Fight, on_delete=models.CASCADE, related_name="fighters") fighter = models.ForeignKey(Fighter, on_delete=models.CASCADE, null=True) class EventSearchFilter(filters.SearchFilter): def get_search_fields(self, view, request): field_names = { "name": "name", "venue": "location__venue", "fighters": "fights__fighters__fighter__first_name__name" } Don't have issues with getting foreign keys to work but i could use some help with foreign sets. I removed the unrelated fields/code from above. -
Rendering Django_Filter Search Results on the searched Property Page
I have tried different options and I don't seem to get how to show my searched property from the home page on searched page. Basically, I have two templates home page and searched property page. I have a search form in my home page and I would like to display the results on the other page. My views.py for Home Page def home(request,): properties = Property.objects.all()[:5] context = {"property": property, "properties": properties} return render(request, "base/index.html", context) My views for Search Page def prop_search(request,): property = Property.objects.all() properties = Property.objects.all() images = Image.objects.filter(property__in=property.all()) propFilter = PropertyFilter(request.GET, queryset=property) count = propFilter.qs.count() context = { "propFilter": propFilter, "property": property, "properties": properties, "images": images, 'paginator':paginator, } return render(request,'base/property-list.html', context) My Urls.py path("", views.home, name="home"), path("add-property", views.addProperty, name="addProperty"), path("prop_search", views.prop_search, name="prop_search"), -
how i can change str serializers name to class objects using django
class Create(View): def get(self, request): sername = request.GET.get('SerializersName') result = sername(request.POST) if result.is_valid(): result.save() return ***** -
Django dynamic ListView filtering problem
I am working on my first solo project with Django and I have hit a problem that no amount of searching and reading similar post on SO have solved. I am trying to filter a gallery of images by their category, so that when the user clicks on a picture it will result in a page showing all the images with the same category. This will use HTMX hopefully in the final product, but I'm trying and failing to implement it using regular Django views initially. As I said, this is my first solo project, so I'm very much a beginner, I know this isn't a debug service but just wanted some pointers on where I could be going wrong. Another set of eyes as you will. I followed the docs on dynamic filtering CBV. I have overwritten get_queryset passing the Category slug into the kwargs and I have overwritten the get_context_dataso I can pass slug into the template. I am getting a Reverse for 'select' with arguments '('',)' not found. 1 pattern(s) tried: ['select/(?P<slug>[-a-zA-Z0-9_]+)\\Z'] error, so I belive the problem is in my template/URLconf. Models. Media with a FK to it's Category class Category(models.Model): title = models.CharField(max_length=200, null=True) slug … -
Django-allauth : prevent user to provide alternative email when logging using social account
I use django-allauth with google and facebook providers and the following options: SOCIALACCOUNT_AUTO_SIGNUP=True SOCIALACCOUNT_EMAIL_VERIFICATION="none" With these settings, django-allauth will use the email provided by the 3rd-party app (Facebook, Google), unless it is already used in an existing account. In this case the user can choose whatever email. I would like an error message instead of that, saying that the address is already in use since I do not want to validate email with social accounts (using social accounts should be handy). How to prevent using social accounts that are associated with an address which is already registered? -
How do I solve this Django HttpResponse error please?
My problem is that in the templates and in the CMD I become a None return instead the images. The views: class AddProductImages(TemplateView): template_name = "addimages.html" def post(self, *args, **kwargs): try: images = self.request.FILES.getlist('images') product = Product.objects.get(id = self.kwargs['pk']) for image in images: product_images = Images.objcts.create( product = product, images = image ) return redirect('index') except Exception as e: print(e) The urls: path('addimages/<int:pk>/', AddProductImages.as_view(), name="addimages"), The templates: <div class="container my-5"> <br /> <h1>ADD IMAGE</h1> <br /> <hr /> <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="images" id="" class="form-control" multiple> <br> <button type="submit" class="btn btn-sm btn-primary my-3">Submit</button> </form> </div> The results: """ The result is so: what's the problem please? ValueError: The view photo.views.AddProductImages didn't return an HttpResponse object. It returned None instead. [31/Aug/2022 22:08:11] "POST /addimages/1/ HTTP/1.1" 500 65400 """ So, could someone check this please? Thanks! -
Does @transaction.atomic follow functon calls
I want to confirm my theory. I was reading the docs, but maybe I am not reading correctly Let's say we have @transaction.atomic def create(...): few queries... func_a() return def func_a(): also running few queries... If queries fail inside func_a will transaction atomic rollback? I am trying to figure out if it wraps the whole execution flow or just the create function in this scenario. Sorry if my question is a bit silly -
How to remove pk in django datalist?
I output datalist, but output pk. I read that it can be removed in data-value like this https://stackoverflow.com/a/48076273/9653855 How can I rewrite the code so that my datalist is displayed in this format <option data-value="1" value="DjangoOneLove"></option>? my forms class ListTextWidget(forms.Select): template_name = 'include/_forms_orders_datalist.html' def format_value(self, value): if value == '' or value is None: return '' if self.is_localized: return formats.localize_input(value) return str(value) class ChoiceTxtField(forms.ModelChoiceField): widget=ListTextWidget() class SimpleOrderAddForm(forms.ModelForm): #service = forms.ModelChoiceField(queryset=Service.objects.all(), widget=ListTextWidget()) service = ChoiceTxtField(queryset=Service.objects.order_by('-used')) class Meta: model = Orders fields = ['service'] my forms_orders_datalist.html <input id="ajax_input_{{ widget.name }}" list="{{ widget.name }}" autocomplete="off" {% if widget.value != None %} name="{{ widget.name }}" value="{{ widget.value|stringformat:'s' }}"{% endif %} {% include "django/forms/widgets/attrs.html" %}> <span class="badge rounded-pill bg-warning text-dark" id="ajax-{{ widget.name }}" name="ajax-{{ widget.name }}"></span> <datalist id="{{ widget.name }}"> {% for group_name, group_choices, group_index in widget.optgroups %} {% if group_name %} <optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %} {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} </optgroup>{% endif %}{% endfor %} </datalist> -
Django, Assign specific fuction tomodel field and then call it
I have a model built like this class ApiPartner(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name=_('Name')) api_key = models.CharField(max_length=50, verbose_name=_('API key'), null=True) secret_key = models.CharField(max_length=50, verbose_name=_('Secret key'), null=True) client_key = models.CharField(max_length=50, verbose_name=_('Client key'), null=True) endpoint = models.CharField(max_length=50, verbose_name=_('Endpoint'), null=True) logo = models.ImageField(upload_to='logos/', null=True) evey API partner has its own method to retrieve data, for example def get_youtube_posts(endpoint,api_key): results=list(requests.get(endpoint+'?key='+api_key).json()) return results[0:50] def get_instagram_posts(endpoint,api_key,secret_key): return requests.get(endpoint+'?key='+api_key+'&secret='+secret_key) the question is: how do i assign the 'get_posts' function to the model so i can call a generic ApiPartner.get_posts() and it will retrieve the posts using the given function? I'm thinking about like a models.FunctionField but i know that doesn't exist. I think this is more a logical problem than a technical one but i can't find a way. Thank you -
How to convert this method in django-rest-framework
I've already done this method in django. But I wanna convert this in django-rest-framework. I'm not how to do this can any one help me regarding this . I want to know how to build the serializers and views for this. At the same time how to send additional data in this itself sorry the code being dirty thank you in advance... models.py class User(AbstractUser): ADDCHKS_ID=models.CharField(max_length=16, blank=True, null=True) is_active=models.BooleanField(default=False,blank=True, null=True) is_excutive=models.BooleanField(default=False,blank=True, null=True) class ExcutiveRegistration(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) '''Personal Details''' First_name = models.CharField(max_length=100,null=True ,blank=True) Last_name = models.CharField(max_length=100,null=True ,blank=True) DOB = models.DateField(max_length=100,null=True ,blank=True) Fathers_name = models.CharField(max_length=100,null=True ,blank=True) Contact_number = models.IntegerField(max_length=10,null=True ,blank=True) Alt_Contact_number = models.IntegerField(max_length=10,null=True ,blank=True) # Profile_picture=models.ImageField(upload_to='images/', null=True, verbose_name="") '''Current Addresss''' Pin_code_c = models.IntegerField(max_length=6,null=True ,blank=True) State_c = models.CharField(max_length=50,null=True ,blank=True) District_c = models.CharField(max_length=50,null=True ,blank=True) Taluk_c = models.CharField(max_length=50,null=True ,blank=True) Location_c = models.CharField(max_length=100,null=True ,blank=True) House_no_c = models.IntegerField(max_length=4,null=True ,blank=True) Street_c = models.CharField(max_length=100,null=True ,blank=True) '''Permanent Address''' Pin_code_p = models.IntegerField(max_length=6, null=True,blank=True) State_p = models.CharField(max_length=50, null=True,blank=True) District_p = models.CharField(max_length=50, null=True,blank=True) Taluk_p = models.CharField(max_length=50, null=True,blank=True) Location_p = models.CharField(max_length=100, null=True,blank=True) House_no_p = models.IntegerField(max_length=4, null=True,blank=True) Street_p = models.CharField(max_length=100, null=True,blank=True) '''Reference''' Family_reference_name = models.CharField(max_length=100, null=True,blank=True) Family_reference_conatact_number = models.IntegerField(max_length=10, null=True,blank=True) Neighbour_reference_name = models.CharField(max_length=100, null=True,blank=True) Neighbour_reference_contact = models.IntegerField(max_length=10, null=True,blank=True) '''Document Proof''' ID_Proof_Document_Type=models.CharField(max_length=50, choices=ID_CHOICES, default="Voter", null=True, blank=True) # ID_Proof_Document= models.ImageField(upload_to='images/', null=True, verbose_name="") '''Bank Details''' # … -
Django - redirect function does not execute
i got this model: class Order(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) made = models.BooleanField(default=False) paid = models.BooleanField(default=False) complete = models.BooleanField(default=False) "Account" is custom user model in utils.py i made this function: from .models import Order def HasActiveOrder(user): try: order = Order.objects.get(user=user) except: return False if order: return True and when I'm using it in views like that: if HasActiveOrder(request.user): print("You have at least one unpaid order") return redirect('cart') I can see "You have at least one unpaid order" in console, but I'm not getting redirected, I do not really understand why cuz if print function is getting executed, redirect should work as well. I can't see any error in console. -
Attendance reports using django
I have a Student class and Attendance class where student var in Attendance is ForeignKey of Student class and Student class contains User as ForeignKey. Now when I take attendance using takeattendance function in views.py the attendance is stored properly in the Attendance class, But I have 3 logins hod, staff and student when staff add the attendance I want that the particular student should get the count of there own attendance in percentage. I am unable to get the logic for it. Please Help me with it Models.py class Student(models.Model): id=models.AutoField(primary_key=True) user=models.OneToOneField(User,on_delete=models.CASCADE) branch=models.ForeignKey(Course,on_delete=models.CASCADE,null=True,blank=True) middle_name=models.CharField(max_length=50,null=True) roll_no=models.IntegerField() mobile_no=PhoneNumberField(default='') parents_mobile_no=PhoneNumberField(default='') year= models.ForeignKey(Year,on_delete=models.CASCADE) division=models.ForeignKey(Division,on_delete=models.CASCADE) batch=models.ForeignKey(Batch,on_delete=models.CASCADE) semester=models.ForeignKey(Semester,on_delete=models.CASCADE, null=True,blank=True) class Attendance(models.Model): id = models.AutoField(primary_key=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) student= models.ForeignKey(Student, on_delete=models.CASCADE) status = models.CharField(max_length=15) views.py def takeattendance(request): if request.method == "POST": subject = Subject.objects.get(id=request.POST['subject']) student_ids = request.POST.getlist('student_name') status_list = request.POST.getlist('status') attendance_objs = [] for sid, status in zip(student_ids, status_list): attendance_objs.append( Attendance( subject=subject, student=Student.objects.get(id=sid), status=status ) ) Attendance.objects.bulk_create( attendance_objs ) if request.user.is_authenticated and request.user.user_type == 2: return render(request,'ms/hod/Attendance.html') elif request.user.is_authenticated and request.user.user_type == 3: return render(request,'ms/staff/Attendance.html') else: return HttpResponse("Failed") else: return HttpResponse("Failed") -
Django Admin shows multiple instances for same primary key
I am struggling with a weird issue in Django (4.0.7) where multiple instances for the same primary key are shown in Django Admin, as well as when executing queries. I have displayed the primary keys to make clear that they are identical: The two classes involved are Collection and Card, where every card has a foreign key to a collection. class Collection(models.Model): FREQUENCY_CHOICES = [('never', 'Never'), ('less', 'Less'), ('normal', 'Normal'), ('more', 'More')] title = models.CharField(max_length=200) author = models.CharField(max_length=200, blank=True, null=True) user = models.ForeignKey(User, related_name='collections', on_delete=models.CASCADE) type = models.CharField(max_length=10, choices=(('books', 'Books'), ('tweets', 'Tweets'), ('articles', 'Articles'), ('podcasts', 'Podcasts'))) custom_id = models.CharField(max_length=200, blank=True, null=True) # e.g. raindropref, amazon book id, etc. url = models.URLField(blank=True, null=True) tags = TaggableManager(blank=True) connection = models.ForeignKey(Connection, related_name='collections', null=True, blank=True, on_delete=models.SET_NULL) frequency = models.CharField(max_length=10, choices=FREQUENCY_CHOICES, default='normal') class Card(models.Model): text = models.TextField() collection = models.ForeignKey(Collection, related_name='cards', on_delete=models.CASCADE, blank=True) custom_id = models.CharField(max_length=200, null=True, blank=True) author = models.CharField(max_length=200, null=True, blank=True) url = models.URLField(blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) favorite = models.BooleanField(default=False) tags = TaggableManager(blank=True) notes = models.TextField(blank=True, null=True) location = models.IntegerField(blank=True, null=True) I cannot fathom where the issue might be. I have already set up the databse from scratch, with no success. Here is an example database query: for c in Collection.objects.all(): print(c.pk, … -
I can't make migration back, after i deleted them in Django
I am using Django with VSC. I got some problem with my database, so i did want to delete inside of migrations but by mistake i deleted directly folder of migrations. Anyway then i used the code; python manage.py makemigrations python manage.py migrate --fake Then i got my migrations informations back. But the problem is, this time it didn't detect my own migrations. So when i click something have connection with database. I got a mistake like "No such table: MyMigrationsName" How can i fix it ? -
DRF pagination with filtering
I have a Django Rest Framework project which is serving up (amongst other things) events. In general, as there could be thousands of events, I prefer to keep the API calls paginated in order to stop the front end API calls from taking too long. I can use this paginated route to produce a table on the front end which will reflect each page in the returned response. Up until now, all good. However, I also want to add a dropdown filter above the table where users can select any of the possible venues that the events are at. But to get an exhaustive list of all the possible venues for the dropdown list, I'll need to go and fetch ALL of the events anyway! Is there another way to do this? Or is a non-paginated events route my only choice? -
RelatedObjectDoesNotExist at /auth/profile/ User has no profile. (user is creating but profile is not)
I had created a custom registration form through which I am creating User and I want to create a profile of the user while creating a User. The code is working if I create a profile manually through admin but not creating while creating user. below is my code. please help me out. Models.py from distutils.command.upload import upload from email.policy import default from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User from PIL import Image # Create your models here. class User(AbstractUser): is_user = models.BooleanField(default=False) is_doctor = models.BooleanField( default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class User_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=100,blank=False) address = models.TextField(max_length=500,blank=False) gender = models.CharField(max_length=7, blank=False) phone = models.CharField(max_length=12,unique=True,blank=False) Username = models.CharField(max_length=100,blank=False,unique=True) Userpassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname class dr_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) image = models.ImageField(upload_to="image") specialisation = models.CharField(max_length=100,blank=False) qualificaton = models.CharField(max_length=100,blank=False) phone = models.CharField(max_length=12,blank=False,unique=True) gender = models.CharField(max_length=7,blank=False) address = models.TextField(max_length=500,blank=False) state = models.CharField(max_length=50,blank=False) city = models.CharField(max_length=50,blank=False) zip = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=50,blank=False) dUsername = models.CharField(max_length=100,blank=False,unique=True) dPassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='#', upload_to='profile_images') bio = models.TextField() def __str__(self): … -
How to display text in html from Django as it is typed in textbox
I want to display the text in HTML from Django in proper format. i.e. Proper space, line break, etc. I used <p>{{blog.main_content}}</p> This is the screenshot of data added The text displaying in webpage Please help me to figure it out. How can I display this text in a proper format? -
Not allowed to load local resource in Django (Images)
I'm trying to load multiple images using Django rest API but getting the error as - Not allowed to load local resource. the setting of app is - STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have checked multiple solution on google but is this due to chrome or Django? Can anyone help here please. NOTE: The call of the API is giving 200 response but only rendering is not happening. Thanks!! -
DRF+Axios: some requests fail with `ERR_NETWORK` or `ERR_BLOCKED_BY_CLIENT`
This is not a question, more like an answer to this common problem. I have a Dashboard built with NextJs and Django+DRF and i am using axios as a HTTP Client. i have noticed that some of my requests go through, and some do not (mainly the requests that fetch for example monthly/yearly payments/expenses of the company). Down below you'll find the solution to this problem. -
Django SetPasswordForm heritage doesn't work
I want to inherit from the built-in Django SetPassWordForm which is class SetPasswordForm(forms.Form): """ A form that lets a user change set their password without entering the old password """ error_messages = { "password_mismatch": _("The two password fields didn’t match."), } new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=_("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}), ) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_new_password2(self): password1 = self.cleaned_data.get("new_password1") password2 = self.cleaned_data.get("new_password2") if password1 and password2: if password1 != password2: raise ValidationError( self.error_messages["password_mismatch"], code="password_mismatch", ) password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user by providing a custom class to the fields: class CustomSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): super(CustomSetPasswordForm, self).__init__(*args, **kwargs) new_password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) new_password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class})) But the template doesnt render it: # user/authentication/password_reset_new.html <div class="password-wrapper field-wrapper mb-4"> <div class="tag pl-1">{{ form.new_password1.label }}*</div> <div class="input text-woys-purple">{{ form.new_password1 }}</div> </div> <div class="password-wrapper field-wrapper mb-4"> <div class="tag pl-1">{{ form.new_password2.label }}*</div> <div class="input text-woys-purple">{{ form.new_password2 }}</div> </div> # urls.py # Set new password path('reset/<uidb64>/<token>/', views.PasswordResetConfirmView.as_view(template_name='user/authentication/password_reset_new.html', form_class=CustomSetPasswordForm), name='password_reset_done'), -
How to send variables from view.py to a signal in Django
i want django to create a ServerModeratorPermission object just after the user has been set as the moderator of the server views.py: class ModeratorSettingsView(LoginRequiredMixin, View): form_class = AddModeratorForm ... def post(self, request, server_tag): form = self.form_class(request.POST) user = User.objects.get(pk=request.POST.get('user')) server = Server.objects.get(tag=server_tag) moderators = server.moderator_of.exclude(user=server.creator) ServerModerator.objects.get_or_create(user=user) moderator = ServerModerator.objects.get(user=user) moderator.server.add(server) return render(request, 'servers/moderator-settings.html', {'moderators':moderators, 'server':server, 'form':form}) signals.py: @receiver(post_save, sender=ServerModerator) def give_default_permission(instance, *args, **kwargs): # i need server_tag for this query # server = Server.objects.get(tag=server_tag) moderator = ServerModerator.objects.get(pk=instance.id) ServerModeratorPermission.objects.create(moderator=moderator, server=server) is there anyway to send server_tag that being used in the view class to the signal? -
Avoid serializer from returning double titles for relation serializer
I have these serializers serializer 2 has a relational field to serializer 1 serializer 1 class ExerciseSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) subject = serializers.SlugRelatedField(read_only=True, slug_field="title") topic = TopicSerializer() class Meta: model = Exercise fields = ["id", "subject", "topic", "questions"] serializer 2 class ExerciseTokenSerializer(serializers.ModelSerializer): exercise = ExerciseSerializer() class Meta: model = ExerciseToken fields = ["exercise", "completed", "score"] this results in a nested "exercise" were I have to access the data by "exercise.exercise", looking at the results below will better explain the issue: { "etoken": 30, "exercise": { "exercise": { ... "completed": false, "score": 0 } } this is how I want it to output { "etoken": 30, "exercise": { ... "completed": false, "score": 0 } } How is this achievable? I couldn't a solution in the docs or here in stack overflow. Thanks. -
Create an API server using Django/FastAPI/Flask and create the following APIs that return this data as JSON in various different ways
https://docs.google.com/document/u/0/d/1BYRJAEI-5aSsQSlHB4BBmvCnKCORPwCGr0ewLvr1f_o/edit?usp=sharing create an API server using Django/FastAPI/Flask and create the following APIs that return this data as JSON in various different ways. All the details of project are given in link. -
Filter model assigned to user , ManyToManyField - Django
new to django and I am finding it hard to know what to search and what questions to ask sooo....here it goes... I have a model named Obiectiv to which I have assigned users in the admin panel using manytomanyfield. models.py: class Obiectiv(models.Model): numeObiectiv = models.CharField(max_length=250) color = models.CharField(max_length=6, choices=COLOR_CHOICES, default='green') user = models.ManyToManyField(User) I want that when the user is logged in, he is able to see only the models that have been assigned to him: views.py @login_required def home(request): obiective = Obiectiv.objects.all() return render(request, 'home.html', context={"obiective":obiective}) With the code in the views.py it display all the Obiectiv models. home.html {% for obiectiv in obiective %} <div class="col-lg-4 col-md-4 col-sm-12 col-xs-12"> <div class="card rounded-0 shadow border-primary text-start summary-card my-3"> <div class="card-body"> <div class="d-flex w-100"> <div class="col-8 pe-2"> <div class="summary-title fs-5 border-bottom">Total Categories</div> <div class="summary-count text-end fw-bolder mt-3 px-4">{{ obiectiv.numeObiectiv|intcomma }}</div> </div> <div class="col-4"> <div class="summary-icon p-3 rounded border text-center bg-gradient bg-light"> <i class="fa fa-list"></i> </div> </div> </div> </div> </div> </div> {% endfor %} thank you in advance.