Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin date time helpers missing
I have a model that includes a datetimefield... # Create your models here. class BroadcastNotification(models.Model): message = models.TextField() broadcast_on = models.DateTimeField() sent = models.BooleanField(default=False) class Meta: ordering = ['-broadcast_on'] In the admin pages the helpers for that field have gone away. I don't know what I did to cause it as I didn't test everything after every change. I did do collectstatic fairly recently if that might be the cause. -
Django - How to compare different models with same foreign key
I'm really stuck in how to do this and appreciate the help. I have three models, two of them shares the same foreign key field: class AccountsPlan (models.Model): code = models.CharField(max_length=7, unique=True,) name = models.CharField(max_length=100, unique=True,) class Planning (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) month = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2,) class Revenue (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) receipt_date = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2,) And I have this view that annotates the sum for each model by the foreign key name with a form that filters by date: def proj_planning(request): form = ProjectionFilterForm(request.POST or None) # some definitions for the form planned = Planning.objects.values('accountplan__name').annotate(Sum('amount')).order_by('accountplan__code').filter( month__range=[start_date, planned_end_date]) done = Revenue.objects.values('accountplan__name').annotate(Sum('amount')).filter( receipt_date__range=[start_date, end_date],).order_by('accountplan__code') if request.method == 'POST': planned = Planning.objects.values('accountplan__name').annotate(Sum('amount')).order_by( 'accountplan__code').filter(month__range=[start_date, planned_end_date], accountplan__name__icontains=form['accountplan'].value()) done = Revenue.objects.values('accountplan__name').annotate( Sum('amount')).filter(receipt_date__range=[start_date, end_date], accountplan__name__icontains=form['accountplan'].value()) comp_zippedlist = zip(planned, done) return render(request, 'confi/pages/planning/proj_planning.html', context={ 'form': form, 'list': comp_zippedlist, }) The code kinda works (it doesn't throw any errors), but the thing is, I will never have an exact amount of data for each model. For example: if I have 6 different records in the Planning model, but only 4 records in the Revenues model, the zipped list will only show the 4 records in the Revenues and not the … -
Axios POST method with React shows as Anonymous user and CORS error in Django Backend
I have been succesfully using GET methods with Axios while the logged in user information is succesfully transmitted to backend with the following code : await axios({ method: 'get', url: BASE_BACKEND_URL + `/project/` + project_uuid + `/`, data: {}, headers: { 'Content-Type': 'application/octet-stream' }, withCredentials: true, }) class ProjectView(APIView): def get(self, request, uuid): logging.info("ProjectManifest GET begin") user = request.user print(user) When I use a similar code with the POST API call of the same function, Django backend shows the request has been requested by an anonymous user instead of the logged in user. The code for the POST command is below: await axios({ method: 'post', url: BASE_BACKEND_URL + '/project/' + project_uuid + '/', data: { project_uuid : projectJSON }, headers: { 'Content-Type': 'application/json', }, withCredentials: true, }) class ProjectView(APIView): def post(self, request, uuid): logging.info(f"ProjectManifest POST begin: {request.user}") How can I make the react axios post call to work properly with Django backend ? -
Django-filter pagination only the first search filed failed
I'm using django-filter with pagination, as long as the search filed is in the first place in filter.py -> fields = ['name_procss','typeLevel'] list, the pagination for filter of that filed will not work. fitler.py: import django_filters from MyCore.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(self,filed): return tuple((l, l) for l in list(MyRunStats.objects.exclude(**{filed: None}).values_list(filed, flat=True).distinct())) name_procss = django_filters.ChoiceFilter(label='Process',choices=tuple,null_label='None',null_value='null') typeLevel = django_filters.ChoiceFilter(label='Message Type',choices=tuple,null_label='None',null_value='null') class Meta: model = MyRunStats fields = ['name_procss','typeLevel'] def __init__(self, *args, **kwargs): super(MyRunStatsFilter, self).__init__(*args, **kwargs) self.filters['name_procss'].extra['choices'] = self.gen_choice('name_procss') self.filters['typeLevel'].extra['choices'] = self.gen_choice('typeLevel') Views.py def runstat_hist_view_render(request): all_obj = MyRunStats.objects.all().order_by('-create_dttm') hist_filter = MyRunStatsFilter(request.GET, queryset=all_obj) paginator= Paginator(hist_filter.qs[:57], 20) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) context = {'response': response,'filter': hist_filter} return render(request, 'My/My_runstat_hist.html',context) html: <form method="get" > {{ filter.form}} <button type="button" onclick="submitFilter()" id="hist-search-button" >Search Message</button> </form> {% for item in response %} <nav> <ul class="pagination"> {% if response.has_previous %} <li><a href="?page=1&{{ request.get_full_path }}">&laquo; First</a></li> <li ><a href="?page={{ response.previous_page_number }}&{{ request.get_full_path }}">Previous</a></li> {% else %} <li><a href="#">Previous</a></li> {% endif %} {% for num in response.paginator.page_range %} {% if response.number == num %} <li><a href="?page={{num}}&{{ request.get_full_path }}">{{num}}</a></li> {% elif num > response.number|add:'-3' and num < response.number|add:'3' %} <li><a href="?page={{num}}&{{ request.get_full_path }}">{{num}}</a></li> {% endif %} {% endfor … -
Connecting html with css using django
This is the html file that i'm trying to add a star rating for book_detail.html {% extends "base.html" %} {% load static %} {% block title %} Block Detail Page {% endblock title %} {% block sidenav %} {% for item in item_list %} <li> <a href="{{ item.link }}"> {{ item.item }} </a> </li> {% endfor %} {% endblock sidenav %} {% block content %} <h1 align="center"> Book Detail </h1> <table align="center" border="2" width="400"> <tr> <td> {{ book.name }} </td> </tr> <tr> <td> <img src="{% static book.pic_path %}" width="100"> </td> </tr> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <tr> <td> {{ book.username }} <div id="full-stars-example"> <div class="rating-group"> <input class="rating__input rating__input--none" name="rating" id="rating-none" value="0" type="radio"> <label aria-label="No rating" class="rating__label" for="rating-none"><i class="rating__icon rating__icon--none fa fa-ban"></i></label> <label aria-label="1 star" class="rating__label" for="rating-1"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-1" value="1" type="radio"> <label aria-label="2 stars" class="rating__label" for="rating-2"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-2" value="2" type="radio"> <label aria-label="3 stars" class="rating__label" for="rating-3"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-3" value="3" type="radio" checked> <label aria-label="4 stars" class="rating__label" for="rating-4"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-4" value="4" type="radio"> <label aria-label="5 stars" class="rating__label" for="rating-5"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-5" value="5" type="radio"> </div> </div> </td> </tr> </table> {% … -
Problems filtering columns that have many rows with a None value(Django database)
I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returned value is None, although in the database this line is filled with a value. Strangely, when I populate lines 86 onwards, the query on line 43 is correct and does not return a None value. I want to know if there is any problem when filtering columns that have many None values and why this might be happening -
web form where you can upload a pdf file and it gets translated into visible text
I'm trying to figure it out how to do it with python and Django or flask. I want to make a website where you can upload a pdf file and it gets translated into visible text, and I need to use specific keywords from pdf file and assign them with translation of my own words and then display it to the user. Is something like that possible with python? -
Two views same URL
I have a single dashboard_view URL path("", view=dashboard_view, name="dashboard"). On this page you can see the homepage unauthenticated. However, if you login, I present a modal popup to allow a user to populate a CreateForm. The issue is that the dashboard_view doesn't have the form ( I have that in another view ). What is the best practice for this? Best for the user to have different options on the same page without having to switch pages. -
{% csrf_token %} django error in speech recognition
I have coded using JavaScript for voice search using speech recognition. In the html form, if I have loaded 'csrf' token for post form, the speech recognition is not working. It is working when there is no 'csrf' token. Why there is an issue like this? Here is my Html page for form. <form action="{% url 'voice' %}" method="post" id="search-form"> {% csrf_token %} <input name="q" type="text" placeholder="Search" autocomplete="off" autofocus> <!-- <button type="button"><i class="fas fa-microphone"></i></button> --> </form> -
Python Django - Passing in multiple parameters to Factory during testing
I'm currently working on a practice social media app. In this app, current users can invite their friends by email to join the app (specifically, joining a 'channel' of the app, like Discord). For this project, I'm working on functionality where a user will get an error if they try to invite someone who is already in the app (meaning people who are already in the app's database). I'm working on unit tests that ensures the error messages pop up when users are detected as already existing. I managed to get my first scenario working, but I'm a bit stumped for the second one. Here is a file that is central to both tests. factories.py class ChannelFactory(factory.django.DjangoModelFactory) class Meta: model = Channel id = int name = str class CurrentUserFactory(factory.django.DjangoModelFactory) class Meta: model = CurrentUser user_email = user_email channel = models.ForeignKey(Channel) Scenario #1 (currently working) - one new user is invited to join the app but already exists in the app's database test_forms.py from tests.factories import ChannelFactory, CurrentUserFactory @pytest.mark.django_db def test_that_current_user_cannot_be_reinvited(email, error_message): """user that is already in the specific channel cannot be reinvited""" email = "user@test.com" error_message = "user@test.com already exists in this channel" # I am not specifying the … -
What causes text to have an odd character at the end
I am using the django standard base.html with the following {% load i18n static %}<!DOCTYPE html> {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" dir="{{ LANGUAGE_BIDI|yesno:'rtl,ltr,auto' }}"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!-- Font Awesome CSS --> <script src="https://kit.fontawesome.com/5135d630a7.js" crossorigin="anonymous"></script> <title>{% block title %}{% endblock %}</title> This is giving me the following header with Home and Admin Pages having an odd character at the end. Is it the font? -
how to read json file array objets with python flask
I have a problem with read a file JSON, that file contains an array objects like this: [{"some": 1, "list": [{"one":1}]},{"some": 1, "list": [{"one":1}]}] my code is like below: ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read()) show me this error: I try to read that file and put that file in ls_plano to read and assign to the other values like this: ls_plano = json.loads(open("tests/mocks/lsplano_itens_pessoais.json", encoding="utf8").read()) if ls_plano is not None: for plano in ls_plano: temp_plano = {} temp_plano["inPlanoPersonalizado"] = plano.get("inPlanoPersonalizado") temp_plano["inSelecionado"] = plano.get("inSelecionado") if plano.get("lsChassi"): temp_plano["lsChassi"] = self.__map_ls_chassi(plano.get("lsChassi", [])) if plano.get("lsTipoObjetoSegurado"): temp_plano["lsTipoObjetoSegurado"] = self.__map_ls_tipo_ob_segurado( plano.get("lsTipoObjetoSegurado") ) if plano.get("lsComissao"): temp_plano["lsComissao"] = self.__map_ls_comissao(plano.get("lsComissao", [])) if plano.get("lsParcela"): temp_plano["lsParcela"] = self.__map_ls_items(plano.get("lsParcela", [])) temp_plano["nmIdentificadorPlano"] = plano.get("nmIdentificadorPlano") temp_plano["nmPlano"] = plano.get("nmPlano") temp_plano["nrPlano"] = plano.get("nrPlano") temp_plano["vlAdicionalFracionamento"] = plano.get("vlAdicionalFracionamento") temp_plano["vlAssistenciaFacultativa"] = plano.get("vlAssistenciaFacultativa") temp_plano["vlCobranca"] = plano.get("vlCobranca") temp_plano["vlComercial"] = plano.get("vlComercial") temp_plano["vlIof"] = plano.get("vlIof") temp_plano["vlPremioLiquido"] = plano.get("vlPremioLiquido") temp_plano["vlPremioNet"] = plano.get("vlPremioNet") temp_plano["vlPremioTarifa"] = plano.get("vlPremioTarifa") temp_plano["vlPremioTotal"] = plano.get("vlPremioTotal") temp_plano["vlTotalComissao"] = plano.get("vlTotalComissao") temp_plano["vlTotalDesconto"] = plano.get("vlTotalDesconto") resp.append(temp_plano) return resp please help me, thanks for your attention. -
What does django's Manager.create() method do?
I was poking around in the rest_framework trying to figure out how it works, and came across a call to Model.objects.create(), but I can't for the life of me find the create() method for django model managers in the docs or the source code. It looks to be dynamically generated. What does it do, exactly? Where can I find its code? If I wanted to override it, what would my implementation have to do? I found this question but it only says to call the super().create() method. -
Django crispy form is not posting or view is incorrect
I am currently working on a note/comment system. It is intended to work as adding notes to each individual projects. For example, you set up a "Project" and there is a note or comment sections intended for adding updates to the project. Here is my view.py for updating the project. The top portion is for updating the project itself, the bottom portion is for adding the notes. @login_required(login_url="/login") def update_project(request, pk): queryset = DevProjects.objects.get(id=pk) form = UpdateProject(instance=queryset) if request.method == 'POST': form = UpdateProject(request.POST, instance=queryset) if form.is_valid(): form.save() return redirect('/') project = get_object_or_404(DevProjects, id=pk) notes = project.notes.filter(id=pk) new_note = None if request.method == 'POST': notes_form = AddProjectNotes(request.POST, instance=project) if notes_form.is_valid(): new_note = notes_form.save(commit=False) new_note.project = project new_note.save() else: notes_form = AddProjectNotes() return render(request, 'projects/updateprojects.html', {"form": form, "queryset": queryset, 'project': project, 'notes': notes, 'new_note': new_note, 'notes_form': notes_form}) Whenever I try and submit the notes, it shows that is successfully posted to DB but in DB there is no entries. Here is my template. <div class="container"> {% if new_note %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form action="." method="post"> {{ notes_form.notes|as_crispy_field }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} </div> <div class="container"> … -
Django to Droplet: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I am getting Internal Server Error while setting up GNINX... On both the domain and on the droplet IP: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Correct response was give by: curl --unix-socket /run/gunicorn.sock localhost also sudo systemctl status gunicorn works as expected Gunicorn bind als worked on both the droplet IP and the domain. There is just something going on with GNINX. So I gues it has something to do with the file settings. Tried to reinstall the Droplet multiple times, Tried different settings and groups already, Nothing seems to work. -
How to implement sending a command from a page to Django via SSH?
How to implement sending a command from a page to Django via SSH? It is necessary that the page has a button that, when clicked, sends a command via SSH to the Ubuntu virtual machine. Good afternoon. Question regarding the implementation of SSH on pages in Django. It is necessary to assemble the command over SSH to the server. There is such code using Paramiko: views.py class StartServer(server, view): def get(self, request, *args, **kwargs): form = AddServerForm(request.POST or None) servers = server.objects.all() context = {'form': form, 'csservers': servers} return render(request, 'csservers/server_detail.html', context) # def post(self, request, *args, **kwargs): # pass def start_server(i, request, pc): print(request.POST) if request.POST: server = Server.objects.get(id=pk) client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=server.host, username=server.server_username, password=server.secret, port=server.port) standard input, standard output, standard output = client.exec_command('./<command>') data = stdout.read() + stderr.read() client.close() HTML: <!DOCTYPE html> <html lang="en"> <head> <metacharset="UTF-8"> <title>Title</title> </head> <body> {{server.host}} {{server.port}} {{server.server_username}} {{server.secret}} <form action="{% url 'server_start' server.slug server.id %}" method="post"> {% csrf_token %} <button type="submit" style="outline: none; border: none; background-color: red; color: #fff;">Start server</button> </form> </body> </html> If I click on the button, it gives an error 405. I need to connect to the local Ubuntu machine via SSH and send the ./ command. Is it … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE doesn't work with Firefox 107 or Chrome 107
With Firefox 107.0 in Win 10, in settings.py, I have SESSION_EXPIRE_AT_BROWSER_CLOSE = True In Storage in Firebug, I see the sessionid cookie with Expires/Max-Age: Session. When I close Firefox and restart it, the cookie is still there and so is my session information. I can manually delete the sessionid cookie. Is there something else I need to do or know? -
I keep getting "TypeError __init__() takes 1 positional argument but 2 were given" in my code but the urls and views are correct?
In Django, I am trying to create 2 new pages. I have created other pages using this similar approach. Here is my code for views.py and urls.py: views.py class practice_spanish(TemplateView): template_name = "practice_spanish.html" class quiz_spanish(TemplateView): template_name = "quiz_spanish.html" urls.py urlpatterns = [ re_path(r'^$', views.HomePageView.as_view(), name= 'home'), # Notice the URL has been named re_path(r'^about/$', views.AboutPageView.as_view(), name= 'about'), re_path(r'^chat/$', views.chat, name = 'chat'), re_path(r'^play/$', views.PlayPageView.as_view(), name = 'play'), re_path(r'^profile/$', views.ProfilePageView.as_view(), name = 'profile'), re_path(r'^scores/$', views.ScoresPageView.as_view(), name = 'scores'), re_path(r'^settings/$', views.SettingsPageView.as_view(), name = 'settings'), re_path(r'^practice_languages/$', views.Practice_languagesPageView.as_view(), name = 'practicelang'), re_path(r'^practicehtml/$', views.practicehtml, name = 'practicehtml'), re_path(r'^quiz_languages/$', views.Quiz_languages.as_view(), name = 'quiz_languages'), re_path(r'^quizhtml/$', views.quizhtml, name = 'quizhtml'), re_path(r'^practice_spanish/$', views.practice_spanish.as_view(), name = 'practice_spanish'), re_path(r'^quiz_spanish/$', views.quiz_spanish.as_view(), name = 'quiz_spanish'), path("chatrooms/<str:room_name>/", views.room, name="room"), path('admin/', admin.site.urls), re_path(r"^registration/$", views.registration, name = "registration"), re_path(r"^registration/register$", views.register, name = "register"), path("login_user", views.login_user, name="login_user"), path("index", views.home, name="home"), path("logout_user", views.logout_user, name="logout_user"), ] I am looking at practice_spanish and quiz_spanish. They are also named correctly as HTML files: my html files I tried to create 2 pages using the exact same way I created my others using the class-based views. I get an error this time when clicking on the buttons to take me to the 2 pages. -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet | APScheduler
I have this APScheduler code: import atexit from apscheduler.schedulers.background import BackgroundScheduler from main.utils import run_employee_import scheduler = BackgroundScheduler() scheduler.add_job(run_employee_import, "interval", minutes=2) scheduler.start() # Shut down the scheduler when exiting the app atexit.register(lambda: scheduler.shutdown()) When I add this code to settings.py to run it when the app starts to run, it gives me the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. PS: I did not include the run_employee_import code because I tested it already (replaced its content with a simple pass) and nothing changed, so it is irrelevant to the error. -
How to use a Django (Python) Login Form?
I builded a login form in Django. Now I have a problem with the routing. When I select the login button, the form doesn`t send the correct awnser. I think the form in the frontend cannot gets the correct awnser from the view.py file. So it will send no awnser and the login process canot work and the form is a simple static html form. I hope you can help me. HTML: <form class="windowlogscreen-content" method="POST" action={% url 'homepage' %}\> {% csrf_token %} <input type="text" placeholder="account" name="username"> <br> <input type="password" placeholder="password" name="password"> <br> <button style="margin: 20px;" type="submit">join</button> </div> </div> </form> views.py def loginuser(request): if request.method == "POST": username = request.POST\['accountName'\] password = request.POST\['accountPassword'\] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return views.homepage else: return redirect('start') else: return render(request, 'start', {}) -
Why is Django trying to find my image in such directory?
Instead"/media/", it tries to find here ??? The idea was to put several images in one object and everything works in the admin panel, but in the html template it paves the wrong path to the image. Tell me what am I doing wrong? models.py ` class Product(models.Model): name = models.CharField(max_length=255, verbose_name='Название товара') description = models.TextField(blank=True, verbose_name='Описание') price = models.DecimalField(max_digits=10, decimal_places=0, verbose_name='Цена') created = models.DateTimeField(auto_now_add=True, verbose_name='Время создания') updated = models.DateTimeField(auto_now=True, verbose_name='Время обновления') is_published = models.BooleanField(default=True, verbose_name='Публикация') available = models.BooleanField(default=True, verbose_name='Наличие') catalog = models.ForeignKey('Catalog', on_delete=models.PROTECT, verbose_name='Каталог') def __str__(self): return self.name def get_absolute_url(self): return reverse('product', kwargs={'product_id': self.pk}) class Meta: verbose_name = "Товар" verbose_name_plural = "Товары" ordering = ['created'] class Images(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') images = models.ImageField(upload_to='images/%Y/%m/%d/') def __str__(self): return self.product.name ` admin.py ` class ImagesInline(admin.TabularInline): fk_name = 'product' model = Images @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ImagesInline, ] list_display = ('id', 'name', 'price', 'created', 'updated', 'is_published', 'available', 'catalog') list_display_links = ('id', ) search_fields = ('name', ) list_editable = ('name', 'price', 'is_published', 'available', 'catalog') list_filter = ('is_published', 'available', 'created', 'catalog') ` settings.py ` MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ` shop/urls.py ` urlpatterns = [ path('', index, name='home'), path('about/', about, name='about'), path('catalog/', catalog, name='catalog'), path('basket/', cart, name='cart'), path('register/', register, name='register'), … -
How to Run an ML model with Django and Celery
I have a Django project that uses a model("deepset/roberta-base-squad2") to make some predictions. The server receives a request with parameters which trigger a queued function. This function is what makes the predictions. views.py class BotView(GenericAPIView): serializer_class = BotSerializer def post(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() print(serializer.data) return Response(data=serializer.data, status=status.HTTP_200_OK) except Exception as e: print(str(e)) return Response(data=str(e), status=status.HTTP_400_BAD_REQUEST) serializers.py class BotSerializer(serializers.Serializer): questions = serializers.ListField(required=True, write_only=True) user_info = serializers.CharField(required=True, write_only=True) merchant = serializers.CharField(required=True, write_only=True) user_id = serializers.IntegerField(required=True, write_only=True) def create(self, validated_data): # call ai and run async upload_to_ai.delay(validated_data['questions'], validated_data['user_info'], validated_data['merchant'], validated_data['user_id']) return "successful" tasks.py @shared_task() def upload_to_ai(questions:list, user_info:str, merchant:str, user_id:int): model_predictions = predict(questions, BotConfig.MODEL, user_info) print(model_predictions) return Every time I send a request, the models begins to run as show my the image but it never goes past 0%. THIS BEHAVIOUR ONLY HAPPENS WHEN IT'S HOSTED BUT NEVER IN MY LOCAL. DOCKER IN MY LOCAL HAS THE SAME ISSUE. -
Implementation CyberSource in Python
I am trying to implement CyberSource´s Microform in Python, but there is a problem with the captureContext I am sending to the frontend. This is the message error: r {name: 'MicroformError', reason: 'CAPTURE_CONTEXT_INVALID', message: 'You have not supplied a valid capture context.', informationLink: 'https://www.cybersource.com/products/payment_security/secure_acceptance', correlationId: undefined, …} correlationId: undefined details: undefined informationLink: "https://www.cybersource.com/products/payment_security/secure_acceptance" message: "You have not supplied a valid capture context." name: "MicroformError" reason: "CAPTURE_CONTEXT_INVALID" captureContext I am sending is something like this: {"kty":"RSA", "use":"enc", "kid":"08ajMBidgTrHvGJVzpR3ZxrNylkXqVA1", "n":"i6vpy5CdziPfwAMk6YyQxfLE2xGjA11gRzp1pL_LwIL87gSSsevZgRRVkI_Y2Jv95wT12O0DgumypVeHcGXmW5oR5tBJNhGp61f2qYHhl4PGMXyYFZ5OTgRYfJ2le0OYL4F4eQdqGd25ghq3qJkMvEN-USLyEGsNfeLwGvHsVtlJK9_QnKshcc-2oT2sKSNIkwxs7FH6afHc67WJUCFtqQQARJBX45O47MSlRbpRHAqJkw2zD35l6RDMQpRAKLzbJ9-cmsZpdWAhCTAvaSU2yH-LvVeEvzfDjWPrd6QcPpV_FYHxO1lHE18rmJHFTow6-LURaLQwl1PuG-C7PI2pZw", "e":"AQAB"} I am using this code to generate the key: def generate_key(compra, medio_pago): encryptionType = "RsaOaep" targetOrigin = "http://localhost:8000" requestObj = GeneratePublicKeyRequest( encryption_type = encryptionType, target_origin = targetOrigin ) requestObj = del_none(requestObj.__dict__) requestObj = json.dumps(requestObj) format = "legacy" try: config_obj = PagoCyberSource(medio_pago).get_configuration() api_instance = KeyGenerationApi(config_obj) return_data, status, body = api_instance.generate_public_key(format, requestObj) print("\nAPI RESPONSE CODE : ", status) print("\nAPI RESPONSE BODY : ", body) return return_data except Exception as e: print("\nException when calling KeyGenerationApi->generate_public_key: %s\n" % e) And these are the Microform and scripts ({{boton_compra.jwk}} is the captureContext): <h1>Checkout</h1> <div id="errors-output" role="alert"></div> <form action="/token" id="my-sample-form" method="post"> {% csrf_token %} <div class="form-group"> <label for="cardholderName">Name</label> <input id="cardholderName" class="form-control" name="cardholderName" placeholder="Name on the card"> <label id="cardNumber-label">Card Number</label> <div id="number-container" class="form-control"></div> <label for="securityCode-container">Security Code</label> <div id="securityCode-container" class="form-control"></div> … -
Django regroup tag get fields values
I have a web page where I have 2 models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I'm getting the categories from the model Products since is the one the page is using to show the products. When I try to filter catching the value from the regroup and pass it to my view: class Categoria_Filter(ListView): model = Productos paginate_by = 10 template_name = 'mail/category-filter.html' def get_queryset(self): categoria = self.kwargs['slug'] print(categoria) if categoria == 'Todos': return Productos.objects.all() else: return Productos.objects.filter(categoria = categoria) I get the following result when printing: GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>]) which according to the docs is a namedtuple() I have tried the following: print(getattr(categoria, 'GroupedResult')) print(getattr(categoria, 'grouper')) print(getattr(categoria, 'Categorias')) They all give me: AttributeError: 'str' object has no attribute 'whatever field I have tried* Also, I print by index and for example: print(categoria[1]) gives me r Which I know is the r from GroupedResult and what I want to get from the namedtuple is Guantes de Box not: GroupedResult(grouper=<Categorias: **Guantes de Box**>, list=[<Productos: Guantes … -
The view basket.views.basket_add didn't return an HttpResponse object. It returned None instead
So when previously i tried to add the price, it worked. When I added the quantity of the product something failed. I watched many times but without luck. If someone can help me I would be grateful. So that is my the error:enter image description here Then there is my views: enter image description here The html, and jquery/css: enter image description here and finaly my add func: enter image description here I have to return the quantity with the success console log in the ajax in the chrome console. I tried to change the data type, adding more advanced error func to show me more indept error in the browser, refreshing the session, watched all the names that I have to see if I typed some name wrong.