Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is best practice to handle related data with REST api and Vue
For example we use the models course and category Category Model entry { "id": 4, "slug": "", "name": "IT", "description": "", "parent": 0, "color": "red", "access_level": 1, "state": 1, "created_at": "2019-08-08T12:15:22Z", "updated_at": "2019-08-08T14:46:22.955028Z" } Course Model entry { "id": 1, "name": "“Herz trifft EKG” – Grundlagen der Anatomie und der EKG- 1", "company": 1, "categories": [ 4 ], "course_dates": [ 5, 6 ], "created_at": "2019-08-08T14:35:57.882390Z", "updated_at": "2019-08-08T14:47:44.858062Z" } In DRF i am using the ModelSerializer with which the Id´s are used to display the relation. Currently i am getting all data from courses and all categories and want to mutate the data in vue to "solve" the Id´s of the categories into the names. Is this best practice to handle multiple relations? My understanding is that all API endpoints should only return their simple data and not the related data but only the id´s. -
Is there a way to create number of list depending upon the int value of a variable?
For example, i=5 so list1, list2, list3, list4, list5 will be automatically generated based on input value provided by user. -
Unable to install pylint-django on mac
I'm trying to install the latest version of pylint-django. I have django 2 installed and updated, and I have built a site that is working fine, but an issue has cropped up with pylint. Whilst it has done a great job in vscode for the past 4 months, something seems to have changed and now pylint is notifying of issues that were never there previously on an unchanged file. Further research showed that django requires it's own version of linting that will ignore these issues correctly instead of just ignoring them, I'm assuming that it compensates for the framework in some way. I have tried to install using pip: pip install pylint-django but received the following error in response: (django_env) UKC02TQH6UHV22:pcc_django rki23$ pip install pylint-django Collecting pylint-django Using cached https://files.pythonhosted.org/packages/05/01/1e7241e247d544aed790391b3a3a4f0e2cd93b7604e5a50ef3323ce5a812/pylint-django-2.0.12.tar.gz Collecting pylint-plugin-utils>=0.5 (from pylint-django) Using cached https://files.pythonhosted.org/packages/5c/94/2f1a7a2468c42be1a57520e0a85953c5cef5f0672c5081c5e66f8d4a7d86/pylint-plugin-utils-0.6.tar.gz Collecting pylint>=2.0 (from pylint-django) Could not find a version that satisfies the requirement pylint>=2.0 (from pylint-django) (from versions: 0.15.2, 0.16.0, 0.18.0, 0.18.1, 0.19.0, 0.20.0, 0.21.0, 0.21.1, 0.21.2, 0.21.3, 0.22.0, 0.23.0, 0.24.0, 0.25.0, 0.25.1, 0.25.2, 0.26.0, 0.27.0, 0.28.0, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.4.0, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.6.0, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.7.0, … -
Multiple Choice Forms with Django
I'm new with Django and am trying to write the form, views, and templates code where a customer selects multiple choices and submits those, with random results from a database. I am struggling with the structure of the code. I am pretty sure I need CheckboxSelect Multiple, MultipleChoiceField or ModelMultipleChoiceField. The Django website discusses both but doesn't provide example templates as to how the code is structured. I am creating a questionnaire, that consists of selecting activity categories via various buttons, like a checkbox list, then based on that, a list of activities would populate on a different page - these activities would be random. Any help would be greatly appreciated. -
Celery doesn't return or fail when calling apply_async. Works with celery_beat
I have a problem with calling celery tasks with apply_async. I have in settings.py: CELERY_BROKER_TRANSPORT_OPTIONS = {'confirm_publish': True} CELERY_BROKER_URL = pyamqp://un:pw@app-rabbitmq:5672 CELERY_TASK_QUEUES = ( Queue('default', Exchange('default', type='direct'), routing_key='default'), Queue('email', Exchange('email', type='direct'), routing_key='email'), ) CELERY_TASK_ROUTES = { 'core.services.CoreSendEmailTaskService.*': { 'exchange': 'email', 'routing_key': 'email' }, } ELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_DEFAULT_QUEUE = 'default' CELERY_TASK_ACKS_LATE = True CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_EXPIRES = 600 CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND = env('CELERY_RESULT_BACKEND_URL') //redis://app-redis:6379/3 CELERY_RESULT_PERSISTENT = False CELERY_WORKER_TASK_TIME_LIMIT = 65 CELERY_WORKER_TASK_SOFT_TIME_LIMIT = 60 CELERY_WORKER_HIJACK_ROOT_LOGGER = False In project_config/celery_config/tasks/__init__.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app __all__ = ('app',) and in project_config/celery_config/tasks/celery.py: class CeleryApp(celery.Celery): def on_configure(self): sentry_dns = os.environ.get('DJANGO_SENTRY_DNS', None) if sentry_dns and os.environ.get('ENVIRONMENT', 'local') == 'production': client = raven.Client( sentry_dns ) register_logger_signal(client) register_signal(client) app = CeleryApp('tasks') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() class CeleryTasksConfig(AppConfig): name = 'project_config.celery_config.tasks' verbose_name = 'Celery Tasks' def ready(self): app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() The weird thing is that the task executes on staging and production but locally it doesn't. Also locally when scheduled with beat the task runs normally. -
how can get values in time period Django and calculated
**i need to get and calculates values in between time period with Django function the data base will be as below : Case(1) start_time = 01-11-2019 end_time = 15-12-2019 rate = 35.00 Case(2) start_time = 16-12-2019 end_time = 31-12-2019 rate = 50.00 i need function to calculate the rate as following : user will request the period from 13-12-2019 till 18-12-2019 rate calculated [(13, 14, 15 December) = 35+35+35 = 105] + [(16, 17 , 18 December = 50+50+50 = 150] with total rate finally 255** class Items(models.Model): name = models.CharField(max_length=200, db_index=True) class Item(models.Model): name = models.ForeignKey(Items, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() rate = models.DecimalField(max_digits=3, decimal_places=2) -
Django formset creating extra empty forms on GET and POST request?
I am learning to implement formset and I am using the django-formset plugin on the client side to dynamically add or remove forms. Now, here is my problem, I notice the extra empty form also gets submitted whenever I submit the formset due to which the updated value never passes validation as there is one empty form that gets submitted. What can I do such that the empty form is ignored and only the changed field value gets submitted for validation. def form_valid(self, form): context = self.get_context_data() print(context,type(context)) titles = context['formset'] self.object =form.save() if titles.is_valid(): if titles.has_changed(): print('title has changed') titles.instance = self.object titles.save() class SkillForm(forms.ModelForm): class Meta: model = Skill fields=('skill_name','level_of_proficiency',) SkillFormSet = inlineformset_factory( UserProfile, Skill, form=SkillForm, fields=['skill_name', 'level_of_proficiency'], can_delete=True,extra=1,max_num=5 ) -
Heroku Django setup install_requires from github
I have a heroku project that is trying to install a Django reusable app using pip install -r requirements.txt (it's not the exact command from the official heroku/python buildpack, but it's basically doing that). The problem is that my Django reusable app has a requirement itself, from a Github public repository. A few answers in pip install dependency links point to: The dependency-links syntax being not compatible with pip 19 The new syntax (i.e. package @ git+protocol://...) of course not being compatible with older versions of pip. My Django project can be deployed in different ways: Heroku, local, Docker (dev and prod). Most of these deployment methods have the latest version of pip. Heroku's python buildpack has Pip 9.0.2 My other deployment methods have Pip 19, so they have incompatibilities in the way they read requirements, and I can't have a method that works for both. For older versions of pip, I do in my setup.py: setup( # [...] install_requires=[ "my_package == x.y.z" ], dependency_links=["git+https://github.com/account/package/tarball/master#egg=my_package-x.y.z"] ) Whereas for Pip 19, I do: setup( # [...] install_requires=[ "my_package @ git+https://github.com/company/package.git" ], ) I tried forking the repo and just increasing the version to pip's latest version. It does work, except for … -
Write to file and then send it via api
I have a retrieve api which receives a pk and then i want to: retrieve from database the record Create a file from a Binary column Send back the file that is created. So i have the following code which works, but i am not sure if its the best way, because i am creating the file and then i am going back to the file system in order to retrieve it with widget_bundle = open(test+'.js', 'rb'). Is there a better way to send it as i have it and not read it again?. def retrieve(self, request, pk): try: ts = Test.objects.get(code=pk) except Test.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) with open(ts.code+'.js', 'w') as filetowrite: filetowrite.write(str(bytes(widget.data), 'utf-8')) try: file = open(ts.code+'.js', 'rb') except Exception as e: pass response = HttpResponse(FileWrapper(file), content_type='application/javascript') -
django-treebeard Node in a foreign key or many to many field: show tree visually correct?
Is there an easy solution for having a visually correct tree representation, when using a treebeard Node based model in a foreign key and/or many to many field? As far as I can tell for now, the tree is show as a flat list, but in the correct order. Also, I cannot find any specific widget or formfields, in the treebeard source and docs. Last, some research shows, that for example django-cms uses it's own solution, just prepending some white space, according to the node's depth. See django-cms source Any suggestions welcome. -
Foreign key field not POSTing on Django REST
So, i'm doing an API for a to-do task manager, and in this api i have a lot of tables that are related to one another (a Project belongs to a Client, a Client is a Person that belongs to a City, and so on) and i hope that by learning how to fix the example below, i'll be able to fix the rest of the tables, that have a similar problem. My problem is: a Person belongs to a City (that already exists), so one of the fields of Person is a ForeignKey to City, that i believe should be a Integer, the city id (Person lives in 1 city, City can home N people). But i can't get it to work. On the django /admin site, it all works perfectly. I can create the Person with his info and theres a select box with a list of every City and it works great. But when i try to POST using Postman or even the /api site, there used to be no field for the City id, now after googling and trying everything, i somehow added the City id field, but can't get it to work. The current problem … -
How do I open a url in selenium web driver using Django?
I am passing this URL(https://www.facebook.com/) through Django to selenium web driver. Selenium is able to open the web browser through: URL=https://www.facebook.com/ browser = webdriver.Chrome(executable_path='C:\Himanshu\Python Work\chromedriver_win32\chromedriver.exe') browser.get(URL) but the URL field is getting blank. Error Message DevTools listening on ws://127.0.0.1:65487/devtools/browser/2aec903c-0b33-4c63-89f7-a766de4a99af ['https://www.facebook.com/ '] Internal Server Error: /get-server Can anybody tell me how to do it? I am using the Django, selenium along with python first time. Any lead will be appreciated. -
How to paste html tag in django view into javascript - typehead
I am trying to paste HTML tag {{ users }} into javascript function, but I am doing something wrong. If i try to put on site, it works fine but if I paste to javascript it wont work. Under that tag is a list of users something like ['administartor', 'admin']. I am try to paste into javascript Typehead, so it will help me to find the user faster, like here it is for states: https://codepen.io/jonvadillo/pen/NrGWEX I already tried to puts there like calling val, but it is not working <script type="text/javascript"> var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push(str); } }); cb(matches); }; }; var states = $('#has_paid_plan').val(); $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', source: substringMatcher(states) }); </script> i also try to put there in the simple way, … -
I am trying to deploy my Django project to Heroku but an error regarding my SECRET_KEY keeps appearing
I am deploying an e-commerce project to Heroku and seem to be running into constant issues and errors. My latest error surrounds the below traceback: 2019-11-11T13:35:34.080363+00:00 heroku[web.1]: State changed from crashed to starting 2019-11-11T13:35:40.020789+00:00 heroku[web.1]: Starting process with command `gunicorn fancyfetish.wsgi:application --preload --workers 1` 2019-11-11T13:35:42.589255+00:00 heroku[web.1]: State changed from starting to crashed 2019-11-11T13:35:42.460008+00:00 app[web.1]: Traceback (most recent call last): 2019-11-11T13:35:42.460049+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in <module> 2019-11-11T13:35:42.460136+00:00 app[web.1]: sys.exit(run()) 2019-11-11T13:35:42.460148+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in run 2019-11-11T13:35:42.460262+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2019-11-11T13:35:42.460273+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 219, in run 2019-11-11T13:35:42.460434+00:00 app[web.1]: super().run() 2019-11-11T13:35:42.460438+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 72, in run 2019-11-11T13:35:42.460565+00:00 app[web.1]: Arbiter(self).run() 2019-11-11T13:35:42.460571+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 58, in __init__ 2019-11-11T13:35:42.460689+00:00 app[web.1]: self.setup(app) 2019-11-11T13:35:42.460692+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 118, in setup 2019-11-11T13:35:42.460823+00:00 app[web.1]: self.app.wsgi() 2019-11-11T13:35:42.460827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2019-11-11T13:35:42.460978+00:00 app[web.1]: self.callable = self.load() 2019-11-11T13:35:42.460981+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2019-11-11T13:35:42.461083+00:00 app[web.1]: return self.load_wsgiapp() 2019-11-11T13:35:42.461087+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2019-11-11T13:35:42.461204+00:00 app[web.1]: return util.import_app(self.app_uri) 2019-11-11T13:35:42.461207+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 331, in import_app 2019-11-11T13:35:42.461388+00:00 app[web.1]: mod = importlib.import_module(module) 2019-11-11T13:35:42.461392+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2019-11-11T13:35:42.461529+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-11-11T13:35:42.461542+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import … -
Unwanted behaviour of a html template when in use with django
I downloaded a free html/css/js template and wanted to run it on django. After fixing some of the directories for static files I managed to get it running. My problem is that some of the sliding elements are unusually extended and instead of being let's say 50px in height, they cover half of the page with nothing but blank. These elements also behave weirdly. If I inspect the element, for some reason all the proportions go back to normal, however when I click and drag the inspect element window up and down, the weirdly behaving elements extend and retract with the inspect element window. I'm relatively new to all this so I'm not even sure whether I should be looking through the html, css or the js files in order to find out why it does that. Could someone point me in the right direction please? This is what it looks like if I just run the html file Here I'm running it on django and you can see the elements extended Opening the inspect element window fixes the proportions Moving the inspect element window also moves the extended elements -
Check database element isn't empty in HTML with Django
I have some display in a website I'm working on that works correctly but shows me everything even if some elements are null. I'm using Django and have the below model with which I want to change the display: class Exchange(models.Model): YEAR_CHOICE = ((4, '4TC'), (5, '5TC')) SEMESTER_CHOICE = ((1, 'S1'), (2, 'S2')) GRADE = ((1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5')) ID = models.AutoField(primary_key=True) Year = models.IntegerField(default=-1, choices=YEAR_CHOICE) StartDate = models.DateField() EndDate = models.DateField() Semester = models.IntegerField(default=-1, choices=SEMESTER_CHOICE) Visa = models.BooleanField(default=False) Comment = models.CharField(max_length=1000, null=True, blank=True) VisaMonths = models.IntegerField(null=True, blank=True, default=-1,) VisaWeeks = models.IntegerField(null=True, blank=True, default=-1,) VisaDays = models.IntegerField(null=True, blank=True, default=-1) Rent = models.IntegerField(null=True, blank=True, default=-1) MonthlyExpenses = models.IntegerField(null=True, blank=True, default=-1) NightLifeGrade = models.IntegerField(null=True, blank=True, default=-1,choices=GRADE) CulturalLifeGrade = models.IntegerField(null=True, blank=True, default=-1,choices=GRADE) Security = models.IntegerField(null=True, blank=True, default=-1,choices=GRADE) Student = models.ForeignKey('Student', on_delete=models.CASCADE) University = models.ForeignKey('University', on_delete=models.CASCADE) def __str__(self): return str(self.ID) In my HTML page, I have the following: <button class="accordion">Commentaires</button> <div class="panel"> {% for e in ex %} <h5>{{e.Student.Name}} {{e.Student.Surname}}, parti en {{e.StartDate}} ({{e.Year}}A {{e.Student.INSADepartement}} S{{e.Semester}})</h5> <blockquote>{{e.Comment}}</blockquote> {% endfor %} </div> I would like to only display the information in the button if e.Comment isn't null. I tried adding {% if(e.Comment) %} ... {% endif %} in the … -
Getting Error: did you install mysqlclient? even though mysqlclient is installed on MacOS when trying to access the database in django
I am using MacOS 10.13.1 and python version 3.7.2. I used pip3 install mysqlclient to install mysqlclient and it was successful: MacBook-Air:~ user$ pip3 install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f8/9b/5db9a03e2088a87c26e3e4d4c7f7e8f4c2dbae610f9521cdfac15755a795/mysqlclient-1.4.5.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... done Created wheel for mysqlclient: filename=mysqlclient-1.4.5-cp37-cp37m-macosx_10_9_x86_64.whl size=56101 sha256=3c1ab2eed45ecf064e60ceda15f2d85f4b01367e7c7e6ed887f483732b9d5e8c Stored in directory: /Users/user/Library/Caches/pip/wheels/26/51/0c/3b9ab7013c539c744cddb55989ef494779fa08e8b273ab5ddf Successfully built mysqlclient Installing collected packages: mysqlclient Successfully installed mysqlclient-1.4.5 pip3 list confirms that version 1.4.5 of mysqlclient has been installed. However, when running python3 manage.py makemigrations in the directory containing my project, this error comes up: MacBook-Air:averages user$ python3 manage.py shell Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models … -
Django remove duplicates from .values_list query while preserving order
I have a model say MyModel which contains a CharField type. The model has a default meta ordering which should be preserved. I am using the following query to get the list of types - MyModel.objects.all().values_list('type', flat=True).distinct() However, the types are getting repeated. I can do .order_by('type').distinct() but that will change the ordering which I don't want. Is there any way to get the list of types in order without manually creating a list in python? Alternative faster solutions are also welcome. Django version - 1.11 -
How could check content of td without spaces and lines
I have a a table with dynamic value of td, some of td will be empty and some will has value, the empty td I want there background red, and filled td should be green I tried to do that with css by : td:empty { background-color: red; } the issue that I faced is empty td has only spaces & lines content that spaces make td:empty totally useless in other words the css reading there is a content in td tag, but in fact that content is just spaces and lines which is fake content how could fix his problem ? --- update --- <td> {% for mission in missions %} {% if mission == 'MISSION' %} {{ mission }} <!-- filled cell - this should be green background --> <br> {% endif %} <!-- empty cell - this should be red background --> {% endfor %} </td> -
Does Django's 'exact' field lookup perform a case-insensitive search?
From what I read on the Django manual, I thought that the exact field lookup would perform a case-SENSITIVE search, yet, when I do this FormZBaseElementExtraLabel.objects.filter(label__exact='his6') I get the following output <QuerySet [<FormZBaseElementExtraLabel: HIS6>]> clearly not case-sensitive, and in fact identical to the default filter or iexact. Any ideas as to what could be the problem? Thank you -
Fix: InvalidAlgorithmError: The specified alg value is not allowed while trying to decode encoded jwt token in Python
I'm trying to decode a token I have received from an authorization service. The problem is when I try to decode it I get InvalidAlgorithmError: the specified alg value is not allowed. When you look at the following image below. I can decode the token from the jwt.io site and view the payload. I'm using the PyJwt library. Below you will find my implementation. Decoded token in the jwt.io site Implementation import jwt encoded = "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJERVZFTE9QRVIiLCJ1c2VyZnVsbG5hbWUiOiJFcmljIE0gS2FyaW1pIiwidXNlcm5hbWUiOiJlcmljIiwidXNlcmlkIjoiMjkiLCJleHAiOjE1NzM0ODE0MzIsImlzcyI6IkVyaWMiLCJhdWQiOiJSZWFkZXJzIn0.tTQckIZGYNHE667NXrxT4YwT4DNZ01u3P3b3IMFyWR4" key = "somekeyrequiredtodecode" decoded = jwt.decode(encoded,key, algorithms=['HS256']) Full StackTrace ~/Desktop/APIs/ncc-api/env/lib/python3.6/site-packages/jwt/api_jws.py in decode(self, jwt, key, verify, algorithms, options, **kwargs) 154 elif verify_signature: 155 self._verify_signature(payload, signing_input, header, signature, --> 156 key, algorithms) 157 158 return payload ~/Desktop/APIs/ncc-api/env/lib/python3.6/site-packages/jwt/api_jws.py in _verify_signature(self, payload, signing_input, header, signature, key, algorithms) 214 215 if algorithms is not None and alg not in algorithms: --> 216 raise InvalidAlgorithmError('The specified alg value is not allowed') 217 218 try: InvalidAlgorithmError: The specified alg value is not allowed In [7]: v = jwt.decode(key, s, algorithms=['HS256']) --------------------------------------------------------------------------- InvalidAlgorithmError Traceback (most recent call last) <ipython-input-7-a9465dfcaa4b> in <module> ----> 1 v = jwt.decode(key, s, algorithms=['HS256']) ~/Desktop/APIs/ncc-api/env/lib/python3.6/site-packages/jwt/api_jwt.py in decode(self, jwt, key, verify, algorithms, options, **kwargs) 90 91 decoded = super(PyJWT, self).decode( ---> 92 jwt, key=key, algorithms=algorithms, options=options, **kwargs 93 ) … -
Can't find files in django
I'm trying to work with some json and csv files in my django project but it never found they. I created a static folder and inside it I have create a new one called data with the different files. But when I call it, the message is always the same, it can't found the path of my files. [Errno 2] File b'data/data.csv' does not exist: b'data/data.csv' Inside settings.py I have this: STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR, 'static'), ] Somebody knows what I'm doing wrong? An example how I call my csv file: def dataframex(): data_csv = pd.read_csv('data/data.csv') print(data_csv) Thank you! -
How to remove all data about users from database from heroku server?
I created many test accounts in my heroku server. Now they all have empty columns, and therefore do not work. And now I want to remove all data about existing users/accounts, including superuser, then recreate. How I can do this? -
Sending the contact form to PostgreSQL DB and email using Django
I've made a contact form using Django, I would like the information entered in the contact form to be sent to an email and database. The code for sending the information to the email id is given below which is successful but I am having issues in adding the code to save it in the PostgreSQL database. I am new to python, so, any help would be very much appreciated. Thanks urls.py from django.urls import path from.import views urlpatterns = [ path('email/', views.email, name='email'), path('success/', views.success, name='success')] forms.py from django import forms # our new form class ContactForm(forms.Form): what_about = forms.CharField(required=True) contact_email = forms.EmailField(required=True, max_length=250) content = forms.CharField( required=True, widget=forms.Textarea) Name = forms.CharField(required=True) Phone_Number = forms.CharField(required=True) views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data subject = form.cleaned_data['what_about'] from_email = form.cleaned_data['contact_email'] message = 'contact_email: "{}"\n Phone_Number: "{}"\n Name: "{}"\n content: "{}"'.format(cd['contact_email'], cd['Phone_Number'], cd['Name'], cd['content']) try: send_mail(subject, message, from_email, yourmail@gmail.com, fail_silently='False') except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your … -
Integrity Error in Django where project has two user table?
I am facing a problem in Django admin panel, when I want to add or delete or update any value I got this error, django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (db_name.django_admin_log, CONSTRAINT django_admin_log_user_id_c564eba6_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') In my project, there are two user tables, one that was created in the first migration after that I create a custom user model. It works fine in local but facing problems in the server. As Django used InnoDB by default all my table is in InnoDB (I find some solution like this if I convert the table engine to MyISAM it'll solve the problem), I have plenty of data in the database and I can't do any test operation in it.