Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django inline formset with one to many model relationship - many side presented as a checklist from third model
I have Django app that adds food items to a fridge. From models.py class Fridges(models.Model): fridge = models.CharField() class FoodItems(models.Model): food_item = models.CharField() class FridgeFoodItems(models.Model): fridge = models.ForeignKey(Fridges) food_item = models.ForeignKey(FoodItems) expires = models.DateTimeField() I want to create an inline formset form that combines two forms: A form for model Fridges that has one instance of fridge. A second form with a list of all possible food items from model FoodItems presented as a checklist. The user would check some of the food items in the list and click submit to add all checked food items to model FridgeFoodItems. I haven't yet seen an example that has a list of second form values populated from a third model. None of the examples / tutorials I have seen have the equivalent of a checklist. They all have a hard coded choice option list that user selects from, and they require submitting one option at a time. How does the third model values get sent to form and presented as a checklist with form checkboxes? -
Invalid authtoken returns 401
I'm using Django Rest Framework for my REST Api. I have a config endpoint that two of my other servers (The client which is a React.js app and the file server) use. The client has to retrieve the config before it can fetch a user or the current logged in user or render the view layer. Since I'm using token based authentication, if the authtoken is invalid (ie, it doesn't exist) Django returns 401. This prevents the client application from starting due to it not having access to the config. I have an auth endpoint that will give the current user or anonymous, this can give 401 because then the client can tell the user that their session expired. How can I tell django rest framework to simply treat an invalid token as an anonymous user instead of returning an error? I've tried this permission class for my config view: class ConfigView(APIView): permission_classes = (permissions.AllowAny, ) def get(self, request): return Response(config) But it still returns an 401 if the token is invalid. -
how to add dynamic bootstrap modal using jinja2
I'm working for a project where i have to make cards and open a modal when view details button is clicked. I am using django 1.8 and jinja2. This is my views.py from django.shortcuts import render from models import Club # Create your views here. def clubs(request, club): ideee = clubs[0].id #as i didn't made the ClubName as primary key and # hence i am taking id as ideee activities = Notice.objects.filter(NoticeClub=ideee) context = {'activities':activities} return render(request, 'club/club.html', context) and this is the template i am rendering i.e club.html {% for notice in activities %} <div class="row"> <div class="col-sm-4"> <div class="card myImg"> <img src="{{ notice.NoticeFile.url }}" alt="Card image" style="border: 7px solid white"> <div class="card-block" > <h3 class="card-title"><b>{{ notice.NoticeTag }}</b></h3> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">View Details</button> </div> </div> </div> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog modal-lg {{id}}"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">{{ notice.NoticeTag }}</h4> </div> <div class="modal-body"> <img src="{{ notice.NoticeFile.url }}" alt="Card image"> <p>{{ notice.NoticeContent }}</p> <a href="{{ notice.facebook_url }}">facebook</a> </div> </div> </div> </div> </div> {% endfor %} Forget the styling i am talking about modal data target. Right now i have let's say two notices. For that i am generating two cards … -
form does not post when submitting
When I submit my form, I do not get a POST, the page just reloads. I have been looking at this for days and cannot see the forest from the trees. Any help would be greatly appreciated models.py from __future__ import unicode_literals from django.db import models from datetime import date from .choices import Countries from .choices import Location from .choices import Status from .choices import Services_required class Offering_request(models.Model): platform = models.ForeignKey('Platform') offering = models.ForeignKey('Offering', blank=True) insight_quote = models.IntegerField(default=0000) customer_name = models.CharField(max_length=120, default='Not Applicable') country = models.CharField(max_length=14, choices=Countries) deal_value = models.IntegerField(default=0000) request_date = models.DateField() ### Need to add default=date.today requester_name = models.CharField(max_length=35) requester_email = models.EmailField() requester_mobile_number = models.CharField(max_length=14) approval_manager_name = models.CharField(max_length=35) approval_manager_email = models.EmailField() presales_name = models.CharField(max_length=35) presales_email = models.EmailField() solution_support = models.CharField(max_length=3, choices=Services_required) start_date = models.DateField() end_date = models.DateField() location = models.CharField(max_length=13, choices=Location) solution_design = models.FileField(upload_to='solution_design/%Y-%m-%d') testplan = models.FileField(upload_to='testplan/%Y-%m-%d', blank=True, null=True) request_description = models.TextField() audience_description = models.TextField() class Platform(models.Model): name = models.CharField(max_length=100) offerings = models.ManyToManyField( 'Offering', blank=True, help_text='List of COE offerings to show for this platform' ) def __unicode__(self): return self.name class Offering(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class PlatformOffering(models.Model): """Configuration for an offering on a platform. This model exists to configure an offering for a particular platform … -
serve multiple gunicorn django instances under nginx ubuntu
I need to serve up two webs apps (Django) on gunicorn under different domain names using nginx on ubuntu. I started using this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 It worked just fine for one using that. Then I tried to do the same thing for the second but it gives me a 502 gateway for the second domain. So I tried following this tutorial: http://michal.karzynski.pl/blog/2013/10/29/serving-multiple-django-applications-with-nginx-gunicorn-supervisor/ I'm at the part where you run the gunicorn start script: sudo bin/gunicorn_start I get back the response: Starting webuildblack as root Traceback (most recent call last): File "/home/devin/webuildblack/bin/gunicorn", line 7, in <module> from gunicorn.app.wsgiapp import run ImportError: No module named 'gunicorn.app'; 'gunicorn' is not a package -
DateField doesn't work in forms.py
I'm trying to create a datetime input field, but it shows as a simple input text, i'm using django 1.10, thanks in advance. from django import forms import datetime from .models import Student class StudentForm(forms.ModelForm): class Meta: model = Student fields = ["name","date"] widgets = { 'date': forms.DateInput(format="%d/%m/%Y")} -
Trouble with psycopg2 setting up django
I'm trying to set up a Django app using a postgresql server (to eventually use with GeoDjango for GIS). I'm on a mac running OSX 10.11 and am running python 3.5 in a virtualenv. I've gone through all the installtion of postgresql, pyscopg2 etc and am trying to run python manage.py runserver But when I do I get the following error. Traceback (most recent call last): File "/Users/me/.python3env/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> import psycopg2 as Database File "/Users/me/.python3env/lib/python3.5/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: dlopen(/Users/me/.python3env/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Users/me/.python3env/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so Reason: image not found I've found a couple of stackoverflow threads on this error but none of the solutions seem to help at all. Any advice would be much appreciated! -
Convert Django View to Python file
I have the following view in django which works as expected: from xmlsoccer import XmlSoccer from straightred.models import StraightredFixtureLive @csrf_exempt def updatefixtureslive(request, soccerseason, league): if request.user.is_authenticated(): xmlsoccer = XmlSoccer(api_key='XYZ123ABC789', use_demo=False) fixtureslive = xmlsoccer.call_api(method='GetLiveScoreByLeague', league='English Premier League') count = 0 for fixturelive in fixtureslive: if 'Id' in fixturelive.keys(): count = count + 1 fixtureLiveUpdate = StraightredFixtureLive(fixtureid_id=fixturelive['Id'], away_team_id = fixturelive['AwayTeam_Id'], home_team_id = fixturelive['HomeTeam_Id'], fixturedate = fixturelive['Date'], fixturestatus = fixturelive['Time'], fixturematchday_id = fixturelive['Round'], spectators = fixturelive['Spectators'], hometeamscore = fixturelive['HomeGoals'], awayteamscore = fixturelive['AwayGoals'], homegoaldetails = fixturelive['HomeGoalDetails'], awaygoaldetails = fixturelive['AwayGoalDetails'], hometeamyellowcarddetails = fixturelive['HomeTeamYellowCardDetails'], awayteamyellowcarddetails = fixturelive['AwayTeamYellowCardDetails'], hometeamredcarddetails = fixturelive['HomeTeamRedCardDetails'], awayteamredcarddetails = fixturelive['AwayTeamRedCardDetails'] ) fixtureLiveUpdate.save() return HttpResponse("Live games have been updated." + str(count)) else: return HttpResponse("You must be logged in to update teams.") I have removed all the parts I thought were just django specific and ended up with the following: from xmlsoccer import XmlSoccer from straightred.models import StraightredFixtureLive xmlsoccer = XmlSoccer(api_key='XYZ123ABC789', use_demo=False) fixtureslive = xmlsoccer.call_api(method='GetLiveScoreByLeague', league='English Premier League') count = 0 for fixturelive in fixtureslive: if 'Id' in fixturelive.keys(): count = count + 1 fixtureLiveUpdate = StraightredFixtureLive(fixtureid_id=fixturelive['Id'], away_team_id = fixturelive['AwayTeam_Id'], home_team_id = fixturelive['HomeTeam_Id'], fixturedate = fixturelive['Date'], fixturestatus = fixturelive['Time'], fixturematchday_id = fixturelive['Round'], spectators = fixturelive['Spectators'], hometeamscore = fixturelive['HomeGoals'], awayteamscore = fixturelive['AwayGoals'], homegoaldetails = fixturelive['HomeGoalDetails'], awaygoaldetails … -
Starting celery with a project's name as a command line parameter issued an error
I have a project under dev VM 'ubuntu/trusty'. I use virtualenv with the following packages: celery 3.1.23 eventlet 0.18.4 django 1.8.15 Python version is 3.4.3. When I start a celery worker in this way: celery worker --loglevel=INFO -P eventlet -c 3 -Q default -E -n default.queue -l INFO It starts correctly, but all tasks stay in the 'pending' state. When I start it this way (with project's name in '-A' parameter): celery worker -A meridian --loglevel=INFO -P eventlet -c 3 -Q default -E -n default.queue -l INFO It issues an error: (meridian)vagrant@vagrant-ubuntu-trusty-64:/vagrant/meridian/meridian$ celery worker -A meridian --loglevel=INFO -P eventlet -c 3 -Q default -E -n default.queue -l INFO Traceback (most recent call last): File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/app/utils.py", line 241, in find_app found = sym.app AttributeError: 'module' object has no attribute 'app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/vagrant/.virtualenvs/meridian/bin/celery", line 11, in <module> sys.exit(main()) File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/__main__.py", line 30, in main main() File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/bin/base.py", line 309, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline self.app = self.find_app(app) File "/home/vagrant/.virtualenvs/meridian/lib/python3.4/site-packages/celery/bin/base.py", line 489, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File … -
Save image to one to one user profile with pillow
So I am fairly new to Django and trying to teach myself by building an application that is fairly feature rich. One of the things I am trying to do is create a new image using pillow based off of some user input and if the user is logged in save the new image as something like image_name + user.email else image_name + datetime and then I will run a cron job to delete the non authenticated images fairly often. I currently have the actual image draw and save functionality in place already but I am looking for some guidance on implementing what I described above. See my current code below: # img definition fit_card = '/Users/krippee/Documents/Projects/project/main/static/img/size-card.png' fit_card_draw = Image.open(fit_card, 'r') draw = ImageDraw.Draw(fit_card_draw) ...(my image draw logic) # save img logic response = HttpResponse(content_type='size_card.png') fit_card_draw.save(response, 'PNG') return response Now I am assuming it would be something like: if request.user.is_authenticated: some save logic else: other save logic But I have been unable to find relevant examples to what I am attempting and I am at a lose as to how to proceed. I would greatly appreciate any advice or guidance that you can provide. -
Django Add PrimaryKeyRelatedField List
I have two classes class Drink(models.Model): name = models.CharField(max_length=100, blank=False, default='') brand = models.TextField() percentage = models.IntegerField() class Drinking(models.Model): amount = models.IntegerField(blank=False) drinks = models.ForeignKey(Drink, related_name='drinks',blank = True,null=True) and want to add a list of drinks to the Drinking model via a REST POST. In the serializer I have the following: class DrinkingSerializer(serializers.ModelSerializer): drinks = serializers.PrimaryKeyRelatedField(many=True, read_only=False ,queryset=Drink.objects.all()) class Meta: model = Drinking fields = ('pk','drinks','amount') def create(self, validated_data): return Drinking.objects.create(**validated_data) def update(self, instance, validated_data): instance.amount = validated_data.get('amount', instance.amount) instance.save() return instance When I try to POST an Drinking Object: { "drinks": [2], "amount": 5 } I get the Error, that Drinkings.drinks must be Drink instance. My guess is that I have to change the queryset to only get the primary key of the drinks but I don't know how. -
Facing problems going back to django 1.9 from 1.10
I am trying to learn django through a tutorial Try Django 1.9. I installed django version 1.10 I am trying to uninstall 1.10 and install 1.9 I uninstalled using pip. Then went into site packages and cleared the django folders. I even searched for django and deleted all possible file. But when I tried to install django version 1.9, the Power Shell (or terminal) started collecting django from the cache and reinstalled django 1.10. How do I clear the cache? -
how to use queue in Jinja2
I am sending a queue in my views to my template and want to only show the last entry to q in the template: def detail(request, id): context = { 'id' : id, 'URL' : URL, 'Q' : q.queue, } return detail_page(request,context) and in my html: {{Q}} works but it shows the whole queue i just want it to show the last element in queue. -
Django - import excel to database
I have a model abd a excel table that represents a data that shluld be imported to the database. How should I do that ? Django 1.7 Thank you! -
django adds %EF%BB%BF at the end of my urls
I am working on a blog django app. I have list of posts and a post detail pages. when I click on a post title in the list should takes to the post detail page. for some reason the url doesn't work. instead shows 404 that looks like this : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/practice-title/%EF%BB%BF Using the URLconf defined in cms.urls, Django tried these URL patterns,in this order: ^admin/ ^blog/ ^$ [name='list_of_post'] ^blog/ ^(?P<slug>[-\w]+)/$ [name='post_detail'] The current URL, blog/practice-title/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. and ideas? -
Django-CSRF verification failed
I'm creating a login page when an error occurred: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed. You can customize this page using … -
'function' object has no attribute 'objects' DJANGO(ERROR GETTING DATA FROM DATABASE)
I am trying 2 get data from the database sqllite and fetch the data n print it in the html file(user1.html) . I m following this tutorial line by line https://www.youtube.com/watch?v=MEcXbeY4_DQ So this is my models.py file in the app called mainpage from django.db import models class user1(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=100) maths=models.IntegerField() physics=models.IntegerField() english=models.IntegerField() computer=models.IntegerField() def __str__(self): return self.name This is my urls.py file from django.conf.urls import url from django.contrib import admin from django.conf.urls.static import static from django.conf import settings urlpatterns = [ url(r'^user1/', 'mainpage.views.user1',name='user1'), url(r'^user2z/', 'mainpage.views.user2z',name='user2z'), ] This is my view.py file from django.shortcuts import render from .models import * from django.http import HttpResponse, Http404 from django.template.response import TemplateResponse def user1(request): return render(request, "user1.html",{}) def user2z(request): data=user1.objects.all() return TemplateResponse(request,"user1.html",{"data":data}) This is my user1.html file hello check {{ data }} {% for video in data %} <h1>{{ video.id }}</h1> <h1>I m ideot</h1> {% endfor %} <br> hell check <br> so when i do localhost:8000/user2z i get this ERROR y? AttributeError at /user2z/ 'function' object has no attribute 'objects' Request Method: GET Request URL: http://localhost:8000/user2z/ Django Version: 1.9.8 Exception Type: AttributeError Exception Value: 'function' object has no attribute 'objects' Exception Location: C:\Users\vaibhav2\PycharmProjects\MyUniversityResult\mainpage\views.py in user2z, line 16 Python Executable: C:\Python34\python.exe Python Version: 3.4.3 … -
Issue passing data to template variable from a view in Django
I'm not really sure if I'm even doing this the correct way, but take a look. I have a view called returnjson which renders my html template. I have a condition, which when called grabs some data from a mysql database and then attempts to send it back to my template. def returnjson(request): if condition_met: # Access Database test_access = Topology.objects.filter(topology_name=data[1][0].get("topology_name")) topology_from_db = test_access[0].topology_json return render_to_response("index.html",{"topology_from_db": topology_from_db}) return render_to_response("index.html") In my template, I have a script tag to take the javascript variable (topology_from_db). I want it to be used by another javascript file which is a static file. <script type ="text/javascript"> var topology_from_db = "{{ topology_from_db|safe }}" </script> {% load static %} <script type="text/javascript" src="{% static 'js/pageFunctions.js' %}"></script> I would like to use topology_from_db in my pageFunctions.js file. -
Django - Lettuce - Selenium
I'm trying to run default project with the above stack, to be able to run front-end tests on my big project. Which uses a much bigger stack. (I've been trying to integrate it for that first but after multiple failures I tried to recreate it in a default django app) So the main issue is that Firefox throws Connection was reset error. I've tried firefox versions: 45, 46, 47. With selenium 2.48 and 2.53.6. Nothing seemed to make it work. I'm really unsure if it is related to that at all. zero.feature: Feature: Opening Page Scenario: Opening Landing page Given I access url "/" zero.py from lettuce import * from selenium import webdriver @step(r'I access url "(.*)"') def access_url(step, url): world.browser = webdriver.Firefox() world.browser.get('http://127.0.0.1:8000') and I have lettuce.django in INSTALLED_APPS. And it seems to run fine: Creating test database for alias 'default'... Django's builtin server is running at 0.0.0.0:8000 Feature: Opening Page # \blog\features\zero.feature:1 Scenario: Opening Landing page # \blog\features\zero.feature:3 Given I access url "/" # \blog\features\zero.py:7 what? No handlers could be found for logger "django.request" Given I access url "/" # \blog\features\zero.py:7 1 feature (1 passed) 1 scenario (1 passed) 1 step (1 passed) Test Suite Summary: 1 feature … -
Add second app to admin site
In my project "mems", I have two apps "teilnehmer" and "events". teilnehmer/admin.py: from django.contrib import admin from teilnehmer.models import --snip-- from events.models import Event admin.site.register(--snip--) # Models from teilnehmer app admin.site.register(Event) # THIS DOES NOT WORK events/models.py: class Event: --snip-- How do I get my second app's models registered in the first app's admin site, so that I can control both in the adminmenu. -
Django : export table in file SQL
I try to deploy my website developped with Django 1.9. I use the web hosting AlwaysData. The problem is that the database of my web hosting is empty (no tables) and I want to import my tables (in models.py) in this database. For that, I need a file sql that contains all my tables. After I will import this file in my AlwaysData database. I try the command dumpdata but the format sql doesn't exist (only yaml, xml and json). How can I do ? I use PostGreSQL. Thank you -
permabots keyboard template with jinja2
I'm going crazy. this is just boring. no docs. nothing. also I'm not good neither in python or jinja2. I know this is the real problem but for now, I need your help. permabots is a app built in django for managing telegram bots, I'm a fan of python so I want to learn this app bot in a very basic stage, I cannot write keyboard response in jinja2 as the app wants. just show how to do it. tnks. http://www.permabots.com/docs/getting-started https://core.telegram.org/bots/api#replykeyboardmarkup -
Python unittest.mock.patch for function don't work
I'm trying to test my python application use unittests with mock.patch but it don't work as well. My code: test_file.py from unittest.mock import patch class TestMaterialsUpdate(TestCase): def setUp(self): self.client = Client() @patch('api.accounts.helpers.get_authenticated_user', return_value={'username': 'username'}) def test_my_castom_method(self): import api.accounts.helpers as he print(he.get_authenticated_user) # printed mock here print(he.get_authenticated_user) # returned {'username': 'username'} url = reverse('materials_create') # next call get_authenticated_user will be in post request self.client.post(url,data=json.dumps({'data': 'data'}), content_type='application/json') The post request call the decorator that check "user auth" use get_authenticated_user function. But in decorator I got function instead mock-object. decorators.py def login_required(func): def wrapper(*args, **kwargs): print(get_authenticated_user) # printed <function get_authenticated_user at 0x7fec34b62510> user = get_authenticated_user(request) # return None instead {'username: 'username'} Why in decorators.py I got a function instead the mock-object? Python version is 3.4.0 -
How to add a List Field in django model
i am trying to add a new field in a model which will show all the related values of this model to another. Like as i have following : models.py from django.db import models class University(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) university = models.ForeignKey(University) def __unicode__(self): return '%s %s' % (self.first_name, self.last_name) views.py from rest_framework import viewsets from .models import University, Student from .serializers import UniversitySerializer, StudentSerializer class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer class UniversityViewSet(viewsets.ModelViewSet): queryset = University.objects.all() serializer_class = UniversitySerializer serializers.py from rest_framework import serializers from .models import University, Student class UniversitySerializer(serializers.ModelSerializer): class Meta: model = University class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student and urls.py from rest_framework import routers from core.views import StudentViewSet, UniversityViewSet from django.conf import settings from django.conf.urls import url, include from django.contrib import admin router = routers.DefaultRouter() router.register(r'students', StudentViewSet) router.register(r'universities', UniversityViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.core.urls', namespace='core')), ] and now i am writing rest-api using django-rest-framework so i get like this HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "students": "http://127.0.0.1:8000/api/students/", "universities": "http://127.0.0.1:8000/api/universities/" } now when i click http://127.0.0.1:8000/api/universities/. I get HTTP 200 OK Allow: GET, POST, … -
How to get current signed user in forms.py?
I'm using ModelChoiceField to select Invoice provider in my forms. In the current case, I'm returning all the Providers to the queryset. But I should return only Providers that created by the signed user. Provider has a ForeignKey field named user. Here is my Form: class InvoiceCreationForm(forms.Form): # ... provider = forms.ModelChoiceField( label='Provider', required=False, queryset=Provider.objects.all(), widget=forms.Select(attrs={ 'name': 'provider', 'class': 'form-control', 'id': 'input-invoice-provider', }) ) I need to filter objects like this: Provider.objects.filter(user=current_user) How can I get the signed user? Or how can I get the request object outside of a view? I tried get the current user from __init__ method of the form then set it to self.user. But I can't use it in the query like self.user.