Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extract django mulitislect form choice
I want to reload part of my page upon form submit. To do this i´d like to extract the selected fields from a Django multiselectfield. Now I´m kinda stuck because Django renders the form like this: Instead of select-Tags. How can i extract which choices have been selected? Or is there any way to return new information when the form has been selected without leaving the page? -
Run django-gulp with gulp watch
I installed and configured django-gulp. It also works with starting the server via python manage.py runserver and automatically firing up gulp install, but I also would like to have gulp watch running. Currently I always need to start this in a second terminal window manually, is there any way to have this always running together with runserver? -
Django app hosting thorugh public ip not working when connected through DNS service
I've hosted a Django app through my public ip like so 12.123.123.123:8080 My ISP provide a free .st domain to which I've connected to ip and port. So mywebsite.st is hosting 12.123.123.123:8080. This DNS service has always worked when using node.js. When someone connects to my public ip it works. The cmd shows: "GET /favicon.ico HTTP/1.1" 404 85 When someone uses my website i get: "GET // HTTP/1.1" 404 75 and the website blanks Here's my ALLOWED_HOSTS = ['localhost', '12.123.123.123', 'www.mywebsite.st'] What's the deal? The DNS literally connects to my ip so I don't understand why it would be an issue. -
update object with a fromset
i'm working on a django project and i want to allow user the users to update a product details. The product is created from two models one for texte details and one for images with the product as a foreign key , i have two problems : 1- the fomset desplay 6 fileds instead of 3.: 2- when i change the image it does not update the old one. views.py def ProductUpdate(request,pk): ImageFormSet = formset_factory( ImageForm, extra=3) if request.method == 'POST': productForm = ProductForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, ) if productForm.is_valid() and formset.is_valid(): product = Product.objects.get(pk=pk) product.Type = productForm.cleaned_data['Type'] product.Price = productForm.cleaned_data['Price'] product.Description = productForm.cleaned_data['Description'] product.Name = productForm.cleaned_data['Name'] product.save() photo = ImageModel.objects.filter(product=product) photo[0].Image = formset[0].cleaned_data['Image'] photo[1].Image = formset[1].cleaned_data['Image'] photo[2].Image = formset[2].cleaned_data['Image'] photo[0].save() photo[1].save() photo[2].save() return redirect(reverse('my_products')) else: messages.error(request, ('Please correct the error below.')) else: product = Product.objects.get(pk=pk) images = ImageModel.objects.filter(product=product) data = [] for img in images: data.append({'Image':img.Image}) productForm = ProductForm(instance=product) formset = ImageFormSet(initial=data) return render(request, 'store/product_update.html', {'postForm': productForm, 'formset': formset,'product':product}, ) models.py class Product (models.Model): User=models.ForeignKey( User, on_delete=models.CASCADE, ) Name=models.CharField(max_length=50,blank=True) Type=models.CharField(choices=Product_Type,max_length=50) Description=models.TextField(max_length=250,blank=True) Price=models.FloatField(default=0.0) def __str__(self): return self.Name def image(self): return self.images.all() class ImageModel(models.Model): product=models.ForeignKey(Product,default=None,related_name='images' ) Image = models.ImageField( upload_to='products_photos',blank=True,null= True) -
Django - Getting current url in a function
So in a form_valid function i want to get the current url and return the last part of it as a string. The function is part of a ModelForm wich is displayed on a Detail view for another model via FormMixin, it works fine just not the part that matters wich is submitting. Here are my two models and the modelform: class Comment(models.Model): title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.PROTECT) def __str__(self): return self.title + '' + self.author.username def get_absolute_url(self): return reverse('comment-detail', kwargs={'pk': self.pk}) class Answer(models.Model): content = models.TextField() comment = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name='comments_answers') author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='answers') date_answered = models.DateTimeField(default=timezone.now) class AnswerForm(ModelForm): class Meta: model = Answer fields = ['content'] def form_valid(self,form): form.instance.auther = self.request.user form.instance.comment = Comment.objects.get(pk="x") return super().form_valid(form) so i want to replace x with a function that gets the current url as a string (and probably use str.raplace and regular expressions to replace the url by just the last part of it wich is the id of the comment object for the detail view the form is on) -
Update context of a django custom view
I have this view rendering a simple template with a context. In this template I have a form to make an axios call to update the variables first_name and last_name . The call is correctly working and the response is ok. But my context does not update. How can I update my template context? Can I do this without re-render my template? def myView(request) first_name = 'John' last_name = 'Doe' # Handling the axios call if request.method == 'POST': email = json.loads(request.body)['email'] user = User.objects.get(email=email) first_name = user.last_name last_name = user.first_name ctx = {'first_name'=first_name, 'last_name'=last_name} return render(request, 'mytemplate.html', ctx) -
Django - ModelForm ignores new field and doesn't show it in template
I have the following modelform in my application on production server: class FullPolicyForm(forms.ModelForm): class Meta: model = Policy fields = ('name',) # common info name = forms.CharField(widget=forms.TextInput(attrs={'class': 'float-none', 'style':'width:140px;'}), required=True) sdk_enabled = forms.BooleanField(required=False) remote_config_time_window = forms.IntegerField() #more fields exists here..... In my development environment I added a new field: group_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'float-none', 'pattern':'^[a-zA-Z\d-_]*$', 'style':'width:140px;'}), required=False) and I aslo added that field in my template as such <div class="fieldWrapper"> <label class="control-label col-sm-3 float-none">Group name:</label> {{ form.group_name }} <span class="label label-info" style="cursor: help;" data-toggle="popover-ex" data-placement="right" title="{{ field_description.group_name.0 }}" data-content="{{ field_description.group_name.1 }}" footer="{{ field_description.group_name.2 }}">?</span> </div> I tested the code in the development environment and everything works as it should. The I committed the code to remote repo and then pulled the changes on my production environment. Then when I opened the webpage, all the previous form fields were present except the new field (group_name), only the label and the span element appeared. What can cause the new model-form field to be ignored by Django? Notes: I restarted the server using pkill -f runserver and I also tried sudo systemctl restart nginx I didn't make any changes in my actual model, only added new fields to the model-form. -
Alternative solution to handle backslashs in Python
I'm currently developing a Flask web app and it works fine in the IDE, but after I deployed my application to the cloud I've got the following problem that I can't solve: 1.Attempt for i in os.listdir('data\\folder\\business'): >> No such file or directory: 'data\\folder\\business' As you see the escaping dosn't work properly on the server. So I've tried several other ways: 2.Attempt for i in os.listdir(r'data\folder\business'): >> No such file or directory: 'data\\folder\\business' 3.Attemt for i in os.listdir('data\folder\business'): >> No such file or directory: 'data\folder\x08usiness' Please tell me, if you know another way how to code backslashs in strings. -
Signal does not apply changes
I have a signal: @receiver(m2m_changed, sender=Company.users.through) def user_remove_sync(sender, instance, **kwargs): if kwargs['action'] == "pre_remove": for user_pk in kwargs['pk_set']: user = User.objects.get(pk=user_pk) if user in instance.admin_users.all(): instance.admin_users.remove(user) print(instance.admin_users.all()) That print shows everithing is OK, and users are removed, but finally my changes does not apply. What am I doing wrong? Thanks! -
Continuesly sending of logs to django websocket
We are currently using https://github.com/django/channels/ to get logs and send commands from and to docker containers. Multiple users connect on the site and simultaneously to the websocket that connects to our consumer. The connection itself is working, but as soon as more and more users are trying to use the functionality, the threads are all used and only the first ~20 users can use it. No further threads and connections can be opened. We assume that it's related to the loop that we are using to allow realtime information of the containers. This is the logic we are using: class TerminalConsumer(JsonWebsocketConsumer): def connect(self): self.accept() try: group_name = 'server-%s' % self.scope['session']['server_id'] server = CustomModel.objects.get(id=self.scope['session']['server_id']) container = get_docker_container(server) self.channel_layer.group_add(group_name, self.channel_name) if container is not False: for line in container.logs(stream=True, tail=150): self.send_json(line.strip().decode('utf-8')) asyncio.sleep(0.01) except Exception: pass def disconnect(self, close_code): group_name = 'server-%s' % self.scope['session']['server_id'] self.channel_layer.group_discard(group_name, self.channel_name) try: group_name = 'server-%s' % self.scope['session']['server_id'] self.channel_layer.group_discard(group_name, self.channel_name) except Exception: pass The client never disconnects and so the threads are completely used by the first users connecting. Where would we have to put the loop to disconnect the websocket accordingly? -
Does django rest-framework force the foreign key to point to a primary key?
In django it is absolutely fine to define a foreign key which point to a unique key column instead of primary key. For example class Cluster(models.Model): _id = models.UUIDField(unique=True, null=False, default=uuid.uuid1) name = models.CharField(max_length=200, unique=True, null=False) class Node(models.Model): _id = models.UUIDField(unique=True, null=False, default=uuid.uuid1) ip = models.GenericIPAddressField(null=False, unique=True) cluster = models.ForeignKey(Cluster, on_delete=models.PROTECT, to_field='_id', db_constraint=False) Please note that the _id field here is not a pk field. But in django rest-framework when define a serializer class NodeSerializer(serializers.ModelSerializer): cluster_id = serializers.PrimaryKeyRelatedField( source='cluster', queryset=models.Cluster.objects.all()) class Meta: model = models.Node fields = ('_id', 'name', 'ip', 'cluster_ip', 'cluster_id') The serializer will think that the cluster_id is pointing to the pk field of cluster. Is there any way I can tell serializer that cluster_id is not pointing to pk? -
Convert timefield to 24hours in django
I have a field Time = models.Timefield Which gives output as for example 8:30 am But I want 08:30:00 how can I get it? -
How to run a python file in the admin interface in Django?
I use window 7, python 2.7 and Django 1.11. I have a python script in the project, called called getsqlite.py. I want to run this file in the admin interface when the project was deployed. I have tried to creat a custom button in the admin interface to run the python script and sending email at the same time following this link but failed: https://medium.com/@hakibenita/how-to-add-custom-action-buttons-to-django-admin-8d266f5b0d41 form.py: class ActionForm(forms.Form): comment = forms.CharField( required=False, widget=forms.Textarea, ) send_email = forms.BooleanField( required=False, ) @property def email_subject_template(self): return 'email/notification_subject.txt' @property def email_body_template(self): raise NotImplementedError() def form_action(self, user): raise NotImplementedError() def save(self, user): try: action = self.form_action(user) except Exception as e: error_message = str(e) self.add_error(None, error_message) raise #if self.cleaned_data.get('send_email', False): email_user( to=[User.email], subject_template=self.email_subject_template, body_template=self.email_body_template, context={ "action": action, } ) return action class call_exe_Form(ActionForm): email_body_template = 'email/call_exe.txt' field_order = ( 'comment', 'send_email', ) def form_action(self, user): return when_call_exe admin.py: class FWAdmin(admin.ModelAdmin): """ Administration object for FW models. Defines: - fields to be displayed in list view (list_display) - adds inline addition of FW instances in FW view (inlines) """ list_display = ('ODM_name', 'project_name', 'NAP', 'UAP', 'LAP', 'num_address', 'download') #inlines = [FWs_InstanceInline] def get_urls(self): urls = super(FWAdmin, self).get_urls() custom_urls = [ url( r'^(?P<user>.+)/call_exe/$', self.admin_site.admin_view(self.process_call_exe), name='user-call_exe', ), ] return … -
A Progressive Web App in the Django, where i put the files?
I have two files for my PWA, service-worker.js and manifest.json, but i not know or to put in the django project, at the root of project ? There is no tutorial that explains well for Django... This is content of service-worker.js : https://paste.ee/p/c5Fme This is content of manifest.json : https://paste.ee/p/LKxOa And in the template base.html : https://paste.ee/p/bj5wz In terms of content, everything is ok? so.. i need help for the place of files. Thanks guys -
Link to the object in the letter
I have url:path('<int:id>',views.article_detail,name="detail") It works on the site. <p><a href="{% url 'detail' id=article.id %}">{{article.title}}</a> </p> But if I try to give a link in the email, for example <p><a href="{% url 'detail' id=article.id %}">article </a></p> In link I heve only http://articles/36 Link like <p><a href="127.0.0.1:8000+{% url 'detail' id=article.id %}">artickle! </a></p> not work. -
Can not import ASGI application module
I am not pro of using django-channels framework.I am facing issues in running asgi server.I will appreciate if anyone can help in fixing these issues.The error with warnings I am getting are : (base) C:\Users\praks\Desktop\django_web_page\mysite>python manage.py runserver :0: UserWarning: You do not have a working installation of the service_identity module: 'No module named 'service_identity''. Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied. Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification. Many valid certificate/hostname mappings may be rejected. :0: UserWarning: You do not have a working installation of the service_identity module: 'No module named 'service_identity''. Please install it from <https://pypi.python.org/pypi/service_identity> and make sure all of its dependencies are satisfied. Without the service_identity module, Twisted can perform only rudimentary TLS client hostname verification. Many valid certificate/hostname mappings may be rejected. Performing system checks... System check identified no issues (0 silenced). October 06, 2018 - 12:18:38 Django version 2.0.7, using settings 'mysite.settings' Starting ASGI/Channels version 2.1.2 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002AE7AF74488> Traceback (most recent call last): File "C:\Users\praks\Anaconda3\lib\site-packages\channels\routing.py", line 33, in get_default_application module = importlib.import_module(path) File "C:\Users\praks\Anaconda3\lib\importlib\__init__.py", line … -
Mysqlclient error on Mac ,while setting up for Django Project
Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /Users/code-7/PycharmProjects/Karma/venv/bin/python -u -c "import setuptools, tokenize;file='/private/var/folders/jy/2s8fhhjd1fl806xpg9lc8yrc0000gn/T/pip-install-h7u6c_94/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/jy/2s8fhhjd1fl806xpg9lc8yrc0000gn/T/pip-record-ttb9h9pq/install-record.txt --single-version-externally-managed --compile --install-headers /Users/code-7/PycharmProjects/Karma/venv/include/site/python3.7/mysqlclient: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.7 copying _mysql_exceptions.py -> build/lib.macosx-10.9-x86_64-3.7 creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb creating build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.9-x86_64-3.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.9-x86_64-3.7 gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -Dversion_info=(1,3,13,'final',0) -D__version__=1.3.13 -I/usr/local/Cellar/mysql/8.0.12/include/mysql -I/Users/code-7/PycharmProjects/Karma/venv/include -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c _mysql.c -o build/temp.macosx-10.9-x86_64-3.7/_mysql.o _mysql.c:257:6: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers] s = PyUnicode_AsUTF8(item); ^ ~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:287:6: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers] s = PyUnicode_AsUTF8(item); ^ ~~~~~~~~~~~~~~~~~~~~~~ _mysql.c:564:3: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers] _stringsuck(ca, value, … -
Why foreign key field in serializer of django rest-frame work become read only?
I have two models as below class Cluster(models.Model): _id = models.UUIDField(unique=True, null=False, default=uuid.uuid1) name = models.CharField(max_length=200, unique=True, null=False) desc = models.CharField(max_length=200, null=False, default='', blank=True) class Node(models.Model): _id = models.UUIDField(unique=True, null=False, default=uuid.uuid1) name = models.CharField(max_length=200, unique=True, null=False) ip = models.GenericIPAddressField(null=False, unique=True) cluster = models.ForeignKey(Cluster, on_delete=models.PROTECT, to_field='_id', db_constraint=False) As you can see above. One cluster model and one node model. The node will have a foreign key reference to cluster which means the node belongs to one cluster. Then I create a serializer class NodeSerializer(serializers.ModelSerializer): class Meta: model = models.Node fields = ('_id', 'name', 'ip', 'cluster_ip', 'cluster_id') The serializer works fine when retrieve data from database. But has problem when creating >>> print(NodeSerializer()) NodeSerializer(): _id = UUIDField(required=False, validators=[<UniqueValidator(queryset=Node.objects.all())>]) name = CharField(max_length=200, validators=[<UniqueValidator(queryset=Node.objects.all())>]) ip = IPAddressField(validators=[<UniqueValidator(queryset=Node.objects.all())>]) cluster_ip = IPAddressField(allow_null=True, required=False) cluster_id = ReadOnlyField() Because the cluster_id is READ ONLY, so serializer.validated_data will always miss the field cluster_id. So how could I create node with this serializer? -
sync database to python django
I am trying to connect the SQLite3 database to Django. while I try to sync the database with a command $ python manage.py syncdb it shows a long trace. I don't know how to fix it. can anyone help me with that Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python35\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python35\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python35\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "F:\django\DatabaseConnectTest\polls\models.py", line 9, in <module> class Choice(models.Model): File "F:\django\DatabaseConnectTest\polls\models.py", line 10, in Choice quesion = models.ForeignKey(Question) TypeError: __init__() missing 1 required positional argument: 'on_delete' -
passing multiple values from select tag of html
how can I pass more than 1 value in this function i tried but this does not work <select onchange="myFunction(this)"> <option value=''>new</option> {% for value in check %} <option value={{value.start}},{{value.end}}>{{ value.start }}</option> {% endfor %} </select> it is only passing {{value.start}} -
clicking link with no response in web page
I use windows 7. I have built a Django website using django 1.11 in python 2.7. In the website I want to achieve this function: when the user click the link in the page, a file should be downloaded. view.py: def download_file(request): # do something the_file_name = 'data.txt' filename = '20181005-1500_SLE1_CSRIOT_005b-02-c12345_3.txt' response = StreamingHttpResponse(readFile(filename)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name) return response def readFile(filename, chunk_size=512): with open(filename, 'rb') as f: while True: c = f.read(chunk_size) if c: yield c else: break url.py: url(r'^myFWs/', views.download_file, name='download_file'), html enter image description here When the user click each link, the corresponding file should be downloaded. But when I click the link, no response showed. -
How to ivoke update_feed() from /data_feeds/google_merchand.py/ every time when load url in saleor?
I need to invoke update_feed() from /data_feeds/google_merchand.py/ on particular url, localhost:8000/feeds/google/merchand. What should I do? -
Where(location) to install a Django project files on an Ubuntu Server, and permissions set
I need to go in production with a Django app on Ubuntu server. Until now(for testing) I set the virtual environment and the project code, in the home directory of an user with sudo permissions(I saw in some tutorials doing this way). But, I have a feeling that is not a good approach. So, what are the best locations, and how to set security for Linux users ? -
Serving icons with django through amazon S3
I have a django app with static files served through Amazon S3. All the static files are correctly served (CSS,js, ico, images..) except icons like for example FontAwesome. The location of thoses files are correcty set in the source code and I have no idea how to debug this. As visible on the picture below, the Content-Type in the metadata is correctly setted. -
Trouble calling the form constructor from django createview
I tried to pass the user( i.e, request.user) to my modelform constructor as given in this link.But i am getting TypeError: __init__() got an unexpected keyword argument 'us' error. Here's my view class dealAdd(generic.CreateView): form_class = dealForm template_name='deals/deal_Add.html' def get_context_data(self,**kwargs): context=super(dealAdd,self).get_context_data(**kwargs) llist=lead.objects.all() clist=contacts.objects.all() context.update({'leadob':llist,'contob':clist}) return context def get_form_kwargs(self, *args, **kwargs): kwargs = super(dealAdd, self).get_form_kwargs() kwargs.update({'us': self.request.user}) return kwargs and my form constructor def __init__(self,*args,**kwargs): usr=kwargs.pop('us') super(dealForm,self).__init__(*args, **kwargs) print(usr) # print(self) the traceback says that i have error at context=super(dealAdd,self).get_context_data(**kwargs) So is there a problem in my view?