Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I check if a record saved successfully in Django?
Could you take a look at this code below? It seems like the form is submitted and validated successfully. However, it doesn't seem to be saving to my database. Please check my comment in the post() method below starting with #####. I know in PHP one can print_r($var); exit; but can't seem to find equivalent in Python/Django. class ReportListView(ListView): model = ReportList form_class = ReportListForm initial = {} context_object_name = 'reportlists' template_name = "reports.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #context['now'] = timezone.now() return context def get_queryset(self): return ReportList.objects.filter(user=self.request.user) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # process form cleaned data # name = form.cleaned_data.get('name') # .lower() new_report = form.save(commit=False) new_report.user = self.request.user new_report.save() ### what can I write to check if new report has been saved? ### also, how can I print something here to print that in the browser e.g. ### print(datavariable) ### exit() ?? or something to stop execution here so that I read previous print output return redirect('report') return render(request, self.template_name, {'form': form}) -
Queryset to filter exactly N objects from a table
I am trying to work out how to allocate exactly N available objects, in a way which is safe against concurrent activity. Is there a way to write a queryset that will fail if it cannot return at least N objects? This is probably an excess of caution for my particular application because the chances of a race are infinitesimal, but I'm curious What I know won't work is available = Foo.objects.filter( status=Foo.AVAILABLE).count() if available < N: #let the user know there aren't enough left # but now something concurrent may grab them! foo_qs = Foo.objects.select_for_update().filter(status=Foo.AVAILABLE)[:N] with transaction.atomic(): for foo in foo_qs: ... # quite a bit. In RL I will have locked related objects as well. foo.status=Foo.RESERVED foo.save() because slicing a queryset guarantees only no more than N objects. Removing the slice might lock a large number of rows that I don't need to lock. Is this inefficient? The whole Foo table won't be locked for long because I update only N objects and then exit the transaction. Is the only answer to grab the objects one at a time inside the transaction, or to get all of them as a list and re-check its length? with transaction.atomic(): foos … -
Django webhook receiver
I built a web hook receiver that takes JSON and creates a model object. It works fine with JSON. But someone I am receiving data from uses a different type of string data. I am currently just printing it out in the console. How would I convert this into a model object? The data they are sending looks like this: Phone1=4441114444&FirstName=Chris&LastName=Farley&DOB=1982-11-21&Email=test@test.com class Client(models.Model): first_name = models.CharField(blank =True, max_length=100) last_name = models.CharField(blank=True, max_length=100) phone = models.CharField(max_length=100, null=True, default="", blank=True) email = models.EmailField(max_length=100,default="", blank=True) @csrf_exempt def webhook(request): if request.method == 'POST': print(json.loads(request.body)) Client.objects.create( first_name=json.loads(request.body)['FirstName'], last_name=json.loads(request.body)['LastName'], phone=json.loads(request.body)['Phone1'], email=json.loads(request.body)['Email'] ) return HttpResponse(request.body, status=200) -
django problem trying to do mosh python Tutorial course
: [Errno 2] No such file or directory python manage.py runserver I tried the cd thing didn't workout Python Tutorial - Python Full Course for Beginners 5:05 project: building a website with Django -
why is the colour of button tag different as you can see in the image?
<!DOC TYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home Page</title> </head> <body> {%for message in messages%} <div class="alert alert-{{message.tags}}alert-disimissible fade show"role="alert"> <strong>Message:</strong>{{message}} <button type="button" class="close" data-dismiss="alert" aria-label="close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} <h3>Welcome!</h3> {%if user.is_authenticated%} <h3>hello{{fname}}</h3} <button type="submit"><a href="/signout">signout</a></button> {% else %} <button type="submit"><a href="/signup">SignUp</a></button> <button type="submit"><a href="/signin">SignIn</a></button> {% endif%} </body> </html> i am creating a django login form can you tell whats wrong with above code as the signout button is not displayed when i run it -
Geodjango Querying geometry returns pointer instead of geometry
I am trying to get a single MultiPolygon geometry in a Queryset from this model: class local_administrative_unit(models.Model): lau_id = models.IntegerField(primary_key=True) lau_name = models.CharField(max_length=150) adm_level_2 = models.ForeignKey('administrative_level_2', on_delete=models.PROTECT) geom = models.MultiPolygonField(srid=4326) trying it this way in the Django shell: local_administrative_unit.objects.get(lau_id=1).geom which returned: <MultiPolygon object at 0x7fb12af0ab10> when I pass this to the Centroid function, it does not what I was looking for: Centroid(Value(<MultiPolygon object at 0x7fb12af0ac90>)) Can you please tell me how I get the actual geometry to use it afterwards - for example for calculating the Centroid of that polygon? Looks like I am getting a pointer to what I am looking for instead of the actual thing. Thanks in advance. -
Import csv file using django - Exception Type: DatabaseError
I am trying to create a django project and I need to upload a csv file and create objects. I found a video: https://www.youtube.com/watch?v=t3BdM6JlAmY and https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html. My code: sales/model.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Sales(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.CharField(max_length=10, blank=False, null= False) product = models.CharField(max_length=10, blank=False, null= False) def __str__(self): return f"{self.user}" sales/admin.py from django.contrib import admin from .models import Sales admin.site.register(Sales) In the main project, settings, I added that part about Media. urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('csvs.urls', namespace='csvs')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) csvs/models.py from django.db import models class Csv(models.Model): file_name = models.FileField(upload_to='csvs') uploaded = models.DateTimeField(auto_now_add = True) activated = models.BooleanField(default= False) def __str__(self): return f"File id: {self.id}" csvs/forms.py from django import forms from .models import Csv class CsvModelForm(forms.ModelForm): class Meta: model = Csv fields =('file_name',) and views.py from django.shortcuts import render from .forms import CsvModelForm from .models import Csv import csv from django.contrib.auth.models import User from sales.models import Sales def upload_file_view(request): form = CsvModelForm(request.POST, request.FILES) if form.is_valid(): form.save() form = CsvModelForm() obj= Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') … -
DJANGO update is_active when email_confirmed is checked
On the Django admin interface, when I check email_confirmed under the Profile model, is there a way for me to automatically update is_active under the Djangos authentication User model? Linking them together in a way. Would like the ability to be able to check both with 1 click if a user hasn't recieved their sign-up email. Profile.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) unique_id = models.UUIDField(null=False, blank=False, default=uuid.uuid4, unique=True, editable=False) email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username admin.py @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ('user', 'email_confirmed') search_fields = ('user__email',) readonly_fields = ('user', 'unique_id') fieldsets = ( ('Details', { 'fields': ('unique_id', 'user') }), ('Status', { 'fields': ('email_confirmed') }), ('Timezone', { 'fields': ('timezone') }), ) I have looked into using @reciever(setting_changed) in Profile.py, but didn't quite understand. Similarly I have looked into the following in admin.py, and trying to set is_active to true in there but to no avail. def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "email_confirmed": Thank you in advance for you help -
Referencing User ID in Django URL dispatcher
I'm trying to implement a search feature where user's can search an email on a React frontend and it'll return that email's top 5 love languages. Currently the url path requires the primary key of a love language model, but I want it to use the user id. I have this Django URL set as: path('love-languages/', LovesView.as_view(), name='love-languages'), path('love-languages/<int:pk>', LoveView.as_view(), name='love-languages') Relevant love language model: class Love(models.Model): # Obtaining the user from the user model user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE ) # Defining the dropdown choices class LoveLanguages(models.TextChoices): ACTS_OF_SERVICE = 'Acts of Service' RECEIVING_GIFTS = 'Receiving Gifts' QUALITY_TIME = 'Quality Time' WORDS_OF_AFFIRMATION = 'Words of Affirmation' PHYSICAL_TOUCH = 'Physical Touch' one = models.CharField(max_length=20, choices=LoveLanguages.choices) two = models.CharField(max_length=20, choices=LoveLanguages.choices) three = models.CharField(max_length=20, choices=LoveLanguages.choices) four = models.CharField(max_length=20, choices=LoveLanguages.choices) five = models.CharField(max_length=20, choices=LoveLanguages.choices) and love language views: class LovesView(APIView): def get(self, request): loves = Love.objects.filter(user=request.user.id) data = LoveSerializer(loves, many=True).data return Response(data) def post(self, request): request.data['user'] = request.user.id love = LoveSerializer(data=request.data) if love.is_valid(): love.save() return Response(love.data, status=status.HTTP_201_CREATED) else: return Response(love.errors, status=status.HTTP_400_BAD_REQUEST) class LoveView(APIView): def get(self, request, pk): love = get_object_or_404(Love, pk=pk) # if request.user != love.user: # raise PermissionDenied('Unauthorized, you are not signed in as this user') # else: data = LoveSerializer(love).data … -
How to filter a queryset of objects created more than one hour ago from Django's DateTimeField?
Problem: I'm trying to filter a model where the status has not changed in over an hour. What I've tried: Product.objects.filter( Q(status="PENDING"), Q(created__hour__gt=1) ).all().order_by("-created") Expected Solution: Get a queryset of objects whose status is "PENDING" but has not changed in more than one hour. -
Fetch image and crop before save django
I'm using django. I have a code that will parse an HTML code and try to get and save the image to the database. Here is the code: link = content[content.find( 'src=')+5:content.find('alt')-2] img_data = requests.get(link).content with open('temp_image.jpg', 'wb') as handler: handler.write(img_data) with open('temp_image.jpg', 'rb') as handler: file_name = link.split("/")[-1] post.cover.save(file_name, files.File(handler)) os.remove("temp_image.jpg") But I also need to crop the image. How can I do that? Thank you. -
Customized CreateModelMixin - Object creation defined in my Model
My rest api view defines only two methods: class RequestSerializerViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): i have some experience overwriting the list, but i have no experience overwriting create as it seems to be a lot more complicated. What i want to achieve is following. My Request model has a special method which creates instance of Requests - start_request. This method creates not only the instance of Request, but also some additional foreign objects and assings them to the newly created Request. So my goal would be to modify rest api POST (create, perform_create, or serializer - i have no idea atm. which is the correct way) method so, that it does not create the Request on its own, instead, uses start_request method of the model. What would be the best django approach to this? -
not able to login with false credentials
Not able to login when I try to register user using react 0 upvotes Anil Kumar · Lecture 42 · 31 minutes ago when i tried to register user from react, the user was registered successfully, but when i tried to login with those credentials its showing "TypeError at /api/users/login/ Object of type Response is not JSON serializable" but I can login if i register the user using postman, class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): try: data = super().validate(attrs) # data['username'] = self.user.username serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data except: message = {'detail': f'Cannot find the user!'} return Response(message) # @api_view(['POST']) def registerUser(request): data = request.data try: user = NewUser.objects.create_user( email=data['email'], first_name=data['first_name'], last_name=data['last_name'], password=data['password'], username=data['first_name'] + data['last_name'], is_active=True, is_student=True, ) serializer = UserSerializerWithToken(user, many=False) # successMessage = "user Registered successfully!" emailSending(user.email) return Response(serializer.data) except Exception as e: message = {'detail': f'User with email: {data["email"]} already exists'} # return Response(message, status=status.HTTP_400_BAD_REQUEST) return Response(message) here is the code in react export const register = (email, first_name, last_name, password) => { return dispatch => { dispatch(registerAuthStart()); const config = { headers: { 'content-type': 'application/json' } } const body = JSON.stringify({ email, first_name, last_name, password }); console.log(body); // … -
Why would object.pk be None in get_success_url in CreateView?
I have a CreateView to which after creation I'd like the user to be directed to the DetailView for that newly created instance. class ModelCreateView(LoginRequiredMixin, CreateView): model = Model template_name = 'models/model-create-template.html' In my get_success_url method, I use self.object.pk, but it is None. def get_success_url(self): return f'/model/{self.object.pk}' I can see that I reach a successful save() since my post_save signals are firing, and form_valid() is called as well, since I update the user in this method. When I look in my debugger at self.object, all of the other fields are populated, by id and pk are both None. Looking at the instance in admin, I can confirm these are actually being set correctly, but for some reason at the time of calling get_success_url I don't have access to this data. Is the instance in self.object actually the created instance, or is it just representing the fields submitted by the CreateView form? If its the former, how could I access the instance in get_success_url? -
Django update order field on save
Advancing on this question: Django model list order field update I am trying to update all order fields when i update 1 record from a drag and drop list result. Current implementation using linked question: class Section(models.Model): name = models.CharField() order = models.IntegerField(default=0) def save(self, *args, **kwargs): existing_sections = ( Section.objects.filter( order__gte=self.order ) .exclude(id=self.id) .order_by("order") ) existing_sections.update(order=F("order") + 1) super(Section, self).save(*args, **kwargs) Lets say i have 5 fields, with order fields 1 to 5 incrementally. This code works fine if i add a new Section at the start or end of sequence. It will make first 1 and add 1 to all existing. But if i want to move from index 3 to index 5, then i will end up with the following as final result. Note the order = 3 is missing and added 6 to the end. order = 1 order = 2 order = 4 order = 5 order = 6 -
django framework: get value from django.db.models.fields.IntegerField
How can I get value from class django.db.models.fields.IntegerField? I want get 1 from admin field. This is python code: model class and function view from django.db import models from django.db import connection import pymysql # Create your models here. class Users(models.Model): def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.firstname=models.CharField(max_length=100) self.lastname=models.CharField(max_length=100) self.username=models.CharField(max_length=50) self.password=models.CharField(max_length=255) self.admin=models.IntegerField() self.createdAt=models.DateTimeField(db_column="created_at") def getAdmin(self): return self.admin class Meta: db_table = 'users' A view function when I run user = Users.objects.get(id=userId) def home(request): #controllo se sei loggato if request.session.has_key('loggedin'): if request.session['loggedin'] != True: return redirect("login") else: return redirect("login") #l'utente è loggato recupero le informazioni userId = int(request.session['id']) user = Users.objects.get(id=userId) print(type(user)) print(type(user.getAdmin())) tmplVar = {} tmplVar["admin"] = user.admin return render(request, 'pygiustizia/home.html',{'tmplVar': tmplVar}) -
ArgumentError with Django rtree module on Apache
I have a VPS running Django on Apache. I am using Django as a backend and I am calling it from JavaScript in the frontend. In the views.py file I handle the upload of a .zip file and I elaborate it using GeoPandas and Shapely. Since GeoPandas module needs Rtree, I installed both Rtree module and his dipendency libspatialindex. The problem is that when JavaScript upload the file using FormData, the server sometimes returns the correct output (and status code 200) and sometimes returns error 500 with this message: ArgumentError argument 5: <class 'TypeError'>: expected LP_LP_c_long instance instead of pointer to LP_c_long ... Exception Location: /opt/bitnami/python/lib/python3.8/site-packages/rtree/index.py, line 688, in intersection Python Executable: /opt/bitnami/python/bin/python3 Python Version: 3.8.12 Python Path: ['/opt/bitnami/projects/GeoidDjangoAPI', '/opt/bitnami/python/lib/python38.zip', '/opt/bitnami/python/lib/python3.8', '/opt/bitnami/python/lib/python3.8/lib-dynload', '/opt/bitnami/python/lib/python3.8/site-packages', '/opt/bitnami/python/lib/python3.8/site-packages/setuptools-46.4.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/pip-21.3.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/six-1.16.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/platformdirs-2.4.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/filelock-3.4.2-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/distlib-0.3.4-py3.8.egg'] How can I solve? I tried to reinstall the required packages both using venv and without. -
Django : can't interrupt update function with redirect. Is it possible?
I use a function for updating a Model. def update_mapping(request, pk): flow = Flow.objects.get(pk=pk) mappings = MappingField.objects.filter(fl_id=pk) headers_samples = GetCsvHeadersAndSamples(request, pk) [...] In this function, I call another one (GetCsvHeadersAndSamples) for getting datas from a CSV. Later, I use those datas with JS in the template. def GetCsvHeadersAndSamples(request, flow_id): get_file_and_attribs = get_csv(request, flow_id) file = get_file_and_attribs[0] separator = get_file_and_attribs[1] encoding = get_file_and_attribs[2] with open(file, encoding=encoding) as f: reader = csv.reader(f, delimiter=separator) headers = next(reader) samples = next(itertools.islice(csv.reader(f), 1, None)) headersAndSamples = {'headers': headers, 'samples': samples} return headersAndSamples For accessing CSV datas, I use another function for checking if the CSV still exists, in which case, I retrieve datas in it. def get_csv(request, flow_id): flow = Flow.objects.get(pk=flow_id) file = flow.fl_file_name separator = flow.fl_separator media_folder = settings.MEDIA_ROOT file = os.path.join(media_folder, str(file)) if os.path.isfile(file): file_2_test = urllib.request.urlopen('file://' + file).read() encoding = (chardet.detect(file_2_test))['encoding'] return (file, separator, encoding) else: # print('No file') messages.error(request, "File not found or corrupted.") return HttpResponseRedirect(reverse('mappings-list', args=(flow_id,))) I hoped that the return would "break" my original function and would redirect to the 'mappings-list' page with the message.error. But it continues and returns to GetCsvHeadersAndSamples function that generates an error because CSV datas were not found. Nota: the commented print however shows … -
Displaying Mutiline string in django through ajax
When I use the following code to return a multiline string data to my html page, it turns out to become a single line string. Is there a way to display the multiline string? <div class="multiline" id="result"> </div> $(document).on('submit','#post-form', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/create', data:{ other:$('#other').val(), code:$('#code').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ $('#result').html(data); } }); }); I try to use the following code: $.each(data.split(/[\n\r]+/), function(index, line) { $('<li>').text(line).appendTo('#result'); }); but the displayed string is increasing each time when i submit another data and i want the new string to overwrite old string -
Can I prevent Django from deleting an object depending on an attribute in a referencing type?
Imagine PetOwner and a Pet models: class PetOwner(models.Model): name = models.CharField() class Pet(models.Model): owner = models.ForeignKey('PetOwner', on_delete=models.CASCADE) alive = models.BooleanField(default=True) I would like it to be possible to delete PetOwners, but only if all theiry associated Pets are not alive anymore. If that is the case, the PetOwner can be deleted and all his associated pets are also deleted (cascade semantics). Is that possible? -
whats the best way to encode/hash url ids in django 1.11
I'm trying to migrate our project that uses incremental ids for our APIs to use encoded or hashed ids. The problem is we're using Django 1.11 that doesn't support url converters which will be very helpful for implementing this feature. But.. Upgrading Django is not an option for us (too risky!) the only viable option I'm considering is to use Django middleware and write our own middleware that will do the transformation for us (but this seems a very ugly solution because modifying original request info is just meh) What is the best implementation and solution for this? thanks! -
Double aggregation of queryset in django
I have data that looks like this: [{ 'ticker': 'ACVA-US', 'source': 'INTERNAL', 'event_id': 300, 'value_usd': 3000.0, 'shares': 300.0, 'days_to_trade': 3.0, 'num_trades': 1 }, { 'ticker': 'ACVA-US', 'source': 'INTERNAL', 'event_id': 200, 'value_usd': 2000.0, 'shares': 200.0, 'days_to_trade': 2.0, 'num_trades': 1 }, { 'ticker': 'ACVA-US', 'source': 'EXTERNAL', 'event_id': 200, 'value_usd': 1000.0, 'shares': 100.0, 'days_to_trade': 1.0, 'num_trades': 1 }] I need to perform what is essentially a double-aggregation. First, I need to take the average of items with the same ticker+event, which would look like: [{ 'ticker': 'ACVA-US', 'event_id': 300, 'value_usd': 3000.0, 'shares': 300.0, 'days_to_trade': 3.0, 'num_trades': 1 }, { 'ticker': 'ACVA-US', 'event_id': 200, 'value_usd': 1500.0, 'shares': 150.0, 'days_to_trade': 1.5, 'num_trades': 2 }] Next, I need to sum up items across tickers, which would look like: [{ 'ticker': 'ACVA-US', 'value_usd': 4500.0, 'shares': 450.0, 'days_to_trade': 4.5, 'num_trades': 3 }] I can't figure out how to do this using Django. I've tried: query1 = queryset.values('ticker', 'event_id').annotate(value_usd=Avg('value_usd'), shares=Avg('shares'), days_to_trade=Avg('days_to_trade'), num_trades=Count('ticker')) query2 = query1.values('ticker').annotate(value_usd=Sum('value_usd'), shares=Sum('shares'), days_to_trade=Sum('days_to_trade'), num_trades=Count('security')) but I receive an error django.core.exceptions.FieldError: Cannot compute Sum('value_usd'): 'value_usd' is an aggregate. I was hoping to do this without having to create a db view that performs the first aggregation, but so far I can't figure it out. I need … -
Check if django queryset have the same value in specific field
Is there any easier way to check if the query set have same value in specific field class Subject(models.Model): name = models.CharField(max_length=15, blank=False) summary = models.CharField(max_length=200, blank=True) price = models.DecimalField(max_digits=6, decimal_places=2) is_finish = models.BooleanField(default=False) y = Subject.objects.all() how to know if y objects, each of them have is_finish == True without using for loop? I just want to know that the queryset is giving me the same value for is_finish field. -
HTML page not refreshing after rendering in views in Django
I am currently working on a django project. Below is a function which handle "charts/" request def charts(request): if request.method == 'POST': form = SecuritiesForm(request.POST) if form.is_valid(): data = generateCharts(list(form.cleaned_data.get("securities_field"))) return render(request, 'charts.html', { "tickerList": data["tickerList"], "current": data[data["tickerList"][1]]}) if request.method == 'GET': ticker = request.GET.get('ticker', '') print(ticker) data = getData() print(data.keys()) return render(request, 'charts.html', { "tickerList": data["tickerList"], "current": data[ticker]}) return render(request, 'home.html', {'form': SecuritiesForm()}) as you can see when it is a GET request I update the dictionary and try to render the same HTML file. However my HTML page does not refresh and continues to show the same content, Can anyone help with this? It does not seem to refresh with the new data. On HTML side I do this {% if current %} {{ current |safe }} {% else %} <p>NO Graph</p> {% endif %} -
how can i use filter to check if specific user's social media link is correct?
def userProfile(request, pk): user = User.objects.get(id=pk) rooms = user.room_set.all() room_messages = user.message_set.all() topics = Topic.objects.all() link_fb = User.objects.filter(Q(link_fb__icontains='facebook')) link_ig = User.objects.filter(Q(link_ig__icontains='instagram')) link_lin = User.objects.filter(Q(link_lin__icontains='linkedin')) context = {'user': user, 'rooms': rooms, 'room_messages': room_messages, 'topics': topics, 'link_fb': link_fb, 'link_ig': link_ig, 'link_lin': link_lin} return render(request, 'base/profile.html', context) I've got something like this. I want to check if url is correct. Problem is i can not get specific user and then use filter. Is there any other way to do that?