Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is the Amadeus traditional flight search (flight offers) API missing scheduled flights? e.g. EasyJet, Wizz Air, TUI?
I am using the test environment and checking on the results I get. On certain itineraries I get all scheduled flights. However, I can't seem to be able to output any EasyJet, Wizz Air, TUI flights. Those are only the ones I have noticed, I presume there's more missing. I double check my results against skyscanner.com. Therefore, if an itinerary only has an EasyJet scheduled flight, then I get no results. Here's an example; import requests from amadeus import Client, ResponseError amadeus = Client( client_id = 'xxxxx', client_secret = 'xxxxx', ) flight_list = [] try: response = amadeus.shopping.flight_offers.get( origin = 'LTN', destination = 'ATH', departureDate = '2020-02-13', adults = 1, nonStop = 'true', currency = 'GBP', ) for resp in response.data: for offer in resp['offerItems']: flt_data = { 'From' : offer['services'][0]['segments'][0]['flightSegment']['departure']['iataCode'], 'To' : offer['services'][0]['segments'][0]['flightSegment']['arrival']['iataCode'], 'Departure Date' : offer['services'][0]['segments'][0]['flightSegment']['departure']['at'][0:10], 'Departure Time' : offer['services'][0]['segments'][0]['flightSegment']['departure']['at'][11:19], 'Arrival Date' : offer['services'][0]['segments'][0]['flightSegment']['arrival']['at'][0:10], 'Arrival Time' : offer['services'][0]['segments'][0]['flightSegment']['arrival']['at'][11:19], 'Price' : offer['price']['total'][0:], 'Terminal' : offer['services'][0]['segments'][0]['flightSegment']['departure']['terminal'], 'Airline' : offer['services'][0]['segments'][0]['flightSegment']['carrierCode'], 'Flight No.' : str(offer['services'][0]['segments'][0]['flightSegment']['carrierCode']) + ' ' + str(offer['services'][0]['segments'][0]['flightSegment']['number']) } flight_list.append(flt_data) print(flight_list) except ResponseError as error: print(error) With the following output; [origin/destination/date(s) combination] No fare found for requested itinerary I can confirm that the script runs fine when none of the … -
How to make speficic validation of a django form
I have a form based on a model Randomization I want to add specific validation on a field I try to add a 'else' just after the if form.is_valid() because I understand that I must manage the case when the form is not valid but how? views.py: @login_required def randomisation_edit(request): if request.method == "POST": form = RandomisationForm(request.POST or None) if form.is_valid(): randomisation = form.save() # print('Patient code :',randomisation.ran_num) return redirect('randomization:confirmation', pk = randomisation.pk) else: #TODO else: form = RandomisationForm(initial = {'ran_num': request.GET['patient']}) preincluded = Preinclusion.objects.get(pat_num = request.GET['patient']) return render(request, 'randomization/randomisation_edit.html', {'form': form, 'preincluded': preincluded}) forms.py class RandomisationForm(forms.ModelForm): ... class Meta: model = Randomisation # Tous les champs sauf les champs de log et les champs TB treatment et Drug batch number fields = ('ran_num','ran_dat','ran_inv','ran_pro','ran_pro_per','ran_crf_inc','ran_tbc','ran_crf_eli','ran_cri','ran_sta','ran_vih',) def clean_ran_crf_inc(self): data = self.cleaned_data['ran_crf_inc'] if int(data) == 0: raise forms.ValidationError("Ce critère est obligatoire pour la randomisation") return data I have a error 'local variable referenced before assignment' because of my views: when a validation error raise, the context 'preincluded' is not yet defined whereas I try to render it -
Django Whitenoise with compressed staticfiles
I'm not able to get my django project to run with whitenoise and compressed staticfiles (including libsass). In links below, I read that it's only possible by offline compression of needed staticfiles. But when I started up the docker container, running compress command docker-compose -f production.yml run --rm django python manage.py compress gives me error: ValueError: Missing staticfiles manifest entry for 'sass/app.scss' While trying to request the site gives me following error (as expected?): compressor.exceptions.OfflineGenerationError: You have offline compression enabled but key "..." is missing from offline manifest. You may need to run "python manage.py compress" Settings are as follows (build with cookiecutter-django, see link for complete code base below): STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_FINDERS += ["compressor.finders.CompressorFinder"] COMPRESS_PRECOMPILERS = [("text/x-scss", "django_libsass.SassCompiler")] COMPRESS_CACHEABLE_PRECOMPILERS = (("text/x-scss", "django_libsass.SassCompiler"),) COMPRESS_ENABLED = env.bool("COMPRESS_ENABLED", default=True) COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage" COMPRESS_ROOT = STATIC_ROOT COMPRESS_URL = STATIC_URL COMPRESS_OFFLINE = True So after searching the internet for 1 day; I'm stuck... Thx for any help or suggestion! Code base: https://github.com/rl-institut/E_Metrobus/tree/compress which is build with cookiecutter-django-foundation including the following changes to config/setttings/production.py: COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage" # Instead of pre-set "storages.backends.s3boto3.S3Boto3Storage" COMPRESS_ROOT = STATIC_ROOT # Just in case … -
Error from rest_framework.exceptions import ApiException ImportError: cannot import name 'ApiException' running python manage.py
''' I am not able to import from rest_framework.exceptions import ApiException ''' ''' This is my Exception.py: ''' class APIException(Exception): status_code = status.HTTP_500_INTERNAL_SERVER_ERROR default_detail = _('A server error occurred.') default_code = 'error' def __init__(self, detail=None, code=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code self.detail = _get_error_details(detail, code) def __str__(self): return self.detail def get_codes(self): return _get_codes(self.detail) def get_full_details(self): return _get_full_details(self.detail) error while running : python manage.py makemigrations networscanners Traceback (most recent call last): File "manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "D:\Python36-32\lib\site-packages\django\core\management\__init__.py", li ne 381, in execute_from_command_line utility.execute() File "D:\Python36-32\lib\site-packages\django\core\management\__init__.py", li ne 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 23, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 61, in execute self.check() File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 90, in check include_deployment_checks=include_deployment_checks, File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 77, in _run_checks return checks.run_checks(**kwargs) File "D:\Python36-32\lib\site-packages\django\core\checks\registry.py", line 7 2, in run_checks new_errors = check(app_configs=app_configs) File "D:\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, i n check_url_config return check_resolver(resolver) File "D:\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, i n check_resolver return check_method() File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 400, in check for pattern in self.url_patterns: File "D:\Python36-32\lib\site-packages\django\utils\functional.py", line 80, i n __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 585, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "D:\Python36-32\lib\site-packages\django\utils\functional.py", line … -
how to send json and images as django response?
currently, I send JSON data using Django rest API, now I have to add images to this data (60 images per request along with the other data) I thought about using sendfile to achieve that but I'm not quite sure that this is a possibility at all. I looked for other options but found nothing. @api_view(['GET']) def get_data(request): collage_list = [] try: for i in range(30): collage_list.append({"focal_brand":{"collage_id": 7,"brand_name":"name"}) except Exception as e: print(e) return JsonResponseNotFound() return JsonResponse(status=200, data=dict(respone=collage_list) can I send both (the JSON data and the files) together? what is the best way to do that? thanks -
Validate body of a POST request in django
I have a view in django that sign's up a client and I have a model for the client and a form that looks like this: from django.forms import ModelForm from api.models.client import Client class SignUpForm(ModelForm): class Meta: model = Client fields = ['first_name', 'last_name'] In my view I would like to validate the data in the request but my problem is that the paramters in the request are camelCase and not snake_case so when I try to validate the data it doesn't work. def sign_up(request): body = json.loads(request.body) form = SignUpForm(body) print(form.is_valid()) return HttpResponse('this is a test response') Is there a clean way of making this work? Also is this the correct way to do what I'm trying to do? -
How to add conditional fields programatically to a wagtail page type?
I’m trying to add a conditional field to a wagtail page type model, the conditional fields may look like as shown in the below image. There are two fields, Question and Answer. The Answer field values should be displayed with respect to the selection of the Question field If we select Toyota from Question then Camry and Land Cruiser should be displayed in the Answer drop down, if we select Honda then Civic and Accord should be displayed in the Answer. In blocks.py I have two classes which are responsible for Questions and Answers fields respectively class ConditionsQuestionBlock(blocks.ChooserBlock): widget = Select class Meta: icon = "question" @cached_property def target_model(self): return Question @cached_property def field(self): return forms.ModelChoiceField( queryset=Question.objects.all(), widget=self.widget, required=self._required, #validators=self._validators, help_text=self._help_text, ) def value_for_form(self, value): if isinstance(value, User): return value.pk else: print("selected q:",value) selectedqval=value print("selected qvalue:",selectedqval) return value class ConditionsAnswerBlock(blocks.ChooserBlock): widget = Select class Meta: icon = "question" @cached_property def target_model(self): return Choice @cached_property def field(self): choice=Choice.objects.all() return forms.ModelChoiceField( queryset=choice, widget=self.widget, required=self._required, ) def value_for_form(self, value): if isinstance(value, User): return value.pk else: return value Now irrespective of the Question selection I'm getting all the Answer options -
How to return custom JSON output in Django REST Framework
I am trying to return custom json with the following structure [ { 'yesterday': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}], { 'today': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}] { 'tomorrow': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}] ] The following is my code: serializer.py class GamesSerializer(serializers.Serializer): class Meta: model = AllGames fields = ('teams', 'start_time', 'pick', 'score', 'odds', 'won_or_lost', 'date') class GamesViewSet(viewsets.ModelViewSet): today_date = date_picker yesterday = AllGames.objects.filter( date=today_date(-1)).order_by('start_time', 'teams') today = AllGames.objects.filter( date=today_date(0)).order_by('start_time', 'teams') tomorrow = AllGames.objects.filter( date=today_date(1)).order_by('start_time', 'teams') queryset = [yesterday, today, tomorrow] serializer_class = GamesSerializer Current Output [ {}, {}, {} ] How can I modify my GamesSerializer to return the custom output as shown above. -
Why I'm getting a 500 internal error when validate Recaptcha V2, Django?
I'm using Django and when I want to submit my contact form, i have to validate my google recaptcha. It's working locally but in production I have a 500 internal error and the mail is not sent when the form is correctly fill with the correct captcha. I added my domain name to the google recaptcha website... I have correct secret key... Again it's working locally -
Form data not saving when use DateField
I am saving the form data into database but no success. Actually when I include DateField in forms.py, its not saving any data but when excluded this field, it works fine. Any possible reason for this problem.? Model: class CoWorker_Data(models.Model): name = models.CharField('Name', max_length=50, help_text='Co-worker name.') email = models.EmailField('Email', help_text='Co-worker email.') address = models.TextField('Address', help_text='Co-worker address.') phone = models.CharField('Phone Number', max_length=20, help_text='Co-worker phone number.') companyName = models.CharField('Company Name', max_length=80, help_text='Co-worker company name.', null=True, blank=True) workingLocation = models.CharField('Working Location', max_length=50, help_text='Co-worker working ' 'location.') workingShift = models.CharField('Working Shift', max_length=50, help_text='Co-worker working shift.', default='') workingSpace = models.CharField('Working Space', max_length=50, help_text='Co-worker working space.', default='') teamMembers = models.CharField('Team Members', max_length=15, help_text="Co-Worker's Team Size.", default='') coworkerPicture = models.ImageField('Co-Worker Picture', upload_to='../media/images/co-woker-pictures' , help_text='Co-worker Picture.', default='', null=True, blank=True) joiningDate = models.DateField('Joining Date', help_text='Joining Date of Co-worker', auto_now_add=False,) Form class addCoWorkerForm(forms.ModelForm): teamMembers = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control formInput', 'placeholder': 'Team Members', 'required': 'True' })) coworkerPicture = forms.ImageField(widget=forms.FileInput(attrs={ 'class': 'form-control formInput', })) joiningDate = forms.DateField(widget=forms.DateInput(attrs={ 'class': 'form-control formInput', 'id': 'datePicker', })) View def Coworkers(request): if request.method == 'POST': form = addCoWorkerForm(request.POST, request.FILES) if form.is_valid(): u = form.save() messages.success(request, 'Co-Worker added successfully.') return redirect('admin/co-workers') else: form = addCoWorkerForm(request.GET) please suggest best solution...? -
How to implement 'others' in django models choices-charfield
was wondering if anyone here know of a good implementation for 'others' choice (where user can input custom text) in django models multi-select .... say for instance i have a multiple choice model field 'options' with pre-set a and b choices. options = models.CharField ( max_length=2, choices=[(a,'a'), (b,'b')], default=a, ) What if I want the user to be able to select a choice 'others' and thereon key in his custom text i.e. 'd' The only way I can think of really, is to use a different field , say options_custom (without getting into the specifics of the model etc...the dummy snippet below is just for discussion sake) options = models.CharField ( max_length=2, choices=[(a,'a'), (b,'b'), ('others', 'others')], default=a, ) # added this.. options_custom = models.CharField(max_length=2, blank=True, verbose_name="Input custom text here" ) # and put a conditional... if others then return options_custom if choices == 'others': return options_custom # something like this.... What do you think? I'd appreciate any pointers. -
Django charfield regex
Consider a charfield with a max_length of 5. I want to put hours and minutes in this CharField like HH:MM. I don't want to use the models.TimeField as it stores the time, not the amount hours and minutes. I want my CharField to hold, let's say, 8:45 (8hrs and 45minutes) which is why I want to add a regex validator that makes sure that the number before the colon : is less than 24 and the number after it less than 60. How would I do that in regex? Thank you for your time. -
UndefinedError: 'url_for' is undefined; while using Jinja2 in Django
I'm trying to use Jinja2 templating language with Django. While trying to render a template I got the error "jinja2.exceptions.UndefinedError: 'url_for' is undefined". 'url_for()' works absolutely fine when used with templates in Flask Applications. The Traceback is as follows: File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/views.py" in index 10. return render(request,"login_auth/index.html") # index.html will be welcome screen File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 62. return template.render(context, request) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/django/template/backends/jinja2.py" in render 71. return self.template.render(context) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/asyncsupport.py" in render 76. return original_render(self, *args, **kwargs) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/environment.py" in render 1008. return self.environment.handle_exception(exc_info, True) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/environment.py" in handle_exception 780. reraise(exc_type, exc_value, tb) File "/home/ParserMouth/folder1/folder2/ProjectName/myvenv/lib/python3.6/site-packages/jinja2/_compat.py" in reraise 37. raise value.with_traceback(tb) File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/index.html" in top-level template folder2 1. {% extends "login_auth/base.html" %} File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/base.html" in top-level template folder2 12. {% block style %} {% endblock %} File "/home/ParserMouth/folder1/folder2/ProjectName/ProjectName/login_auth/jinja2/login_auth/index.html" in block "style" 4. <link rel="stylesheet" href="{{ url_for('static/login_auth', filename='index_stl.css') }}"> Exception Type: UndefinedError at / Exception Value: 'url_for' is undefined I want to know how to solve this problem. Thanks in advance. -
How to create proxy-http-server
I write a proxy-http-server on the Django using django-revproxy. re_path(r'^(?P<path>.*)$', ProxyView.as_view(upstream='https://example.com')) It works. When I open 127.0.0.1:8000 I get content of example.com. But I have a two nuance: How can I change text on the page (for example, change every word, length which equals 6 letters) How can I change links on the page (at current moment all links go to the example.com, but not to 127.0.0.1:800) -
django-tables2 - show all per page
Good afternoon, im using Django-tables2, I know in the query string I can set per_page and have used the below template tag to create some urls {% querystring "per_page"=20 %} however is it possible to show all items per page via a url? ive tried using -1 and 0 but it does not work, the only thing I can think to is put a ridiculous number like a billon which works, but I dont think thats a clean implementation? Thanks -
django-tables2/django-filter - pagination with filterclass
Good Afternoon, I am using a custom django-filter in django-tables2 to search all fields with a single input. Ive just noticed that when I search I lose my pagination menu. this is the link to the filter code https://spapas.github.io/2016/09/12/django-split-query/ here's my filter class SiteFilterEx(django_filters.FilterSet): ex = django_filters.CharFilter(label='Ex filter', method='filter_ex') search_fields = ['location', 'bgp_as', 'opening_date','town','postcode'] def filter_ex(self, qs, name, value): if value: q_parts = value.split() # Use a global q_totals q_totals = Q() # This part will get us all possible segmantiation of the query parts and put it in the possibilities list combinatorics = itertools.product([True, False], repeat=len(q_parts) - 1) possibilities = [] for combination in combinatorics: i = 0 one_such_combination = [q_parts[i]] for slab in combination: i += 1 if not slab: # there is a join one_such_combination[-1] += ' ' + q_parts[i] else: one_such_combination += [q_parts[i]] possibilities.append(one_such_combination) # Now, for all possiblities we'll append all the Q objects using OR for p in possibilities: list1=self.search_fields list2=p perms = [zip(x,list2) for x in itertools.permutations(list1,len(list2))] for perm in perms: q_part = Q() for p in perm: q_part = q_part & Q(**{p[0]+'__icontains': p[1]}) q_totals = q_totals | q_part qs = qs.filter(q_totals) return qs class Meta: model = Site fields = ['ex'] form … -
How to show what changed in a model using Django simple-history?
I am using django-simple-history to track changes in a model. This is working fine. I can also create a view for the admin site. When I do not derive the class for the admin view from SimpleHistoryAdmin I get this history view showing what changed in the model under the column ACTION (last column). However, I cannot revert the values for the object to a previous time point. If I derive the admin view class from SimpleHistoryAdmin I can revert the instance but the history view changes and I no longer have the ACTION column. This makes this view almost useless since there is no way to tell what changes from one-time point to the other. So my question is: How can I have the column ACTION in the history view when I derive the admin view from SimpleHistoryAdmin? If by any chance this is not possible I will be happy by changing CHANGE REASON from None to the values in the column ACTION in the first image. -
How to fix UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 5: invalid continuation byte
I am trying to run a newly created environment on a server and get UnicodeDecodeError. Windows 7, 64-bit. I have created a virtual environment and directed code to the source folder. Here are django, python and virtualenv versions installed. I have tried installing older versions of django and python and got the same error. When searching for troubleshooting recommendations I only find articles related to .csv and pandas. Django==2.2.7 pytz==2019.3 virtualenv==16.7.7 PS: C:\Users\User\Dev\Selectia\src> python manage.py runserver Here is the output: Watching for file changes with StartReloader Performing system checks... System checkidentified no issues (0 silenced). November 05, 2019 - 12:02:31 Django version 2.2.7, using setings 'foodie.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREALK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self.args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54 in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 203, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 67, in __init__ super().__init__(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\socket.py", line 676, in getfqdn hostname, aliases, ipaddrs = … -
Django - How to create many to one relation
In my application there is many-to-one relation, such as one teacher can teach more than one subject. So in admin panel I can't simulate it. Can't add more than one subject: Here are my codes: models.py: class Subject(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) credit = models.IntegerField() class Teacher(models.Model): def __str__(self): return self.name name = models.CharField(max_length=100) email = models.CharField(max_length=100, null=True) chair = models.ForeignKey(Chair, on_delete=models.CASCADE) academic_degree = models.CharField(max_length=100) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) -
Django problem accessing Admin while my main DB is Mongo
my name is Víctor. I'm quite new using Django and Python and I'm working in a project that is yet started. Default Database is MongoDB where I have users and I can authenticate in the login page of the app. Now we installed 'helpdesk' app that is a ticketing system and we would like to use Admin that is disabled in our project. I added Admin app in Settings and Url but I dont have any access to any user. I tried to create a superuser with python manage.py createsuperuser but it gives me this error: TypeError at /admin/ int() argument must be a string, a bytes-like object or a number, not 'ObjectId' In django/contrib/auth we made some changes for example: def _get_user_session_key(request): # This value in the session is always serialized to a string, so we need # to convert it back to Python whenever we access it. if SESSION_KEY in request.session: return ObjectId(request.session[SESSION_KEY]) Where appears this ObjectId, it seems that Admin is trying to access user from MongoDB and not from helpdesk DB that is sqlite. Probably my problem is that I dont understand about mixing databases and accessing. I created a router with functions like: class RouterDB: … -
moving python backend to django for Yahoo Fiannce APİ
Hi i am good with Python but my Django skills is beginner. I developed a program in Tkinter as GUI but decided to put in Django. Here is my backend and GUI shorted: from tkinter import* import numpy as np import pandas as pd from scipy.stats import norm from pandas_datareader import data as wb from yahoofinancials import YahooFinancials The user insert ticker in input field and the variable helped to get ticker symbol through tickers = [self.entry_stock.get()] then i used the below to get stock's price yahoo_financials = YahooFinancials(tickers) new_data = pd.DataFrame() for t in tickers :new_data[t] = wb.DataReader(t, data_source ='yahoo', start = '2004-1-1')['Adj Close'] a = new_data[t] In Django i am confused how to convert input data to index symbol: <form class="ticker_area form-control-lg" method="POST"> {% csrf_token %} <input class="ticker_button" type="text" placeholder="Ticker" aria-label="Search"> <button class="btn btn-outline-warning btn-rounded btn-sm my-1" type="submit">OK</form> in backend the symbol= ['AAPL']which allow to get company data in such format. In tkinter i used `tickers = [self.entry_stock.get()] to get stock value and use further. But i do not know how how to make in Django the form to pass ticker data to this format `tickers = [self.entry_stock.get()] so that i can further use it to get price … -
Determine the source of the API request from which it is coming from?
How can I determine the source of the request? I am using django. For example, if I send a request from POSTMAN to some API like http://example/api/, I need to get POSTMAN as an answer. If I do the same from Chrome, I need to get Chrome as an answer. -
How to run javascript in view only after specific post request?
I am trying to run javascript code after specific post. I will explain what is happening. I got some forms on my page and checking which POST request is "released" I will make something. So I made this, it will change state of that specific object in database and reload the page. if request.method == 'POST': if 'acceptresults' in request.POST: t = Pools.objects.get(pk=Pools_id) t.Status = "Testing_closed" t.save() return HttpResponseRedirect('#') How am I able to run the specific javascript which could be call startConfetti(); and after 5 seconds call stopConfetti();. Can someone please help me? -
Edit the session inside Django form_valid gives "Object is not JSON serializable"
I'm using class based views in Django to create an entry in db. I want the saved object to be stored in session, so that it could be passed to the next view. My view looks like class CreateCommission(BaseContext, CreateView): # boring staff... model = Commissions def form_valid(self, form): object = form.save(commit=False) self.request.session['created_object'] = object return super().form_valid(form) This raise an Object of type Commissions is not JSON serializable error. What's wrong with that? -
OTP only login for Django
I would like to have OTP only for authentication. I read about django-otp and django-two-factor-auth but they are both for two-factor authentication. I read the examples in the github and unfortunately do not know if it is possible to make if OTP authenticated only based on limited experience. I was thinking about using native python and Javascript for this, but I guess decorators @login-required requires Django Login? I would also like to log the user activity with Matomodjango-analytics in the future. I am not sure if I have to use Django Login in order to track activities later. Thanks for your suggestion!