Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to prevent deleting multiple objects at once from leaving <2 objects remaining in the Django admin site?
I have a Highlight class with a ForeignKey relationship to the Organism class. On the admin site, Highlights are an inline of Organism. I want each organism object to have 2-5 highlights. I want it to be impossible to use the Organism admin page to delete highlights from an organism in a way that leaves <2 remaining. In models.py: class Organism(BaseModel): ... class Highlight(BaseModel): organism = models.ForeignKey(Organism, on_delete=models.CASCADE) ... class HighlightAdmin(admin.ModelAdmin): ... In admin.py: class HighlightInline(admin.TabularInline): model = Highlight max_num = 5 extra = 1 min_num = 2 ... line_numbering = 0 def count(self): return self.line_numbering def line_number(self, obj): self.line_numbering += 1 return self.line_numbering def has_delete_permission(self, request, obj=None): messages.add_message(request, messages.ERROR, ( request.POST.dict(), request )) if obj.highlight_set.count() > self.min_num: return True elif obj.highlight_set.count() == self.min_num: return False messages.add_message(request, messages.ERROR, ( "Can't have fewer than 2 highlights" )) return False # return return super().has_delete_permission(request, obj) class OrganismAdmin(admin.ModelAdmin): inlines = [HighlightInline] ... admin.site.register(Organism, OrganismAdmin) admin.site.register(Highlight, HighlightAdmin) The function has_delete_permission counts the number of highlights associated with the organism we are deleting highlights from. When there are 0-2 highlights, there are no Delete checkboxes (which is intended). When there are >2 highlights, there are Delete checkboxes. If I have 3 highlights and delete one … -
Customizing Django Admin filters
I’m running an old Django 1.3 website. We use the admin pages to view the models. One of the fields of the model is the User accounts. Filtering is enabled on the admin page for the User field. The problem is that I want it to list only active users. Or better yet, only to show users that exist in the instances of the model. Later versions of Django has a feature that can easily do this. I.e.: list_filter = [ ("author", admin.RelatedOnlyFieldListFilter), ] Is there a way to do this in 1.3? I hope to avoid doing an update, simply to make this one change. Thanks. -
Django: CSRF Verification always fails
So I have separate frontend and backend servers and when I'm performing any POST action from my frontend I'm passing a "Cookie" header with csrftoken inside, but for some reason it's not working. Then I've tried to pass in the csrftoken alone in the header, but it's still the same error. The strange part is that I can't see it in django request.META or request.headers. I use nginx for a reverse proxy and I use TLS for encryption. This is the strange part, where is the header at? X_CSRFTOKEN and Cookie is being passed from my frontend Django and django-cors config (And yeah I have all the required middlewares and in the right order): NOTE: When http://dev.admin.lt is removed I get another error: (Origin checking failed - http://dev.admin.lt does not match any trusted origins.): /auth/login/ CORS_ALLOWED_ORIGINS = [ "https://127.0.0.1", "https://admin.lt", "https://dev.admin.lt", "https://api.admin.lt", "http://dev.admin.lt", # NOTE, without this we get another error ] CSRF_TRUSTED_ORIGINS = [ "https://127.0.0.1", "https://admin.lt", "https://dev.admin.lt", "https://api.admin.lt", "http://dev.admin.lt" # NOTE, without this we get another error ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_DOMAIN = ".admin.lt" # Is this actually doing anything? SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN … -
Django backend can't connect to reddis?
i am asking the question with a questionmark because i don't actually know if this is the problem. For context everything worked fine on my local env. where i use docker-compose with reddis. I have a react frontend that does a websocket connection to the backend. The websocket connects to a azure caching for reddis service. Now i am using SSL for this connection and i am setting the right variables for my CHANNELS_LAYER config. My docker logging gives me this, so i know i am setting the right env's {'default': {'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': {'hosts': [('rediss://name.redis.cache.windows.net', 6380, 'REDDIS_PASS')]}}} My settings.py: redis_host = os.environ.get('REDIS_HOST', 'localhost') redis_port = int(os.environ.get('REDIS_PORT', 6379)) redis_password = os.environ.get('REDIS_PASSWORD', '') use_ssl = os.environ.get('USE_SSL', 'False') == 'True' redis_scheme = 'rediss' if use_ssl else 'redis' redis_url = f"{redis_scheme}://{redis_host}" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [( redis_url, redis_port, redis_password )], }, }, } Now my frontend does a ws connection like this: const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${wsProtocol}//name-api.azurewebsites.net/ws/endpointurl/`; const ws = new WebSocket(wsUrl); ws.onmessage = event => { const message = JSON.parse(event.data); switch (message.type) { case 'send_progress_update': setProgress(message.progress); console.log(newTabIndex); if (message.progress === 100) { if ( (grids.length === 1 … -
Predefined performance evaluation per user
I am trying to make an app for the performance evaluation of workers by their boss. For this, there is a database with information on the workers, from which information such as the ID must be extracted, in such a way that to evaluate a worker, personal information must be passed as a parameter in the url of the form and The evaluation is displayed with some complete fields of personal information and 15 questions to answer and stored in a new table to later report on the data. A worker can have many evaluations, for example one monthly. However, I can't get it to work. At first I tried to do it with 2 models, but when it didn't work, I added a third one that would relate to the previous 2. I think the error is in view.py, can someone help me please? Models.py: from django.db import models # Create your models here. nota= ( ('25','Casi Nunca'), ('50','Algunas Veces'), ('75','Con Frecuencia'), ('100','Siempre'), ) recomienda = ( ('0', 'no'), ('100', 'si') ) class Trabajador(models.Model): nombre = models.TextField(max_length = 50, null=False) codigo = models.TextField(max_length = 8, primary_key=True, null=False, unique=True) rut = models.TextField(max_length = 10, null=False, unique=True) cargo = models.TextField(max_length = … -
Reading data corresponding to a specific ID from the database and passing the data to an API
I am trying to fetch data from a database table named "orders_address" by specifying the required ID in the request body and I expect to receive the row for this specific ID along with an API result in the response. However, I can't get fetch the data for this specific ID from the database. I am using DJANGO. I am applying this request body: { "orders": [1] } and my response results is: {"error": "No orders found for the given order IDs."} Here is my route_optimization.py script which does the function needed: import requests from django.http import JsonResponse from orders.models import Order import configparser import json # Read configuration file config = configparser.ConfigParser() config.read('config.ini') # Get Nextbillion.ai API key from config NB_API_KEY = config['API_KEYS']['NB_API_KEY'] def optimize_route(request): if request.method == 'POST': try: data = json.loads(request.body) order_ids = data.get('orders', []) print("Received order IDs:", order_ids) # Debugging statement # Fetch orders from the database based on order IDs orders = Order.objects.filter(id__in=order_ids) print("Orders:", orders) # Debugging statement # Ensure that orders are retrieved if not orders: return JsonResponse({'error': 'No orders found for the given order IDs.'}) # Construct list of delivery locations for Nextbillion.ai API payload delivery_locations = [ {"latitude": order.address.latitude, "longitude": order.address.longitude} for … -
Case-insensitive filter in Django admin using SimpleListFilter
I have a SimpleListFilter in the Django admin panel that filters values (ingredients) based on their first letters (see the code below). The issue is that ingredients could be saved/updated in the database with either uppercase or lowercase letters. Because of this, the filter starts behaving incorrectly, displaying two fields for the same letter (for example, A(1) and a(70)). I've addressed the problem by overwriting CharField in my models (see the code below). But I'm not satisfied with this solution as it's not universal. Is there a way to make this filter case-insensitive without modifying the values before adding them into the database? I want the filter to work regardless of the letter case. (for example, A(71)). class FirstLetterAlphabetiseFilter(admin.SimpleListFilter): title = _('First letter') parameter_name = 'first_letter' def lookups(self, request, model_admin): ingredients = model_admin.get_queryset(request) for letter in sorted( ''.join(set(ingredient.name[0] for ingredient in ingredients)) ): count = ingredients.filter(name__istartswith=letter).count() if count: yield (letter, f'{letter} ({count})') def queryset(self, request, ingredients): if not self.value(): return ingredients return ingredients.filter( name__istartswith=(self.value())) class NameField(models.CharField): """Converts NameField into lower case while saving in database.""" def __init__(self, *args, **kwargs): super(NameField, self).__init__(*args, **kwargs) def get_prep_value(self, value): return str(value).lower() -
How can i modify the serializer.is_valid() method for existing rows on the database so it passes the validation
**I am trying to insert a list of objects by using serializer.save() but when i try to insert existing data it throws error and doesn't pass the validation how can i modify the is_valid() method or is there any way of skipping the existing objects and inserting the others inside the method ** //Saving data = sanitizer.to_dict() serializer = serializer_class(data=data, many=True) if serializer.is_valid(raise_exception=True): serializer.save() //Serializer from apps.trades.models import Trade from rest_framework import serializers class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ['identifier', 'issue_date', 'maturity_date', 'invested_amount', 'interest_rate'] The validation error: [{"identifier":["trade with this identifier already exists."]} -
redirect https non-www to https www for nginx django
I tried many solutions but nothing worked. I am trying to redirect https://example.com to https://www.example.com. If I write https://example.com in the address bar, I get an insecure website prompt. I have ssl certificate installed for www.example.com. Here's the code from nginx server: server { server_name exmaple.com www.exmaple.com; location ~ ^/.well-known { root /home/xyz/xyz-dir; allow all; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xyz/xyz-dir; } location /media/ { root /home/xyz/xyz-dir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.exmaple.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.exmaple.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.exmaple.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = 'exmaple.com') { return 301 https://www.$host$request_uri; } # managed by Certbot listen 80; server_name exmaple.com www.exmaple.com; return 404; # managed by Certbot } -
How to implementing Razorpay Test Mode Withdrawal in Django Web App
I'm in the process of developing a Django web app where users can initiate withdrawals with the following flow: On the website, users have the option to withdraw a specific amount. Upon clicking the withdraw button, users are directed to the next page. On this page, users are prompted to enter their bank details. After saving the bank details, users can click the "Continue" button. At this point, I want the specified amount to be automatically transferred to the entered bank account, all while operating in Razorpay's test mode. I would greatly appreciate any insights, code examples, or references on how to implement this flow effectively. Your help is invaluable. Thank you! -
Subclassed Django SelectMultiple ignores any attribute set to its options
following what I found in this answer I am trying to add a custom class to each option into the two select the widget produces. I used the FilteredSelectMultiple admin widget, which is made of two list of elements the user can interact with to select one or more elements. My relevant code: from django.contrib.admin.widgets import FilteredSelectMultiple class MySelectMultiple(FilteredSelectMultiple): def create_option(self, name, value, *args, **kwargs): option = super().create_option(name, value, *args, **kwargs) print(option) option.update({'attrs': {'foo':'bar'}}) # set option attribute print(option) return option from django import forms class MyReportForm(forms.Form): filters = forms.ModelMultipleChoiceField( queryset= Item.objects.none(), # fixed below widget=MySelectMultiple("Item", is_stacked=True), required=False ) def __init__(self, *args, **kwargs): from myapp.utils import get_all_enabled_items super(MyReportForm, self).__init__(*args, **kwargs) # this returns a filtered queryset self.fields["filters"].queryset = get_all_enabled_items(lvl0=True) The dictionary gets updated correctly if printed, but the form just ignores the attributes I set and produces the same HTML: <select name="generic_filters" id="my_id_from" multiple="multiple" class="filtered" data-is-stacked="1"> <option value="1" title="myTitle1">myTitle1</option> <option value="2" title="myTitle2">myTitle2</option> <option value="3" title="myTitle3">myTitle3</option> </select> Please note that if I try to change the "value" using the same code (with option.update({'value':'0'}), the value correctly changes (and makes all the options have the same value!) What am I doing wrong? How do I set an attribute for each select option … -
Django mysql database eats too much RAM even though no queries are coming in
I rented a small vps(1core 1gb-ram 15ssd) for my Django project. When I added another endpoint to the project, the database on the server suddenly started crashing from lack of RAM (the process was simply killed by the system). Attempts to restart the database with the systemctl restart command resulted in an error, and I was unable to restart the database until I shut down another process(telegram integration) to free up memory. My queries are optimised. Hoping to ease the load on RAM, I changed the innodb_buffer_pool_size and key_buffer_size configurations within 1-16M, but the situation didn't change much. Having increased the server rate to 2gb of RAM, I found that RAM consumption increased (mysql's VIRT value in htop before the upgrade was ~1200, now it is ~1600). Are these normal values of RAM consumption? Why is the database consuming so many resources while idle? How can I redistribute the load between cpu and ram? Why did adding a feature to django affect the database so much(before even using it)? I would really appreciate a detailed explanation of Django's behavior and its impact on the DB, or any advice -
Django not able to authenticate username and password , although data is present is db and the entered data is checked correctly
view.py def loginverify(request): print("-----------login verification------------") if request.method == "POST": cemail = request.POST.get("cemail") cpassword = request.POST.get('cpassword') print(cemail, cpassword) (able to print the data sent ) User = authenticate(request, email=cemail, password=cpassword) print(User)-->(this shows none) if User is not None: login(request, User) print("no problem") messages.success(request, 'Login successful') return redirect('dashboard') # Redirect to the user's dashboard or landing page else: messages.error(request, 'Invalid email or password') print("problem occurred") template = 'polls/login.html' return render(request, template) # Redirect to login page template = 'polls/CustLandingpage.html' return render(request, template) *well the data is received by this function but the authentication is not working * model.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Customer(models.Model): name = models.CharField(max_length=20) Email = models.CharField(max_length=50) password = models.CharField(max_length=20) USERNAME_FIELD = 'Email' REQUIRED_FIELDS = ['name'] for authentication email and password is used , I tried most of the things but its not working , kindly help -
How to call a View function from another one on Python Django
I'm creating a project that gets NBA data from an API with Python-django. I got a view that renders the index.html page and created another one that generates the data and save it on a model. I think it's completely wrong but i'm kinda stuck....Basically I want to display the index.html page with all the objects on the model Post (at this time this part works), but I also want to call the view "Pontos" to create the posts automatically if some parameter it's called (example, I would create a IF to see if the datetime was 11 o'clock. If it's true, then call the 'Pontos' view to generate the data that would be displayed on index.html) but I don't know how to call the view on another view. Can someone explain to me what I could do to solve this ? I tried creating and IF on the index view to call the Pontos view, but when the Pontos View it's called, it returns his own index.html without the parameters needed....resulting in a blank page. -
How to display the date one day ahead?
Well, currently I only display the 'calendar' with the current date. I would like the current date to be displayed in one field, and the next date to be displayed in the next one, up to 5 days later. def Schedule(request): date = datetime.date.today() report=Submissions.objects.filter(execution_date=date) context={ 'date':date, 'report':report, } return render(request, 'staff/work_schedule.html', context) <div class="row no-gutters" style="width: 100%;"> <div style="width: 100%;background-color: rgb(0, 0, 0);color: white;font-weight: 800;font-size: 12px;">{{date}}</div> <table class="table table-striped table-hover"> <tbody> {% for qs in report %} <tr style="font-size: 10px;text-align: center;"> <th style="width: 8%;">{{qs.client.user.get_full_name}}, tel.:{{qs.client.phone_number}}</th> <th style="width: 8%;">{{qs.client.post_code}} {{qs.client.city}}, ul.{{qs.client.street}}</th> <th style="width: 40%;">{{qs.contents|linebreaks|truncatewords_html:50}}</th> <th style="width: 40%;">{{qs.details_planned_service|linebreaks|truncatewords_html:50}}</th> </tr> {% endfor %} </tbody> </table> <div style="width: 100%;background-color: rgb(0, 0, 0);color: white;font-weight: 800;font-size: 12px;">29 styczeń 2024</div> <div style="width: 100%;background-color: rgb(0, 0, 0);color: white;font-weight: 800;font-size: 12px;">30 styczeń 2024</div> </div> -
why notification message is not showing in off canvas
this my balance.html code {% extends "money/index.html" %} {% load static %} {% block body %} <div class="blatitle"> Balance </div> <div class="bladiv"> <div class="amtext"> Available Amount : ₹ {{ user.bankaccount.balance}} </div> </div> <button id="notification-button" onclick="toggleOffCanvas()"> Notification <span id="notification-badge" class="badge badge-danger">{{ unread_notifications|length }}</span> </button> <div id="offCanvas"> <!-- Off-canvas content --> <div id="offCanvasContent"> <ul id="notification-list"> {% for notification in unread_notifications %} <li>{{ notification.message }} <button class="mark-as-read" data-notification-id="{{ notification.id }}">Mark as Read</button></li> {% endfor %} </ul> {% if unread_notifications %} <button id="mark-all-as-read">Mark All as Read</button> {% else %} <p>No notifications.</p> {% endif %} </div> </div> <div id="overlay"></div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function () { // AJAX to mark a notification as read $(".mark-as-read").click(function () { var notificationId = $(this).data("notification-id"); $.ajax({ type: "POST", url: "/mark_notification_as_read/", data: { notification_id: notificationId }, success: function () { // Reload the page or update the UI as needed location.reload(); }, error: function (xhr, status, error) { console.error("Error marking notification as read:", error); }, }); }); // AJAX to mark all notifications as read $("#mark-all-as-read").click(function () { $.ajax({ type: "POST", url: "/mark_all_notifications_as_read/", success: function () { // Reload the page or update the UI as needed location.reload(); }, error: function (xhr, status, error) { console.error("Error marking all notifications as read:", … -
How to correct use django_db_setup (pytest-django)
I try to test my Django app and confused about using test database. # conftest.py @pytest.fixture(scope="session") def django_db_setup(): settings.DATABASES["default"] = { "ENGINE": "django.db.backends.sqlite3", "NAME": "db.sqlite3", } My test files look like this: # tests.py @pytest.mark.django_db def test_mailing_detail(mailing_instance_one): obj_link = mailing_detail(mailing_instance_one) expected_link = reverse( "api:admin_mailing_detail", args=[mailing_instance_one.id] ) assert f"<a href='{expected_link}'>" in obj_link Output: django.db.utils.OperationalError: could not translate host name "app_db" to address: Temporary failure in name resolution app_db is name from app settings file. If I add print(f"{settings.DATABASES['default']}") to django_db_setup() I see correct db parameters. How I can use test database? -
Managing image files in django. Separation of administrative photos of the site and photos of users
I'm begginer in django and doing my first car blog project. I am concerned about the question of how to correctly separate the photos that the user uploads to the page (when adding a new post, creating a profile, etc.) and the photos that are uploaded from the administrative panel (adding a photo category when creating it). As far as I know it is not recommended to store it all together. I made the following directory settings.py MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / "media" Maybe there are some tips or solutions that are used in real projects.Thanks in advance! -
Python Plotly fill between two specific lines
I've seen this question asked before in some form or the other, but never answered entirely, so i'll try my luck. In a plot with several traces, i’m trying to fill the areas between two specific lines that i choose. The desires effect, achieved with matplotlib.pyplot looks like this: desired plot where the cyan and orange areas are filled between their respective trends, and up/down to the red line. The black line is unrelated to those filled areas, but should be plotted along with the blue line regardless. I tried achieving this with Plotly’s fill: 'tonexty', but this doesn’t work out well because due to the randomness of the data, the nearest Y is sometimes the black line and not the red. I can achieve this with pyplot's fill_between function: plt.fill_between(x, y1, y2, color, alpha) Where it can be used as: from matplotlib import pyplot as plt import numpy as np import pandas as pd series1 = pd.Series(np.random.randn(100), index=pd.date_range('1/1/2000', periods=100)) series2 = ts + np.random.randn(len(ts)) positive_contribution = ts2 + 0.5 negative_contribution = ts2 - 0.5 plt.plot(series1, color='black') plt.plot(series2, color='red') plt.fill_between(ts.index, series2, negative_contribution, color='cyan', alpha=0.2) plt.fill_between(ts.index, series2, positive_contribution, color='orange', alpha=0.2) I’d love to hear of a solution / workaround for this. … -
On stripe payment failure update the subscription, what would happen to the failed invoice
I am trying to downgrade the user from annual to quarterly if the payment fails. Which will update the subscription and try to charge the user(with a new invoice) due to proration behaviour, My question is would stripe still retry the failed invoice? I am worried that it will charge the user 2 times. -
Enter key on input field make the webpage redirect to prev step in Django wizard
I have django wizard contains 4 steps: the first step is account step where user enters the account information the second step is personal information, at this step I have some problem: when the user press enter on some input field ( like card num field) the webpage redirect the user to the previous step ( Account step ), the account page returned with all fields filled except passwords ( they are return empty) I will show snapshot of the webpage the form, and I will provide the code: <form method="post" enctype="multipart/form-data" class="multiStep-form style-one simplePresentCart-two"> <div class="row"> {% csrf_token %} {{ wizard.management_form|crispy }} {% if wizard.form.forms %} {{ wizard.form.management_form|crispy }} {% for form in wizard.form.forms %} {% crispy form %} {% endfor %} {% else %} {% crispy wizard.form %} {% endif %} <div class="multiStep-footer"> <div class="multiStep-footer-flex"> <div class="multiStep-footer-left"> {% if wizard.steps.prev %} <button formnovalidate name="wizard_goto_step" type="submit" class="primry-btn-2 lg-btn" value="{{ wizard.steps.prev }}">{% translate "prev step" %}</button> {% endif %} </div> {% if wizard.steps.current == wizard.steps.last %} <div class="multiStep-footer-right"> <input type="submit" class="primry-btn-2 lg-btn" value="{% translate "Register" %}"/> </div> {% else %} <div class="multiStep-footer-right"> <input type="submit" class="primry-btn-2 lg-btn" value="{% translate "Next" %}"/> </div> {% endif %} </div> </div> </div> </form> I have … -
Display Generated Map File of Folium in index.html [Django/Python localhost]
I am trying to display the 'output.html' (The generated Map File using Folium) to be displayed in index.html. Currently I was able to generate the Map without a problem and it is currently stored in BASE_DIR/media (which is where I want it to be stored) Here's my snippet code for views.py: def index(request): # Existing code... final_map = map_init(request) context = { 'gpx_dictionary': gpx_dictionary, 'final_map': final_map } return render(request, 'index.html', context) def map_init(request): #Existing code logic... final_map.save(temp_file_path) return final_map and here's my snippet code for index.html (Currently displaying the map inside the card body): <div class="card col-md-6 mb-4 mx-auto" id="mapResult"> <div class="card-header text-center bg-primary-subtle text-emphasis-primary"> <strong>MAP RESULT</strong> </div> <div class="card-body"> <div id="map-container"> {{ final_map | safe }} </div> </div> </div> It just refreshes the page without displaying the map, How can I Properly display the map on index.html? -
Need inputs on Web application development
I need inputs on tech stack used for building a web application. Currently I'm using Angular with Django in my application. But when I'm trying to query SQL databases using Django in my code, if the datasets are with heavy data Django is not completing the query. How make this work? Can we use any other technology as backend for Angular to work on large datasets? Please share your thoughts on this.. I tried with Django but it's giving timeout issues and exiting out of api. Note: I need to show the result in Angular UI after processing. So I need a better framework that handles heavy processing. -
why the django restframework's "request" not working?
I have below DRF code that is instantiating a class that has GET method, from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request from rest_framework import status class MrgCompInsert(APIView): def post(self, request): try: # Use rest_framework.request.Request to make the initial request merge_company_info_view = MrgCompInfo.as_view()(Request(request)) organization_data_response = merge_company_info_view.data if organization_data_response.status_code == status.HTTP_200_OK: # Access the data attribute from the Response object organization_data_post = organization_data_response.data post_url = 'https://example.com/ # Use rest_framework.request.Request to make the subsequent request merge_to_kloo_post = Request(request).client.post(post_url, organization_data_post, format='json') if merge_to_kloo_post.status_code == status.HTTP_200_OK: return Response({'message': 'Data sent successfully to the second API'}, status=status.HTTP_200_OK) else: return Response({'error': 'Failed to send data to the second API'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response({'error': 'Failed to retrieve Category list'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) and then doing a POST on an another restful API. The GET APIView class individually is working fine. But the POST APIView class is causing issue, and I am getting below error. HTTP 500 Internal Server Error Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "error": "The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`." } Then imported request from django.http as shown below from django.http import HttpRequest organization_data_response = MrgCompInfo(HttpRequest) merge_to_post = … -
In Django, when I click a button, I can't satisfy a condition that should be True and then display a panel on the screen
There is a problem in my code but I can't figure out what it is and how to fix it. The code consists of clicking on a button and displaying a panel (redPanel) in the center of the screen that overlays the index.html page. However, the panel must be displayed only if there are both <html> and <head> tags in the textarea. If, however, there is only one of the two tags, then the panel should not be displayed. The condition is found in the custom_tags.py file and for the sake of order and cleanliness I would like it to remain in that file. PROBLEM: In the textarea there are both <html> and <head>, so the condition (if) should be True, but when I click on the button then it does not open panel (redPanel) in the center of the screen. The problem should be in the def only_checkend function of the custom_tags.py file or in the def checkend function of the views.py file or in the javascript script (in index.html). I show you minimal code of all files (including javascript script with fetch). I hope someone can figure out the problem and show me the solution code. index.html {% …