Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'AnonymousUser' object has no attribute 'user_type'
I am trying to display data on my base.html file so I decided to use context processor to achieve that below is my code def meeting_notifications(request): if request.user.user_type == 'CDA Admin': n = Meetings.objects.filter(meeting_class='CDA Admin') context = {'notifications':n} return context elif request.user.user_type == 'CDA Member': n = Meetings.objects.filter(meeting_class='CDA Member') context = {'notifications':n} return context But below is the error I get 'AnonymousUser' object has no attribute 'user_type' When I added @login_required and check if the user is authenticated as seen in the code below @login_required(login_url='/backoffice/') def meeting_notifications(request): if request.user.is_authenticated: if request.user.user_type == 'CDA Admin': n = Meetings.objects.filter(meeting_class='CDA Admin') context = {'notifications':n} return context elif request.user.user_type == 'CDA Member': n = Meetings.objects.filter(meeting_class='CDA Member') context = {'notifications':n} return context I now have a new error when I tried to load my page. I will appreciate it if I get help from someone. dictionary update sequence element #0 has length 0; 2 is required -
How can I fix this paginator problem in python
in my views I defined the paginator function to show only 2 posts per page, but the thing is that every time I add a new post the pagination in the bottom changes, but it still shows all the posts instead of two, I'm going to share my code so you can check if I'm doing any mistakes. views.py def StockView(request, sym, ): stock_posts = Post.objects.filter(stock__symbol=sym) stock_sym = get_object_or_404(StockNames,symbol = sym) post_list = Post.objects.filter(stock__symbol=sym) paginator = Paginator(post_list, 2) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'app1/stockview.html', {'page':page,'posts':posts,'stocks':stock_posts, 'stock_sym':stock_sym, 'sym':sym }) models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) urls.py app_name = 'app1' urlpatterns = [ path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'), path('stock/<str:sym>/', views.StockView, … -
Django Rest Framework - customize default list view to show unique values for ManyToMany fields
My models are bound with multiple fields using ManyToMany and "through" property something like this: class KLA(): version = ForeignKey("Version", on_delete=CASCADE) stages = ManyToManyField('Stage',through='KlasOutcomes', blank=True) objectives = ManyToManyField('Objective', through='KlasOutcomes', blank=True) outcomes = ManyToManyField('Outcome', through='KlasOutcomes', blank=True) class KlaSerializer(SerializerCacheMixin, ModelSerializer): version = VersionSerializer(many=False, read_only=True) class Meta: model = KLA list_serializer_class = CachedListSerializer fields = ('outcomes', 'version', 'stages') I am trying to return unique values for a specific field that is otherwise repeated due to combination of other fields in the table like this: In other word, "stages" should have only one entry 23 in the list. I tried using following to return unique stages for my model: @property def stages(self): return self.stage_set.all() But it doesn't help, gives following error: -
Django CMS, there is a piece of HTML in the include, how to include this piece twice on one page and so that you can change different content?
There is a template in the include / skver_cards folder {% load cms_tags %} {% load static %} <div class="cards"> <div class="card__item"> <div class="card__top"> {% placeholder 'card__top_c1' %} </div> <div class="card__foot"> {% placeholder 'card__foot_c1' %} </div> </div> ......... </div> I connect this piece on one page twice, is it possible somehow that one include had one content, and the other has another ???? it just turns out if I change something in the first, then it changes in the second, what can be done ??? {% include './include/cards.html' %} <br><br> {% include './include/cards.html' %} -
XMLHttpRequest - url not found
I am making a quiz app, and I want each answer to be submitted without a page refresh. So for this I am using the following script: window.onload = initial; var saveAnsButton; function initial(){ saveAnsButton = document.getElementsByClassName("save_ans")[0] saveAnsButton.onclick = saveans; } function saveans(){ var ans = $("input:radio[name=choice]:checked").val() alert("Answer: "+ans+" submitted"); var req = new XMLHttpRequest(); var url = '/save_ans?ans='+ans req.open("GET", url, true); req.send(); } The relevant parts of my html: {% for q in question_list %} {{q}} <br> {% for choice in q.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.answer }}"> <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br> {% endfor %} {% endfor %} {% if page_obj.has_next %} <a class='btn btn-warning save_ans' href="?{% param_replace page=page_obj.next_page_number %}">Save answer</a> {% else %} <a class='btn btn-warning save_ans' href="#">Save answer</a> <br> <br> <a class='btn btn-success submit_ans' href="{% url 'quizzes:song_results' 1 %}">Submit Answers</a> {% endif %} <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> This works to the extent that I get the alert and the selected answer. However, I get the following error in the console: Cannot set property 'onclick' of undefined at initial And I also get the following in the console: Not Found: /save_ans I've tried all … -
can't authenticate user in django
I create authentication link to email the user and this is the error I get: Reverse for 'activate' with keyword arguments '{'uidb64': 'MzA', 'token': 'a8o36j-51326a9d14c0ebf00a88a9a8c4983014'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] urls.py: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), line from views.py: message = render_to_string('main/acc_active_email.html' activate function in views.py: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') acc_active_email.html: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'main:activate' uidb64=uid token=token %} {% endautoescape %} Now it may be because I copied it from an article that refrences an older version of django. any help is apperciated! -
I am trying to create a model and try to migrate it but facing error such as :AttributeError: module 'django.db.models' has no attribute 'models'
from django.db import models # Create your models here. class Topic(models.Model): top_name = models.models.CharField(max_length=50,unique = True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=256,unique = True) url =models.URLField(unique =True) def __str__(self): return self.name Well i am using django version 3.0.3 and python 3.8.5 and using vs code and i have made environment in anaconda.. Well I am trying to make model and than migrate it but when i try to migrate my models by writing command python manage.py migrate Then compiler show error AttributeError: module 'django.db.models' has no attribute 'models' . -
Django - Create forms with loops
I have a model called comments and I am displaying them using a for loop in the template. I want the users to be able to edit these forms without having to go into a different page but I'm not sure how I will go about creating these forms in a loop and more importantly how to handle the post requests. Thanks in advance. -
How to do a nested loop in Django
I'm trying to loop through my choicefield form and surround every 4 in a <div> </div> so that there are only 4 of the choices per line. The problem is I can't seem to figure out nested loops in django. The documentation on parent-loops is almost nothing and I've also tried creating a template tag counter to no avail. Here's what I'm working with: {{ counter.count }} {% for check in form.pt_medical_condition %} {% if counter.count == 4 %} <div> {% endif %} <label> {{ check.tag }} {{ check.choice_label }} </label> {% if counter.count == 4 %} </div> {% endif %} {% if counter.count == 4 %} {{ counter.count = 0 }} {% endif %} {{ counter.increment }} {% endfor %} Is there a simpler way to do this without template tags seeing as mine don't work anyway? Thanks! -
Django pagination shows the same page twice if the database updates in the background
I am working on a webpage that get images of cars from various sources and stores them in SQLite database and then I display them in an infinite scrolling webpage. Lets say a user goes to my site and the first page gets loaded, then they scroll to the bottom and the javascript then gets the second page. And while scrolling through the second page the database is updated in the background to add more images to the database using code running on the server. If at that moment of the database update, the user scrolls to page three, for some reason page one from before shows up and the user has to scroll through page one, and then two and then to page three. How do I keep track of what images were in the last page and then show them only the images that come after that based on by specified order_by filter in the view function. **Views.py file is given below:** def car (request): category = 'CARS' files_list = Car.objects.all().order_by('-upload_date', '-id') paginator = Paginator(files_list, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'memes/car.html', {'page_obj':page_obj, 'category':category}) **The template file is given below:** {% block content %} <div … -
Django model analytic feature
I am using Django on my website and I have a bunch of moving parts. One of the apps in question is a user flow where they are sent a email and navigate through a set of "steps" on my site. I would like to keep track of all my analytic data such as: When they first clicked on email How long they spent on each page How long it took to complete How many completed How many didn't start Longest page users spend time on etc I can gather all this data easily and store it in a model, but I have no good way of displaying and comparing it over time. I am interested in Django has anything that would work for this? -
variable min_value in a decimal field form
I am trying to set the min_value of a field's form variable. class BidForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bid'] = forms.DecimalField(min_value=50, error_messages={'min_value': 'Price must be greater than the current price'}) self.fields['bid'].widget.attrs.update({'placeholder': 'Place your bid here', 'step': 1}) I have harcoded the 50 value in this case, but what I need is to set it according to the current bid. This is the Bid model: class Bid(models.Model): bid = models.DecimalField(max_digits=5, decimal_places=2) user = models.ForeignKey(User, related_name="bid", on_delete=models.CASCADE) auction = models.ForeignKey(Auction, related_name="bid", on_delete=models.CASCADE) def __str__(self): return f'Bid for ${self.bid} on {self.auction} by {self.user}' This is the view: def detail(request, auction): auction = get_object_or_404(Auction, slug=auction) comments = auction.comments.all() current_bid = auction.bid.last() comment_message = None bid_message = None new_comment = None new_bid = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) bid_form = BidForm(data=request.POST) if request.POST.get("form_type") == 'form_comment': bid_form = BidForm() if not request.user.is_authenticated: comment_message = "You have to sign in to post a comment" else: if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.auction = auction new_comment.user = request.user new_comment.save() return redirect('detail', auction.slug) elif request.POST.get("form_type") == 'form_bid': comment_form = CommentForm() if not request.user.is_authenticated: bid_message = "You have to sign in to place a bid" else: if bid_form.is_valid(): new_bid = bid_form.save(commit=False) new_bid.auction = auction new_bid.user = … -
How to populate data from select dropdown so that data of particular id will be displayed to the main page
I have created a dropdown selector and want data to be fetched from the database according to that.For example I have two models Cuisine and Dish.I have taken all the cuisines in my dropdown selector (eg Indian,British,Frech etc) and want to fetch all the dishes from the database the database accourding to it. For example,when I select Indian then all the dished that are associated to it should be fetched so that I can display it to home page. model.py class Cuisine(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ['-id'] def __str__(self): return self.name class Dish(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to='dishes_pics') description = models.TextField() required_time_to_cook = models.CharField(max_length=100) cuisine = models.ForeignKey(Cuisine, on_delete=models.CASCADE) class Meta: ordering = ['-id'] def __str__(self): return self.name views.py from django.shortcuts import render from django.http import HttpResponse from .models import Cuisine,Dish def select_cuisine(request): dish_id = Dish.objects.get(pk = 1) cuisine_id = Cuisine.objects.filter(cuisine=cuisine_id) return render(request, 'cookbook/base.html', {'cuisine_type' : cuisine_id}) def home(request): context = { 'dishes' : Dish.objects.all() } return render(request, 'cookbook/home.html',context) index.html Select Cuisine {% for type in cuisine_type %} {{ type.name }} {% endfor %} </div> </li> -
Relating two models with same field value?
I'm new to Django, so I apologize a head of time if my verbiage is off. But I'll try my best! I have two models : PlayerProfile - this is updated once a day. PlayerListing - this is updated every 5 minutes. Here are simplified versions of those models. class PlayerProfile(models.Model): listings_id = models.CharField(max_length=120) card_id = models.CharField(max_length=120) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) overall = models.IntegerField() class PlayerListing(models.Model): listings_id = models.CharField(max_length=120, unique=True) buy = models.IntegerField() sell = models.IntegerField() Currently, we just make queries based on the matching listings_id - but I'd like to have a more traditional relationship setup if possible. How do you relate two models that have the same value for a specific field (in this case, the listings_id)? Some potentially relevant information: Data for both models is brought in from an external API, processed and then saved to the database. Each PlayerListing relates to a single PlayerProfile. But not every PlayerProfile will have a PlayerListing. When we create PlayerListings (every 5 minutes), we don't necessarily have access to the correct PlayerProfile model. listings_id's are generated last (as we have to do some extra logic to make sure they're correct). -
Static files: Images are being loaded but not CSS and JS files | Django
I'm trying to load CSS and JS files in my Django templates but it's not working. I could load images succesfully. My settings: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( STATIC_DIR, ) My urls.py: urlpatterns = [ . . . ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + \ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My template: {% extends 'base.html' %} {% load static %} {% block content %} <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <link href="{% static 'card-js.min.css' %}" rel="stylesheet" type="text/css" /> <script src="{% static 'card-js.min.js' %}" type="text/javascript"></script> <img src="{% static 'bag1.png' %}" width="25px"> My file structure: dma - account - cart - dma - home - media - payment - static - - bag1.png - - card-js.min.css - - card-js.min.js The image 'bag1.png' is loaded correctly but not the 'css' and 'js' files. Any help? Thank you! -
Deploying django docker container to elastic beanstalk
I have a django rest framework app configured with nginx + gunicorn. I can run the containers locally using docker-compose up -d --build just fine, but I wish to deploy the docker image to AWS elastic beanstalk. For debugging purposes, I am trying eb local run, butI seem to be getting this error: latest: Pulling from <user>/<repo> Digest: sha256:15cec14272aca0b787c4209e3196b2e61d50732f6f4616f2cf50baa28b82c65c Status: Image is up to date for <user>/<repo>:latest docker.io/<user>/<repo>:latest Sending build context to Docker daemon 316.7MB Step 1/2 : FROM <user>/<repo>:latest ---> eex74e02e4e5 Step 2/2 : EXPOSE 8000 ---> Using cache ---> 094f132e13a7 Successfully built 094f132e13a7 SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories. docker: invalid reference format. See 'docker run --help'. ERROR: CommandError - None Here is my Dockerrun.aws.json: { "AWSEBDockerrunVersion": "1", "Image": { "Name": "j0hnk1m/refridge:latest", "Update": "true" }, "Ports": [ { "ContainerPort": "8000" } ] } Why am I getting th -
Django: How to create enum of classes to define choices
How to subclass models.Choices to define enum of classes? The following code raises TypeError: from django.db.models import Choices class DataTypes(type, Choices): CHAR = str, _('Short string') INTEGER = int, _('Integer') The error message: dynamic_attributes = {k for c in enum_class.mro() TypeError: descriptor 'mro' of 'type' object needs an argument -
django form doesn't go inside post
I am just trying to be able to read the values entered by the user on the form in the server. I have noticed that it never goes inside this part of the view function if request.method == 'POST': Please let me know if I missed anything. I have included my code snippets for views, urls, form, html files: urls.py=> urlpatterns = [ path('create',views.create), path('create/',views.create), path('download', views.download), ] checklistform.py=> class ContactForm(forms.Form): name = forms.CharField() create.html=> <!DOCTYPE html> <html lang="en> <head> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="OK"> </form> </body> </html> views.py => from django.shortcuts import render, HttpResponseRedirect, HttpResponse, redirect from .checklistform import ContactForm def create(request): print("letssee") print(request.method) if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] print(name) form=ContactForm() return render(request, 'create.html', {'form': form}) Output seen in pycharm => (as we can see it never goes inside the if) [15/Aug/2020 23:47:03] "GET / HTTP/1.1" 404 2038 letssee GET [15/Aug/2020 23:47:08] "GET /imschecklist/create HTTP/1.1" 200 364 Thanks, Nick -
Can django do computations in the client?
I am about to design an app that requires to do some medium level of computation (training some small machine learning model). I am thinking about designing the app with django. Was wondering if django can allow that some of these computations can be done in the client‘s browser, i.e. using its memory and cpu. Some initial tips of where to start looking at will be much appreciated. Thanks -
Changing value in Django changes form field in static value
I'm quite new to Django so there might be a simple solution. I try to load a value from Excel and add it as a default/initial value of a form. However, the formfield changes to a static value (can't be changed anymore). See 3 images below. Could you help me get the value from Excel (value in first row and first column) as an initial value in a form which can still be changed? Initial screen: Initial Result after Excel import: After import Preferred result after Excel import: Preferred The code: views.py from django.shortcuts import render from django.template import RequestContext from django.http import HttpResponse from .models import InputForm from .models import InputForm1 from .compute import compute from django.db import models import os import xlsxwriter import io def index(request): os.chdir(os.path.dirname(__file__)) result = None if request.method == 'POST' and 'calculate' in request.POST: form = InputForm(request.POST) form1 = InputForm1() if form.is_valid(): form2 = form.save(commit=False) result = compute(form2.A, form2.B, form2.C) elif request.method == 'POST' and 'calculate1' in request.POST: print(1) form1 = InputForm1() form = InputForm(request.POST) if form.is_valid(): form2 = form.save(commit=False) result = compute(form2.A, form2.B, form2.C) print(2) # create our spreadsheet. I will create it in memory with a StringIO output = io.BytesIO() workbook = … -
Get "raw" string to handle function [duplicate]
I have problem with handling GET responses form HTML. I'm getting selected parameter to handle with: atribute = request.GET.get('parameters') and I want to use this atribute to access specific values from my database and add it to array by: for i in things: my_data.append(i.atribute) But of course this can't work because atribute is a string value, so reference through string will not work. How to manage with such problem? -
django class based CreateApiView author_id is not null?
I have also authenticate it with token but when I create a new post error is alert IntegrityError at /api/create/ NOT NULL constraint failed: core_article.author_id how can I valid data with request user in serializer? model.py from django.contrib.auth.models import User from django.db import models class Article(models.Model): title = models.CharField(max_length=255, help_text="Short title") content = models.TextField(blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=True) def __str__(self): return self.title serializer.py from rest_framework import serializers from django.contrib.auth.models import User from core.models import Article class NewsSerializer(serializers.ModelSerializer): author = serializers.SlugRelatedField( slug_field=User.USERNAME_FIELD, read_only=True, required=False) class Meta: model = Article fields = [ 'id', 'author', 'title', 'content', 'status', ] views.py class ArticleCreate(CreateAPIView): queryset = Article.status_objects.all() serializer_class = NewsSerializer permission_classes = (permissions.IsAuthenticated, ) -
How to Dockerize a Django + Postgres App with Apache (Instead of NGINX) for production
I'm new to the DevOps world and I have been following this tutorial successfully, my Docker setup is almost identical to the one on the tutorial. I now would like to setup a Docker container with Django and Postgres but with Apache instead of NGINX for production. What commands should I add/modify to the Dockerfile, volumes and configurations to the docker-compose file and what configuration files should I have for the Apache configuration? -
How to authenticate users with HttpOnly Cookie Django-React
I'm trying to understand authentication system for my web app but I'm going nuts. At this point I literally have no idea what I am doing, Anyway I'm developing a Django-React Web App and using JWT tokens for authentication. For security measures I decided not to store JWT tokens in client, this is where my confusion gets start. So I make an axios POST request to login from React => //LOGIN USER export const login = (username, password) => dispatch => { //Headers const config = { headers: { "Content-type": "application/json" } } //Request body const body = JSON.stringify({ username, password }) axios.post("http://localhost:8000/auth/login/", body, config, {withCredentials: true}) .then(res => { dispatch({ type: LOGIN_SUCCESS, payload: res.data }) }).catch(err => { console.log(err) dispatch({ type: LOGIN_FAIL }) }) } and server responses with some cookies => and JSON response => then I want to use the access_token for authentication but since it is HttpOnly I can't access the token from client. Anyway, with some research I found out that I can send csrf-token to authenticate(I could be wrong about that), so I made a request to protected endpoint => import axios from 'axios' axios.defaults.xsrfCookieName = "csrftoken" axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" //ADD POST export const … -
How to get the object of a specific user and make a check?
I need to check for a specific user for the presence of the same link that I just entered from the form. I enter two links in the field, the user is filled in automatically. I want to check if the user has the same link, but I don’t know how to get all the user objects. models.py: class LinksModel(models.Model): user=models.ForeignKey(User,verbose_name="user", on_delete=models.CASCADE) full_link=models.CharField(verbose_name="full_link",max_length=250) short_link=models.CharField(verbose_name="short_link",max_length=250) def __str__(self): return f"{self.short_link}" forms.py: class LinksForm(forms.ModelForm): def __init__(self, *args, **kwards): super(LinksForm, self).__init__(*args, **kwards) self.fields['full_link'].widget = forms.TextInput(attrs={'placeholder': 'full_link'}) self.fields['short_link'].widget = forms.TextInput(attrs={'placeholder': 'short_link'}) class Meta: model=LinksModel fields=["full_link","short_link"] def clean_short_link(self): short_link_list=LinksModel.objects.filter(user=self.) short_link=self.cleaned_data['short_link'] if short_link in short_link_list: raise ValidationError ("error") return short_link here views.py: class LinksPage(LoginRequiredMixin,CreateView): model=LinksModel template_name="News/links.html" form_class=LinksForm success_url= reverse_lazy("links") def form_valid(self,form): form.instance.user=self.request.user return super().form_valid(form) def get_context_data(self, **kwards): ctx = super(LinksPage, self).get_context_data(**kwards) ctx['links']=LinksModel.objects.filter(user=self.request.user) return ctx