Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my dependent drop down disappearing upon submission?
I have a form with a dependent drop down. Whenever the form is submitted, only the first field is cleared, if the drop downs were filled out, they remain the same. I have the dependent dropdown set to appear only when there are options available, but after the form gets submitted with an option that has a secondary option, only the first dropdown renders, because it does not load the dropdown logic until you select a new option and go back to what you had. For a more visual understanding: This is the form when the page first loads When you select an option that has secondary options, the other dropdown appears After you select a Station and submit, the Employee # clears, but the other two remain, however, when the page reloads upon submission, it looks like this And when I look at the data that remained in the form, only the work area stayed, because the dependent dropdown does not load until you select another option from the drop down, and if you wanted to be able to see the Box Assembly options again, you'd have to click another option and then go back to Box Assembly (for … -
Mandatory many to many relationship in Django
Suppose I've a model Car (cars are not owned, may be shared by passengers) and a model Passenger (passenger includes the driver of the bus). The models are read/write able via DRF and admin interface. How can I enforce that each car has at least one passenger and potentially several passengers (mandatory many-to-many relationship)? -
Celery beat tasks not executing
I'm learning periodic tasks in Django with celery beat. But my tasks are not executing. my __init__.py file: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) my celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'new_todo_app.settings') app = Celery('new_todo_app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) my tasks.py file: from celery import Celery from celery import shared_task app = Celery('tasks', broker='pyamqp://guest@localhost//') @shared_task def progress_bar(): print("Executed every minute") and my settings.py file CELERY_BROKER_URL = 'amqp://localhost' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TIMEZONE = 'Asia/Baku' CELERY_ENABLE_UTC = True CELERY_BEAT_SCHEDULE = { 'progress-bar': { 'task': 'app1.tasks.progress_bar', 'schedule': 5.0, }, } I run celery beat worker by writing: #celery -A new_todo_app beat -l info celery beat starts, but tasks don`t execute.I tried DEBUG logging mode and I get: Configuration -> . broker -> amqp://guest:**@localhost:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%DEBUG . maxinterval -> 5.00 minutes (300s) [2019-12-04 19:35:24,937: DEBUG/MainProcess] Setting default socket timeout to 30 [2019-12-04 19:35:24,938: INFO/MainProcess] beat: Starting... [2019-12-04 19:35:24,975: DEBUG/MainProcess] Current schedule: <ScheduleEntry: progress-bar app1.tasks.progress_bar() <freq: 5.00 seconds> <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * … -
Django: Access num_pages in view to generate pagination
I want to generate a range of pages in my template when using a ListView and it's pagination, to generate dynamically the number of pages for the pagination: https://getbootstrap.com/docs/4.0/components/pagination/ My first attempt was to make a for loop for everyelement in page_obj.paginator.num_pages, getting error int is not iterable: {% if is_paginated %} <ul class="pagination"> {% for i in page_obj.paginator.num_pages %} <li class="page-item"> <span class="page-link"> <a href="/catalogo?page={{i}}"> <span class="sr-only">(current)</span> </span> </li> {% endfor %} </ul> {% endif } Then I've discovered that there isn't and wont be a range template filter because this calculation should be done in the view and send the range to the template, not generated in the template. See: https://code.djangoproject.com/ticket/13088 So how can I access the page_obj.paginator.num_pages inside the view??? My LisView: class CatalogoListView(ListView): model = UnitaryProduct template_name = "shop/catalogo.html" paginate_by = 10 def get_queryset(self): filter_val = self.request.GET.get('filtro', 'todas') order = self.request.GET.get('orderby', 'created') if filter_val == "todas": context = UnitaryProduct.objects.all().filter(available=True).order_by('-created') return context else: context = UnitaryProduct.objects.filter( subcategory2=filter_val, ).filter(available=True).order_by('-created') return context def get_context_data(self, **kwargs): context = super(CatalogoListView, self).get_context_data(**kwargs) context['filtro'] = self.request.GET.get('filtro', 'todas') context['orderby'] = self.request.GET.get('orderby', 'created') context['category'] = Category.objects.get(slug="catalogo") return context -
Docker app server ip address 127.0.0.1 difference of 0.0.0.0 ip
He everyone. I'm working with docker and trying to dockerize a simple django application that does an external http connect to a web page (real website) so when I set in the Docker file the address of my django server that should work in the container - 127.0.0.1:8000. my app wasn't working because of the impossibility to do an external connection to the website. but when I set the port for my server: 0.0.0.0:8000 it started to work. So my question is: Why it behaves like that? What is the difference in this particular case? I just want to understand it. I read some articles about 0.0.0.0 and it's like a 'generic' or 'placeholder' port that allows to use the OC default port. 127.0.0.1 is like a host that redirects the request to the current machine. I knew it. But when I run the app at my localmachine (host: 127.0.0.0:8000) everything was working and the app could do the connection to the real website but in case of docker it stopped to work. Thanks for any help! Here are my sources: Docker file FROM python:3.6 RUN mkdir /code WORKDIR /code COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY … -
How to make a dependent drop-down be required when there are options available using Django?
I'm fairly new to Django/Python, so apologies in advance. I have a form with a dependent drop-down. Currently, I have it set so that the second drop-down only appears if there are options available in it, otherwise is hidden. What I am having trouble with is that, whenever you choose a primary(Work Area) option that has a secondary(Station) drop-down, you can submit the form without having selected an option from the dependent (secondary) drop-down, which is supposed to be required whenever there are options in it. How can I modify this so that the dependent drop-down is required whenever it appears? models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = Station.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif … -
How to make a field read-only inside a CreateView
I am a Django beginner and I am trying to make read-only a 'price' field for an order. I think, based on what I have understood, this cannot be done inside the model itself, but rather inside a form. Since I am using a CreateView generic view, I thought this could have been done by setting the attribute disabled equal to True, as said here. so what I have done is, in views.py from django.shortcuts import render from django.views.generic import CreateView from .models import Order from django import forms # Create your views here. class CreateOrderView(CreateView): model = Order template_name = 'home.html' meal_price = forms.DecimalField(disabled=True) fields = [ 'meal_name', 'meal_price', 'restaurant', 'customer', ] But this doesn't work. Here is my models.py from django.db import models from restaurant.models import Restaurant from account.models import Customer # Create your models here. class Order(models.Model): meal_name = models.CharField(max_length=255) meal_price = models.DecimalField(max_digits=5, decimal_places=2) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, default=None) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, default=None) Can anybody give me a hint? Please consider that I am still learning so I would prefer coded answers to descriptive ones. Thank you in advance -
Python django 'NoneType' object has no attribute 'indicador_set'
I have the following problem, I implemented an ajax function to be able to have a dependent dropdown, at the time of creating a question all right but the problem arrives when saving it and sending me to the page to add questions, could someone tell me that I am wrong?. error: Traceback (most recent call last): File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Proyectos\proyecto-educa-quiz\classroom\views\teachers.py", line 733, in question_change form = QuestionForm(instance=question, quiz=quiz) File "C:\Proyectos\proyecto-educa-quiz\classroom\forms.py", line 450, in __init__ self.fields['indicador'].queryset = self.instance.objetivo.indicador_set.order_by('id') AttributeError: 'NoneType' object has no attribute 'indicador_set' this is my code: forms.py: class QuestionForm(forms.ModelForm): class Meta: model = Question context_object_name = 'questions' fields = ('number','objetivo','indicador','text','description', 'texto' ,'puntaje' ,'image','document','video') label = 'Pregunta' def __init__(self ,quiz ,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['objetivo'].queryset = Planificacion.objects.filter(asignatura_id = quiz.subject.id, curso_id = quiz.curso.id) self.fields['indicador'].queryset = PlanificacionIndicador.objects.none() self.fields['texto'].queryset = TextoQuestion.objects.filter(owner__id=quiz.owner.id) if 'objetivo' in self.data: try: objetivo_id = int(self.data.get('objetivo')) self.fields['indicador'].queryset = PlanificacionIndicador.objects.filter(objetivo_id=objetivo_id).order_by('indicador_evaluacion') except (ValueError, TypeError): pass elif self.instance.pk: … -
How to clear only a specific field from a form after submission?
I have a form with a few fields. Most of the time, people only need to change one field every time they submit, not all, so I would like to change it in such a way that upon submission, only the employee # field is cleared, but the Work Area choice and station (if there are any available) remain selected. How could I change the way the form is handled so it is not completely cleared upon submission? I know the form = WarehouseForm() is what clears is, but I'm not sure how I could just specify I only want the employee_number field cleared. views.py def enter_exit_area(request): enter_without_exit = None exit_without_enter = None if request.method == 'POST': form = WarehouseForm(request.POST) if form.is_valid(): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in request.POST: # Submission logic form = WarehouseForm() elif 'leave_area' in request.POST: # Submission logic .. form = WarehouseForm() else: form = WarehouseForm() return render(request, "operations/enter_exit_area.html", { 'form': form, 'enter_without_exit': enter_without_exit, 'exit_without_enter': exit_without_enter, }) -
DJANGO ORM join on multiple tables
I have the following models: class Timesheet(models.Model): work_packet logged_billable_hours class WorkPacket(models.Model): type name purchase_order description class PurchaseOrder(models.Model): customer class Customer(Programme): verbose_name the following queries: my_timesheet_Q3 = me.timesheets.filter(date__gte=datetime.date(2019, 9, 1), date__lte=datetime.date(2019, 11, 30)).values('work_packet', 'logged_billable_hours') my_timesheet_Q3_by_wp = my_timesheet_Q3.values('work_packet').annotate(wp_hours=Sum('logged_billable_hours')).order_by() produces: [{'work_packet': 1152, 'wp_hours': Decimal('384.00')}] to the result I would like to add: WorkPacket.type, WorkPacket.name, WorkPacket.purchase_order, WorkPacket.description, Customer.verbose_name I know how to achieve it in plain SQL but I don't using DJANGO ORM. Can you help? -
Django Admin Forms validate child form based on parent values
What I'm trying to do is validate a nested_admin.NestedTabularInline form based on some parent data. (If a parent field is one value check if a child field is blank). But I'm having trouble finding a good solution. I've tried using self.data, but it seems incredibly difficult to parse reliably. I've also seen use of FormSet to access other forms, but I'm not sure how to apply it in my case. A simple example looks like: model.py Parent(models.Model): type = models.CharField(max_length=256) Child(models.Model): value = models.IntegerField() items = models.CharField(max_length=256) admin.py @admin.register(models.Parent) class ParentAdmin(nested_admin.NestedModelAdmin): inlines = [ChildInline] class ChildInline(nested_admin.NestedTabularInline): form = forms.ChildInlineAdminForm model = models.Child forms.py class ChildInlineAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ChildInlineAdminForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() # How can I access the parent instance type field here??? I really feel like there should be a straightforward solution I'm missing, but I haven't found it yet so help would be greatly appreciated. -
can't catch/get the created instance, during the test for create_view in Django
I can't get the just created instance during the create_view() test(in Django). The View class works properly. It seems that the instance is being deleted before I can make an assertion(if it's possible to happen like that). this is my view: class CreateItemView(CreateView): form_class = ItemForm template_name = 'item/item_create.html' success_url = '/list_item' # <---- redirecting my test: class ItemViewsTest(TestCase): def setUp(self): self.client = Client() self.factory = RequestFactory() self.category = create_category() self.item = create_item(self.category) def test_item_create(self): data = { 'number': 2, 'name': 'item_2', 'description': 'item 2 description', 'created_by': 'admin', 'quantity': 100, 'category': self.category.pk, } request = self.factory.post('/item_create', data) response = CreateItemView.as_view()(request) """following has the same result(doesn't work): response = self.client.post( '/create_item/', data, )"""" print(Item.objects.all()) # <----- only getting instance created in SetUp function self.assertEqual(Item.objects.last().name, data['name']) getting no errors for request or response, except the following error for the assertion: Creating test database for alias 'default'... System check identified no issues (0 silenced). FAIL: test_item_create (core.tests.test_views.ItemViewsTest) Traceback (most recent call last): File "D:\PYTHON\Projects\My web\warehouse\warehouse\core\tests\test_views.py", line 155, in test_item_create data['name']) AssertionError: 'item_1' != 'item_2' Ran 1 test in 0.497s FAILED (failures=1) Destroying test database for alias 'default'... and I have the same for another model and it works: class CreateCatView(CreateView): form_class = CategoryForm … -
Django view function getting called twice for one GET request
I have a url path defined as follows: re_path(r'installapp/(.+)', views.install_app, name='install-app') This URL path triggers a view function install_app. When a GET request is made to this URL path, the view function is triggered twice instead of once. How to prevent calling of view function twice for one GET request. -
How can I modify custom datetimepicker to display time selection first?
I have a modal that pops up to request an estimated timestamp. Most of the time, people only have to change the time, not the date, I was wondering how I can modify this so the time selection is displayed first when the picker is clicked, not the date? I'm not too familiar with python so I'm not sure if this is possible. update_modal.html {% load core_tags %} <form id="create-update-form" method="post" action="{% url "operations:update_timestamp_modal" main_object.id %}"> {% csrf_token %} <label>Please enter best estimated time for missing entry/exit</label> <div class="row"> <div class="form-group col-xs-6"> {% standard_input form.edited_timestamp datetimepicker=True hide_label=True %} </div> </div> </form> This is where I get the standard_input from core_tags.py def standard_input(context, field, **kwargs): """ Renders a form field with a label and a tooltip containing the help_text :param context: :param field: Form field :param kwargs: Additional keyword arguments (see below) :return: Rendered HTML for form field Additional optional kwargs: pre_addon: Additional group-addon text that appears before the input post_addon: Additional group-addon text that appears after the input datepicker: Whether or not this should use a datepicker widget datepicker_future: Whether or not this should use a datepicker widget that only allows future dates timepicker: Whether or not this should use … -
How to save manytomanyfield in django rest framewor and angular?
I am trying to save a manyToManyField, but I have the following error. TypeError at Direct assignment to the forward side of a many-to-many set is prohibited. Use .set() instead. In the following way I make my object in angular this.event.plan = []; checkPlan(plan) { if (this.event.plan.indexOf(plan) > -1){ this.event.plan.splice(this.event.plan.indexOf(plan),1); }else{ this.event.plan.push(plan); } } I only have this error when adding a record, when editing everything is done well -
getting object ID inside form.py
I am trying to check if my instance.id is not equal object.id in form.py so I can edit the post whenever all conditions are met. form.py ''' from django import forms from .models import Topic class TopicForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.owner = kwargs.pop('owner') super(TopicForm, self).__init__(*args, **kwargs) self.fields['country'].empty_label = 'أختر الدولة' self.fields['city'].empty_label = 'أختر المدينة' self.fields['neighborhood'].empty_label = 'أختر الحي' self.fields['category'].empty_label = 'أختر القسم' self.fields['sub_category'].empty_label = 'أختر الفئة' self.fields['sub_sub_category'].empty_label = 'أختر النوع' class Meta: model = Topic fields = ['topic', 'category', 'sub_category', 'sub_sub_category', 'country', 'city', 'neighborhood', 'price', 'insurance', 'description', ] error_messages = { 'topic': { 'required': "الخانة هذي مطلوبة" }, 'category': { 'required': "الخانة هذي مطلوبة" }, 'sub_category': { 'required': "الخانة هذي مطلوبة" }, 'sub_sub_category': { 'required': "الخانة هذي مطلوبة" }, 'country': { 'required': "الخانة هذي مطلوبة" }, 'city': { 'required': "الخانة هذي مطلوبة" }, 'neighborhood': { 'required': "الخانة هذي مطلوبة" }, 'price': { 'required': "الخانة هذي مطلوبة", 'number': "الرجاء ادخال رقم صحيح" }, 'insurance': { 'required': "الخانة هذي مطلوبة" }, 'description': { 'required': "الخانة هذي مطلوبة" } } widgets = { 'topic': forms.TextInput(attrs={ 'required': True, 'placeholder': 'الرجاء إدخال عنوان' }), 'country': forms.Select(attrs={ 'required': True, 'empty_label': 'أختر الدولة' }), 'city': forms.Select(attrs={ 'required': True, 'placeholder': 'أختر المدينة' }), 'neighborhood': forms.Select(attrs={ 'required': True, … -
Django - Bad request syntax or unsupported method
I am working on a django project and I want to make a post request. import pandas import requests excel_data_df = pandas.read_excel('workorders.xlsx') json_str = excel_data_df.to_json(orient='records', date_format='iso') print(json_str) API_ENDPOINT = "http://127.0.0.1:8000/api/create/" API_KEY = "dF8NbXRA.94Mj2xeXT3NZOtx1b575CvNvbs8JWo0D" source_code = json_str data = {'api_dev_key':API_KEY, 'api_option':'paste', 'api_paste_code':source_code, 'api_paste_format':'csv'} r = requests.post(url = API_ENDPOINT, data = data) views.py class PostDataView(CreateAPIView): queryset = Workorder.objects.all() serializer_class = WorkorderSerializer serializers.py class WorkorderSerializer(serializers.ModelSerializer): class Meta: model = Workorder fields = '__all__' Thank you -
Django ModelForms - Filling fields from view?
Lets say I have a model: class Subtype(models.Model): SubtypeID = models.AutoField(primary_key=True, unique=True) Name = models.CharField(max_length=255, blank=True, null=True) TypeID = models.ForeignKey('Type', on_delete=models.CASCADE, null=True) And I'm creating this Subtype having already selected my Type object. I have TypeID as a parameter in my view. I now have a form: class addSubtypeForm(forms.ModelForm): class Meta: model = Subtype fields = ('Name',) labels = {"Name": "SubType Name"} SubtypeID is auto so I don't include that, but I need to specify a TypeID. I don't want my user to have to do that, which is why I have passed it to the view: def addSubtypeForm_Create(request, type): typeselected = Type.objects.get(TypeID = type) if request.method == 'POST': form = addSubtypeForm(request.POST) if form.is_valid(): form.save() return redirect('AddPart', obj.SubtypeID) else: form = addSubtypeForm() return render(request, 'proj/addSubtype.html', {'form': form, 'type': typeselected}) I just have no idea how to assign this from the view, I feel it should be possible though? Any help would be really appreciated. -
predicting image using fastai and django
i am making a django application in which i let user upload an image. i am not saving image anywhere. inside the view i want to predict the image label using learn.predict method of fastai library. i want help about how can i pass the image uploaded by user to the predict function inside of view without actually saving image. here is the predict image function def openimage(img): loc = static('/MainApp/') learn = load_learner(loc) i = open_image(img) predx, predidx, info = learn.predict(img) print(predx) and here is view function def predict(request): if request.method == "POST": i = request.FILES['img'] #img is form field in forms.py file openimage(i) return render(request, 'MainApp/ML.html') else: form = predictform return render(request, 'MainApp/ML.html', {"form" : form}) -
TokenValidator in `django-cognito-jwt` get_public_key method returns None
I am following the aws-cognito-tutorial-complete and trying to use Bearer with Django because my target is Single Page App(SPA) consuming Django REST Framekwork and GraphQL. With the given example I can get connected with AWS and be able to signup, login, ... etc to AWS Cognito. Then I use django-cognito-jwt to decode the Bearer token. Problem: django-cognito-jwt raises error regarding the public key problem Attempt: TokenValidator class with method _get_public_key token is there 35 def _get_public_key(self, token): 36 import ipdb; ipdb.set_trace() ---> 37 try: 38 headers = jwt.get_unverified_header(token) 39 except jwt.DecodeError as exc: 40 raise TokenError(str(exc)) 41 42 if getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_ENABLED", False): ipdb> token b'eyJraWQiOiJUaGd4NXo5MnFxNjdPR1wvMDRjT0xDS2U2K0dsQlU3XC9LZklHK2hJdFwvSjR3PSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyZTQ3OTBhMC0zNWE0LTQ1ZDctYjEwYy1jZWQ3OWJlMjJlOTQiLCJhdWQiOiIxNTl1ZmpyaWhnZWhiNjdzbjM3M2FvdGxpNyIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJldmVudF9pZCI6ImM2OTA0NjYyLWZlOWUtNGYwZi04OTc3LTdhZGU4M2YyOTAxMyIsInRva2VuX3VzZSI6ImlkIiwiYXV0aF90aW1lIjoxNTc1NDU3MDIwLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtd2VzdC0yLmFtYXpvbmF3cy5jb21cL3VzLXdlc3QtMl9mbENKYW9EaWciLCJjb2duaXRvOnVzZXJuYW1lIjoiam9obi1yYW1ibyIsImV4cCI6MTU3NTQ2MDYyMCwiaWF0IjoxNTc1NDU3MDIwLCJlbWFpbCI6ImZvZ2d5Z2lnYUBnbWFpbC5jb20ifQ.jk207sDdYb7CDhc5r0hZXa_EDPqG9Fi2oBTot8Tv_moJxdB1v4cNCDLB6m5rVVHzmxI8-cPj00GViMH3-LORnQcg4KitAlew_aD_RMD5Hzy3ltABrMYBf9LEI2kq6---Li9jk3NYpVji2h5W4oKoJrHRriJSuNuBFFijFXEc29iLhQclaDLWvXw4BJI087BKCYpnD-xR79bM3nYI-m9Wp40e_e7JbsGtu1JKfTym_nKLE-yncyhWq0rarIbauBHmq5hRYCQofUbSWD6IRGCZaiLRPBTk6LvUd3VigUz9x0mIU8feViRQmFcVFfRsB56Pbx10RUAUYHBR4JNHCMROpQ' Go next to headers ipdb> headers {'kid': 'Thgx5z92qq67OG/04cOLCKe6+GlBU7/KfIG+hIt/J4w=', 'alg': 'RS256'} ipdb> cache_key 'django_cognito_jwt:Thgx5z92qq67OG/04cOLCKe6+GlBU7/KfIG+hIt/J4w=' jwk_data is None ipdb> self._json_web_keys {'D2syaFjXXpkbzTjkRHLAtdX065Neb1EfUguGabpJWlo=': '{"alg": "RS256", "e": "AQAB", "kid": "D2syaFjXXpkbzTjkRHLAtdX065Neb1EfUguGabpJWlo=", "kty": "RSA", "n": "kDmz5mTlTil_r6sVMnln2ohc45_TlBPw1pOcVJtEyGW2_vXN4EXnYKxcFyFQqZIjXaYlrAFBAMAW_qlIfJ0J8coyNImLngfUbk1cbwwQr3wTB-6t8bM8x_B8D_D7uB-HfGe8SNS1yFU6gfDnd4z7kJZvJIFV_uEWP5A1cbXdTOTPlj3zKUXnpXBvnZ5d_V2Y3gPjlv_m3uh3ZejeTAnaLF-PGt69DdD9dj04ncqPa2rK8eShPWYckZ_oaH_4Ju9FmQGD6lzoUHhRxEsfq6pEr2wFt2TAcji9WG7NUFO5v83GRfaWiRnGSVI8iVzVWjzzGvdqAuiMgKUDtmq7b9r5Xw", "use": "sig"}', 'a7tocHhrCduYr7EFRiR9A2txhEbl2dCOOBvYAYEdEJA=': '{"alg": "RS256", "e": "AQAB", "kid": "a7tocHhrCduYr7EFRiR9A2txhEbl2dCOOBvYAYEdEJA=", "kty": "RSA", "n": "re0iYlsRqmSkoqZiGlz3mTYb0HJ3vjCXwN83OmbNQyAguC-Tflb95Z1bEJsVL0Wr6ZvmFFGpXjJU1n3K9DO2JadnBQkGsJegYvXaNC2IgHnHDq9chrP6cNdnO5jAo7wqtMeZi2VqccyRFXVx9dyKAbyGgborORP5raFSvHU-qT2iVfwrbSbWXAH1qwkwbMMbU6fUHJp7u9ZrJT04qMhm-asgoSA6Swe4znqcg87W2dSWMzstyUQwTN-1Kn2GXmTIyYo4lUIoyQRXyl2d8L37iTkbRayulvLqvzkKglAHlRF6jLLHLZt6-ZBf3hvISDbO5Vwo7jJGTYYu6h3tKKbSBQ", "use": "sig"}'} ipdb> headers["kid"] 'Thgx5z92qq67OG/04cOLCKe6+GlBU7/KfIG+hIt/J4w=' At this point jwk_data is None > /Users/sarit/.pyenv/versions/muy/lib/python3.7/site-packages/django_cognito_jwt/validator.py(48)_get_public_key() 47 jwk_data = self._json_web_keys.get(headers["kid"]) ---> 48 timeout = getattr(settings, "COGNITO_PUBLIC_KEYS_CACHING_TIMEOUT", 300) 49 cache.set(cache_key, jwk_data, timeout=timeout) ipdb> jwk_data ipdb> Workaround: Zoom in the token_validator.validate(jwt_token) class JSONWebTokenAuthentication(BaseAuthentication): """Token based authentication using the JSON Web Token standard.""" def authenticate(self, request): """Entrypoint for Django … -
How can you manually assign a generated file to a form field?
I've been struggling to solve this myself for a good while now and I just can't understand how it works. I found a way to get my generated file straight into the model, but it doesn't serve its purpose well because I also need the file to be uploaded to Amazon Web Services. Any solution that helps me with this is appreciated! In my code, I request a JSON file from the user and generate a text file in a specific format using it. This needs to both make its way to the field in the model, and be uploaded to the storage system in AWS. Here's my view as it is currently: def sped_create(request): form = SpedForm(request.POST, request.FILES, None) # sped = get_object_or_404(Sped, pk=id) if form.is_valid(): data = json.load(form.cleaned_data['json_file'].open()) # (json is successfully processed here: I've confirmed that the lines that would usually be here are irrelevant to the problem) f_txt = open(f"static/file_created_txt/bacon.txt", "w+", encoding='utf-8') # FALTA ARRUMAR O DIRETÓRIO for string in fileTxt: f_txt.write(f"{string}\n") f_txt.close() instance = SpedForm(sped_file=request.FILES['static/file_created_txt/bacon.txt']) instance.save() sped = form.save() return redirect(sped_list) return render(request, 'sped_form.html', {'form': form}) Currently, I've been getting this traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/sped_create/ Django Version: 2.2.7 Python Version: 3.7.3 … -
Mandatory one to many relationship in Django
Suppose I've a model Car and a model Passenger (passenger includes the driver of the bus). The models are read/write able via DRF and admin interface. How can I enforce that each car has at least one passenger and potentially several passengers (mandatory one-to-many relationship)? How/where do I have to implement validation before a model is created? -
Ajax request causing Internal Server error
This is my ajax call which is causing internal server error $.ajax({ url: url, method: "POST", dataType: 'json', data: { 'completed': true }, success: function (data) { console.log(data) }, error: function (data) { console.log(data) } }); But when i try manually with the django rest framework it is working fine. -
Django override login page
Would it be possible to just reuse the login page? I just want to add sign up button in the login page. But for what I have searched, it needed to customize all in order to override it. Please help. -
How to properly implement AJAX into Django's MVT
Estimated outcome: When a user visits www.myapp.com/dashboard Django shall render the dashboard. Meanwhile, AJAX shall call (on a regular period) the view getAccountInfo which queries data via the model AccountInformation from PostgreSQL database. The view then returns the latest data and AJAX/JS will update the DOM accordingly (staying on the very same page/url). What makes me feel dizzy: I just don't get how Ajax is implemented here considering the Django MVT architecture. Basically each URL maps to a single view. So once I visit /dashboard it calls the view render_Dashboard. But when I now map the Ajax URL to that view and include the DB query logic into the very same view, it will render the complete site again which will create an infinite loop. So I have to map the Ajax URL to my second view to make it happen? But this view doesn't have an URL because I only want to have /dashboard as URL for users to visit? So how to implement the second view into this architecture? What I have so far: views.py inside dashboard app: from Dashboard.models import AccountInformation #Get Account Information from PostgreSQL DB def getAccountInfo(): account_information = AccountInformation.objects.all() for row in account_information: profit …