Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker-Compose container continuosly exits with error code 247
I'm currently trying to create a Django web server using Docker. When I run the Django webserver locally, by using python manage.py runserver 0.0.0.0:8000, everything works fine. This problem occurs when running the server using docker-compose up. The container starts and dis "Watching for file changes with StatReloader" message than hangs up there for a minute or two then exits. I've tried adjusting the amount of RAM and CPU cores available to docker and that hasn't fixed the problem. Any ideas on what could be causing this and how to fix it? -
Error when working with PasswordChangeView
Please help me to solve one problem. I want to change my login, mail and password on one page. I was able to implement a change of login and mail, but I could not push the change of password there, I get an error( __init__() got an unexpected keyword argument 'user' file views.py: from django.contrib.auth.views import PasswordChangeView from .forms import ProfileUpdateForm from django.contrib.auth.forms import PasswordChangeForm class ProfilePage(UpdateView, PasswordChangeView): model=Profile template_name="market/profile.html" second_form_class=ProfileUpdateForm third_form_class=PasswordChangeForm def get_success_url(self): obj=Profile.objects.get(user__username=self.object) return reverse_lazy('profile',kwargs={'slug': obj.slug},) def get_context_data(self, **kwargs): ctx = super(ProfilePage,self).get_context_data(**kwargs) ctx['PasswordChangeForm'] = self.third_form_class( prefix='PasswordChangeForm', # data = self.request.POST if 'PasswordChangeForm-submit' in self.request.POST else None, # files = self.request.FILES if 'PasswordChangeForm-submit' in self.request.POST else None, instance=self.request.user.profile, ) ctx['ProfileUpdateForm'] = self.second_form_class( prefix='ProfileUpdateForm', data = self.request.POST if 'ProfileUpdateForm-submit' in self.request.POST else None, files = self.request.FILES if 'ProfileUpdateForm-submit' in self.request.POST else None, instance=self.request.user, ) return ctx def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs -
How to add column in django user table and access it directly from admin page?
I have seen many answers to this question but none worked out. class userLogin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isManager = models.BooleanField(default=True) I have executed the commands python manage.py migrate and python manage.py makemigrations. The commands were executed successfully. I got an ok and change log in the terminal. If I click on add user on the admin page I can not see the field isManager w.r.t the user. I have triend adding AUTH_USER_MODEL = 'app.userLogin' in settings.py. -
Django: NotImplementedError: aggregate() + distinct(fields) not implemented
I have a table called reviews. In the reviews a person can leave multiple reviews for a service. A review can have a total score. I am trying to get the average of the total scores for the distinct reviews. Here is what I have: reviews = Review.objects.distinct('pairing').aggregate(Avg('total_score')); I keep getting this error: NotImplementedError: aggregate() + distinct(fields) not implemented. Could someone help me? I am fairly new to Django and have no clue why I am getting this. Thanks! -
How to generate UUID paths in views.py in Django?
I would like to create an object in views.py with an ID using UUID and then enter its specific path directly from the views file where I have create it. The error that I get is: TypeError at /item/create_item _reverse_with_prefix() argument after * must be an iterable, not UUID So I wonder whether anyone knows a way how this could be done? models.py: class Item(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=True) views.py def create_item(request): context = {} if request.method == 'POST': name = request.POST['name'] item = Item(name=name) item.save() return HttpResponsePermanentRedirect(reverse('item', args=(item.id))) return render(request, 'items/item.html', context) def item(request, pk): item = get_object_or_404(Item, pk=pk) #Code to be written -
Django modelformset how to redirect if the instances already exist
I am using a modelformset_factory to create multiple instances. Now when the user goes back to the page and the existing instances populate the forms, if the user clicks on submit, the error shows up that the instances already exist triggered by a unique_together constraint. formset_errors [{'__all__': ['course with this instructor, location, program already exists.']}, {'__all__': ['course with this instructor, location, program already exists.']}, {}] I'd like to redirect the user to a listview to display those instances and set a message that we did not create the instances as they already are in the database. How do I do that? Right now, I am using the following which is not the best: redirect_already_exists = True for form_error in formset_errors: # list of dictionaries if form_error.get('__all__'): error_message = form_error['__all__'][0] if 'already exists' not in error_message: redirect_already_exists = False if redirect_already_exists: redirect_page = reverse('course:list_courses', args = (program_id,)) return HttpResponseRedirect(redirect_page) -
Django UnicodeDecodeError While inserting arabic letters
i'm trying to input Arabic letters while using django command python manage.py createsuperuser and it gives me always this error, what should i do to solve this? Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 111, in handle input_value = self.get_input_data(field, message) File "/home/mohammed/PycharmProjects/PatientStatus/venv/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 176, in get_input_data raw_value = input(message) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd8 in position 4: invalid continuation byte -
Enforce that only certain attributes can be changed using a PUT request in Django
I want to make it so a user is able to update only certain attributes with a PUT request in my Django Rest API. As an example, if I had the following model and only wanted the user to be able to update their first and last name, how would I go about doing this? models.py: class User(models.Model): email = models.EmailField('email address', unique = True) first_name = models.TextField(max_length = 10) last_name = models.TextField(max_length = 20) (noting that they should not be able to change the 'id' field either which is automatically set) serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'email', 'first_name', 'last_name'] views.py: class SingleUser(APIView): def put(self, request, user_id): user = User.objects.get(pk = user_id) serializer = UserEditSerializer(user, data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status = status.HTTP_200_OK) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) What is the best way to enforce that users can only change a subset of these attributes? Thanks, Grae -
Error during template rendering / Could not parse some characters
Im trying to get a bio info for each profile, when running server and going to accounts/profile y find this error: Could not parse some characters: |% with website=profile.website| | default:"" % {% extends 'base.html' %} {% block title %}Profile{% endblock %} {% block content %} <h1> {{ user.get_null_name }} (@{{ user.username }}) </h1> {% with profile=user.profile %} {% if profile %} <h2> {{ profile.persona }} </h2> <div> {{ profile.bio|default:"" }} </div> <div> {{ % with website=profile.website | default:"" % }} <a href="{{website}}">{{website}} </a> {% endwith %} </div> <br/> <div> Interest: {% for Interest in profile.interest.all %} <span> {{ interest.name }}{% if not forloop.last %}, {% endif %} </span> {% endfor %} </div> {% endif %} {% endwith %} {% endblock %} -
Invalid block tag on line 1: 'extends"base.html"'. Did you forget to register or load this tag?
I search the solution in internet and I found similar issue but those solution didn't match. {% extends "base.html" %} {% block title %}User Login{% endblock title %} {% block content %} <h1>Login</h1> <form method="post" action="{% url 'Login:user_login' %}"> {% csrf_token %} <label for="username">Username:</label> <input type="text" name="username" placeholder="Enter Username"> <label for="password">Password:</label> <input type="password" name="password"> <input type="submit" name="" value="Login"> </form> {% endblock content %} -
How to upvote or downvote a post on Django [closed]
I have a blog system, very simple one. I want users to be able to upvote and downvote posts. How to do it ? Like the youtube system, click on "like" or "dislike" Thank you -
Issue with vine.five in Django
I'm running on Ubuntu a Django project that started running on Windows. I've installed a venv with python3.6 and with the same requirements with pip. Installed the vine 1.3 version as many posts told to do. No broken requirements found. Same error: ModuleNotFoundError: No module named 'vine.five' Tried other python versions too. This is the exception: SyntaxError: invalid syntax (venv3.6.0) (venv3.6.0)codea@codea-Inspiron-5570:~/Workspace$ sudo python3 manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 361, in execute self.check() File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/usr/local/lib/python3.6/dist-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.6/dist-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py", line 213, in __iter__ return iter(self.databases) File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/dist-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/dist-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, … -
Django Combining Multiple Filters for ManytoMany Choice
I'm trying to filter a ManyToMany field in a form on Django so that it only includes choices for the current user logged in users associated to the logged in user (parent and children) forms.py class LessonsForm(forms.ModelForm): class Meta: model = models.Lessons fields = ['type_of_lesson','attendees','max_capacity','teacher','date_of_lesson','time_of_lesson'] class LessonAddForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(LessonAddForm, self).__init__(*args, **kwargs) self.fields['attendees'].queryset = CustomUser.objects.filter(username=user) class Meta: model = models.Lessons fields = ['attendees'] Models.py class CustomUser(AbstractUser): date_of_birth = models.DateField() is_parent = models.BooleanField(verbose_name="Parent") children = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) REQUIRED_FIELDS = ['date_of_birth', 'is_parent','email',] class Lessons(models.Model): type_of_lesson = models.CharField("Lesson Type", max_length=128) attendees = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="attendee_users") max_capacity = models.IntegerField() teacher = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="teaching_user",limit_choices_to={'is_staff': True}) date_of_lesson = models.DateField() time_of_lesson = models.TimeField() date_added = models.DateField(auto_now_add = True) the line below is where I am struggling, this brings back the current user but I am also trying to have the 'children' connect to the user also appear in the attendees choices. self.fields['attendees'].queryset = CustomUser.objects.filter(username=user) I have tried a few methods below is an example but I can't seem to figure how how to combine two filters self.fields['attendees'].queryset = CustomUser.objects.filter(username=user,user.children) -
How to make humanize work with crispy forms?
I am trying to humanize some datetimes and I can't seem to get humanize to work with crispy forms. I have done {% load humanize %} at the top of the template Example from template <div class="form-row"> <div class="form-group col-md-6 mb-0"> {{ form.start_date|as_crispy_field | naturalday }} </div> <div class="form-group col-md-6 mb-0"> {{ form.finish_date|as_crispy_field | naturalday }} </div> </div> The datetimes currently just display like this 2018-05-11 00:00:00 which is ugly. Anyone have any ideas on this one? -
Tailwind broke Vue templates (cdn)
I'm building a web app with Django and wanted to utilize Tailwind (https://tailwindcss.com/docs/installation) I followed the instructions to set up tailwind and its working fine. However, all of a sudden, my Vue templates are not being rendered properly. In my template, all I see is [[data]]instead of the actual variables? My Vue tag looks like this: (I'm using Vue through a CDN, not the CLI) var app = new Vue({ delimiters: ['[[', ']]'], el: '#app', data: { text: "something" } }) In my django template, I tried: [[text]] {% verbatim %} {{text}} {% endverbatim %} without success. All I see in the template, no matter what is just [[text]] Interestingly enough - the functions themselves work fine. E.g mounted() { console.log("test") } actually prints the message to the console, so nothing wrong with the Vue setup I guess -
Complex Django ORM Annotations & Aggregations
I'm currently preparing some logged items into a JSON serialized format. I am attempting to do this via Django's built-in ORM, utilising annotations and aggregations. I'm trying to replicate the following structure per each of these "logged items": ... { "count": 20, "metric-type": "total-dataset-requests", "access-method": "regular", "country-counts": { "au": 6, "jp": 1, "us": 13 } } ... I've currently built this queryset from my own knowledge: metrics = LoggedItem.objects.filter( identifier=record['identifier'], hit_type='investigations', is_machine=False, is_robot=False ).values( 'identifier', 'country' ).annotate( count=models.Count('identifier'), metric_type=models.Value("total-dataset-requests", output_field=models.CharField()), access_method=models.Value("regular", output_field=models.CharField()) ) This gives me a <Queryset []> as follows: <QuerySet [{'identifier': '10.80519/954e-4db4', 'country': 'fr', 'count': 1, 'metric_type': 'total-dataset-requests', 'access_method': 'regular'}, {'identifier': '10.80519/954e-4db4', 'country': 'gb', 'count': 5, 'metric_type': 'total-dataset-requests', 'access_method': 'regular'}]> As you can see, I have all of the data I need for mimicking the above data stucture. But in a sightly obscure format ... I can go in a clean this up with Python, from a values_list() or iterator(), but I'd like to do most of the heavy lifting on the database layer via the ORM. So I guess my question is, how could I replicate the kid of aggregation as shown in the JSON structure as an ORM query...? FYI: It would likely be useful to … -
Get user identity values - Django Saml2 Auth
I have implemented Django Saml2 Auth in my application, It's working very well. I want to get the user information from azure. While debugging I am able to see the user_identity, Now I need to get the user_identity which is available in the library here I don't know how to read the value from my application. -
How to access data from database using Javascript and django
Below is my code with database. Where I am trying to access the zip code data using JavaScript and Django. In this case when user enters a zip code then state field should autofill using this database according to entered zip code. So I am trying alot to achieve this But not able to get exact solution. So in this situation if any one have an idea please help me trying a lot to achieve this. Thanks in advance This is my database INSERT INTO pages_zip_code (id, zip, city, st) VALUES (1, '00501', 'Holtsville', 'NY'), (2, '00544', 'Holtsville', 'NY'), (3, '00601', 'Adjuntas', 'PR'), (4, '00602', 'Aguada', 'PR'), (5, '00603', 'Aguadilla', 'PR'), (6, '00604', 'Aguadilla', 'PR'), (7, '00605', 'Aguadilla', 'PR'), (8, '00606', 'Maricao', 'PR'), (9, '00610', 'Anasco', 'PR'), (10, '00611', 'Angeles', 'PR'), (11, '00612', 'Arecibo', 'PR'), (12, '00613', 'Arecibo', 'PR'), (13, '00614', 'Arecibo', 'PR'), (14, '00616', 'Bajadero', 'PR'), (15, '00617', 'Barceloneta', 'PR'), (16, '00622', 'Boqueron', 'PR'), (17, '00623', 'Cabo Rojo', 'PR'), (18, '00624', 'Penuelas', 'PR'), (19, '00627', 'Camuy', 'PR'), (20, '00631', 'Castaner', 'PR'), (21, '00636', 'Rosario', 'PR'), (22, '00637', 'Sabana Grande', 'PR'), *javascript* function is_int(value) { if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) { return true; } else { return false; } … -
while fetching the data for JWT authorization shows bad request, why?
i am new to Reactjs and DRF both. recently i want to make JWT authenticatoion with DRF and Reactjs. in reactjs part i am using React Hooks Function. In Django Rest Framework i have implemented Login, signup, and current user part with JWT authentication system. and in api side, it is working fine while i am registering a new ID or login. here is the full code of Django Rest Framework then i have installed pip install django-cors-headers and i put the following to avoid cors error: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'https://localhost:3000', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ] then i wrote the react side in another myapp folder and here is the whole code while running npm start no error has been shown. but when i try to signup for a new id, in development tools it is showing the error: POST http://localhost:8000/core/users/ 400 (Bad Request) when i try to login, it is showing the kind of same error: Unhandled Rejection (TypeError): Cannot read property 'username' of undefined and here are the details in development console: Userbar.js:13 GET http://localhost:8000/core/current_user/ 401 (Unauthorized) (anonymous) @ Userbar.js:13 commitHookEffectListMount @ react-dom.development.js:19731 commitPassiveHookEffects @ react-dom.development.js:19769 callCallback @ react-dom.development.js:188 invokeGuardedCallbackDev @ … -
Python Django.Как вывести переменную в html? [closed]
i have a problem with a variable: js: <script> var interval function callAjax(){ $.ajax({ type: "GET", url: "../row_han_two", data: { 'id_group': $("#id_group").val(), }, cache : false, success: function(data){ rot_message = data interval = setTimeout(callAjax, 1000); } }); } callAjax() </script> views: from django.shortcuts import render from django.contrib.auth.models import User,Group from django.contrib.auth import models from create_group_handler.models import Parameters_User from django.contrib.auth.decorators import login_required from create_group_handler.models import UserProfile from django.http import HttpResponse, HttpResponseRedirect from rot.models import Rot_model from django.http import JsonResponse import time @login_required def row_han_two(request): rot_message = Rot_model.objects.filter(id_chat = request.GET['id_group']) return HttpResponse(rot_message) Please tell me how you can display the chat_message variable in html,in this way: {% for object in rot_message%} <div class="row"> <div class="col-xl-3 block_messeage"> <span class="span_block_messeage">{{object.name_author}} ,{{object.time_message}}</span> <br> {{object.text_message }} </div> </div> {% endfor %} Lorem, ipsum dolor sit amet, conctetur adipisicing elit. Амет, веритатис. Eveniet culpa eaque quisquam ducimus ut ratione quae ex reiciendis, rerum vel, -
Understanding Gunicorn worker processes, when using threading module for sending mail
in my setup I am using Gunicorn for my deployment on a single CPU machine, with three worker process. I have came to ask this question from this answer: https://stackoverflow.com/a/53327191/10268003 . I have experienced that it is taking upto one and a half second to send mail, so I was trying to send email asynchronously. I am trying to understand what will happen to the worker process started by Gunicorn, which will be starting a new thread to send the mail, will the Process gets blocked until the mail sending thread finishes. In that case I beleive my application's throughput will decrease. I did not want to use celery because it seems to be overkill for setting up celery for just sending emails. I am currently running two containers on the same machine with three gunicorn workers each in development machine. -
Reverse for 'password-change' not found. 'password-change' is not a valid view function or pattern name
Please help me to solve one problem. I want to change my login, mail and password on one page. I was able to implement a change of login and mail, but I could not push the change of password there, I get an error ( from django.contrib.auth.views import PasswordChangeView class ProfilePage(UpdateView, PasswordChangeView): model=Profile template_name="market/profile.html" form_class=UserUpdateForm def get_success_url(self): obj=Profile.objects.get(user__username=self.object) return reverse_lazy('profile',kwargs={'slug': obj.slug},) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) return kwargs -
How to grant permissions in docker to pip installations?
Hey guys i have recently just been trying to dockerize my existing django project. Im facing a problem of permissions. Here is my docker file # Pull base image FROM python:3.8-alpine # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH="/scripts:${PATH}" RUN apk update #Installing dependencies, remove those that are not needed after the installation COPY ./requirements.txt /requirements.txt RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc postgresql-dev libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev gcc musl-dev && \ apk add jpeg-dev zlib-dev libjpeg &&\ pip install -r requirements.txt &&\ apk del .build-deps #Copy our backend folder and place it inside the image COPY ./backend ./backend WORKDIR /backend COPY ./scripts ./scripts #Create media and static directories RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ #Create less privilledged user, give it access to the folders RUN adduser -D user RUN chown -R user:user /backend RUN chown -R user:user /vol RUN chmod -R 755 /vol/web #change to the less privillege user USER user CMD ["entrypoint.sh"] The problem when Im trying to run migrations using docker-compose run backend python backend/manage.py makemigrations Is that i'll be faced with a permission error of: PermissionError: [Errno 13] Permission … -
Django: overlapping label and radio button options
I am using django crispy_forms.helper and crispy_forms.layout to create radio button with options. The label and radio button options are overlapping. The code which i am using is : forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, HTML, Layout, Row, Div, Fieldset,ButtonHolder,Column from crispy_forms.bootstrap import InlineRadios, PrependedAppendedText, Div ROUTER_OPTIONS = ( ('', 'Choose router...'), ('FIP', 'First IP in range'), ('AM', 'Add Manually') ) class DhcpForm(forms.ModelForm): router = forms.ChoiceField(label='Router', choices=ROUTER_OPTIONS, initial='', widget=forms.RadioSelect) def __init__(self, *args, **kwargs): super(DhcpForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Row( Column('dhcp_member', css_class='form-group col-md-6 mb-0'), Column('router', css_class='form-group col-md-6 mb-0'), css_class='form-row' ) html {% block content %} {% crispy form %} {% endblock %} The view which i am getting: overlapped view -
Profile "relation username slug" alternative
I'm using a profile system as each user can see. I'm looking for an alternative. Because if a user register from FB or Google he always has "." in username. So if I want to reach his profile with slug I got a 404 error. Because username != slug. Do you have any idea? In my UserProfile I got unique slug for each user. def userpublicpostview(request, slug): userid = get_object_or_404(User.objects.select_related('userprofile'), username=slug) posts = Post.objects.filter(author_id=userid.id) comments = Comment.objects.filter(user_id=userid.id) pictures = Picture.objects.filter(user_id=userid.id) story = Story.objects.order_by('-created_on').all() return render(request, 'user_public_profile.html', { 'user_posts': posts, 'current_user': userid, 'user_comments': comments, 'user_pictures': pictures, 'story': story, })