Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ValueError at /en/admin/auth/user/ year -1 is out of range
i have production django server one of the users with id 399 is causing this error every time it included in search results, the user model i am using is the default django User model. Django Version: 4.0.10 Exception Type: ValueError Exception Value: year -1 is out of range Exception Location: ../.venv/lib64/python3.9/site-packages/django/db/utils.py, line 98, in inner Python Executable: ../.venv/bin/python3.9 Python Version: 3.9.18 database : Postgresql 10.23 even when i go to the django admin page and trying to delete the user the same error raised but it is possible to delete any other user. -
Unable to link a model Object to another model, which takes in a OnetoOnefiled
So I have a login page, which also has an option to register if you're a new user. The registration phase consists of two pages, one where the user enters their personal information, and two where the user sets the username and password. Right now I am storing them as strings just to get my website running. I am successful in creating a model object for the personal information, and also successful in linking that object to the newly created login details object. I am trying to compare the entered values of the user on the login page to the objects stored in the database and once they match, I want to be able to retrieve the role of the user, which is a part of the UserData object and navigate to the appropriate dashboard. I dont seem to to get it working Registration.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; const RegistrationPage = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const navigate = useNavigate(); const [latestUserData, setUserData] = useState(null); useEffect(() => { const fetchLatestObject = async () => { try { const … -
Django ORM get latest from each group
I have records in below format: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |2 | A |2024-04-01T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| |5 | B |2024-02-01T02:49:47.327583-07:00| Model: class Model1(model.Models): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) I want to perform a group by in django with month from field created and get latest record from that month. Expected output: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| So far, I have tried: from django.db.models.functions import ExtractMonth m = Model.objects.get(id=1) ( Model1.objects.filter(name=m.name) .annotate(month=ExtractMonth("created")) .annotate(latest_time=Max("created")) .values("month", "id") .order_by("-latest_time") ) But this is still returning be duplicate month data. Please provide some insights. -
Connect to Server signed with openssl certificate with Android Studio Virtual Device
I am creating an app on my computer with React Native as frontend and Django as backend. I had a prototype working with requests in protocol HTTP from the app to the Django server, but as I wanted to implement HTTPS, I installed Apache as a reverse proxy server and everything looks good but now, I have an error while requesting the virtual device of Android Studio to the new URL... (have to mention that from Postman it works perfectly) I think is has to do with the CA Certificate I created for using HTTPS as it is not trusted because it was created with OpenSSL. I can enter all the URLs from Django in my local network but when I try to enter them from the virtual device browser they don't render I can see that the certificate I created is there but I can't install it as the virtual device's screen goes black when I try to do that Photos: Error when fetching Local PC Virtual Device: enter image description here enter image description here Do you have any clue of what am I missing? Thanks! -
Django custom user admin not reflected in admin site
I am new to django and going through legacy django project where Custom user admin is configured with following: app1/admin.py from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): """Define admin model for custom User model with no email field.""" fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email', 'first_name', 'last_name', 'phone_number', 'type_of_user', 'timezone', 'deleted', 'is_supervisor', 'supervisor', 'role')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined', 'created_date')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username', 'password1', 'password2'), }), ) list_display = ('username', 'first_name', 'last_name', 'is_staff') search_fields = ('username', 'first_name', 'last_name') ordering = ('username',) Also in app1.models.py, where CustomUser is further inherit from AbstractBaseUser. class User(CustomUser): first_name = models.CharField(max_length=1024, db_index=True) last_name = models.CharField(max_length=1024, db_index=True) phone_number = models.CharField(max_length=1024, blank=True, null=True) is_supervisor = models.BooleanField(default=False, db_index=True) license = models.CharField(max_length=1024, blank=True, null=True) type_of_user = models.IntegerField(choices=TYPE_OF_USER, default=1, db_index=True) created_date = models.DateTimeField(default=timezone.now) timezone = TimeZoneField(choices=[(tz, tz) for tz in pytz.all_timezones]) deleted = models.BooleanField(default=False, db_index=True) load_id = models.CharField(max_length=1024, null=True, blank=True) approval_status = models.IntegerField(choices=APPROVAL_STATUS, null=True, blank=True) supervisor = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) last_alert_sent_on = models.DateTimeField(null=True, blank=True, db_index=True) role = models.ForeignKey("common.Role", on_delete=models.SET_NULL, null=True, blank=True) In settings.py: AUTH_USER_MODEL = 'app1.User' There's no admin.py in main_app folder. The problem here is that the User model … -
How can I re-filter queryset without N+1 problems in Django?
I have simple N+1 problem with queryset in Django. Simple views.py code example of the problem what I'm having. a_queryset = AA.objects.filter(user=request.user).all() # some codes in here with a_queryset . . . b_queryset = a_queryset.filter(id__in=[3,4,5]) # re-filtered # some codes in here with b_queryset . . . c_queryset = a_queryset.get(id=10) # re-filtered # some codes in here with c_queryset . . . I have N+1 problem which is three SELECT queries and I already know these codes cause it. It would be very nice to call queryset at once, but I can't because there're some tasks in the middle. What should I do? -
i am facing the issue when submiting the form of second section , the returns back to the first section insted of updating the content of curent page
User this is my script for the single page with side bar in which 4 four buttonsrespectivey for page 1 page 2 page 3 page 4, these four pages are in a single template and containing the relevant content , page is containg two form, the first form showing the drop down of the loc_ids as i selects the value from the drop down and submits the form it should update the current page content as the second form from the views file rendering the same template which containing the four pages , as the view sending the value to the template, on the front as page loading completes it showing me the first page which welcome page , instead of this how can i remain on the current page(specific section of the template), this is due to as the view rendering the template and on submiting the previus form it rediret to the second form's view which is rendering the template and when loading it show the template from the start . on tis page i have a multiple forms , here i have also same forms but rendering from diffrent views. <script> window.addEventListener('load', function() { var urlPath = … -
How to add Django admin panel widgets to custom templates?
how to you use admin panel widgets on custom templates ?? like edit, add and view -
Django is mixing 2 different translation entries and creates a fuzzy entry in the PO file
I see this in the django.po file after executing python manage.py makemessages command: #: .\homepage\models.py:40 #, fuzzy #| msgid "The logo of the site as appears on the top of each page." msgid "The logo of the brand as appears on the homepage." msgstr "لوگوی سایت که بالای هر صفحه نمایش داده میشود." The problem: #| msgid "The logo of the site as appears on the top of each page." belongs to line 20 (not 40) of models.py of core app (not homepage). There's no other entry for line 20 of models.py of the core app in the file. msgid "The logo of the brand as appears on the homepage." belongs to line 40 of models.py of homepage app. Ironically, the translated text appears for the first message (which is commented out) not the second. I have no idea why this is happening and how to fix it. This is Django v5.0.3 on Windows. -
most of time flask rest api request is aborted when authentication is failed onyl sometime it raise unauthorised error
I have a Flask REST API through which I make requests with a large XML payload. In the code, I have set it up so that when authentication fails, it should raise an 'unauthorized' error. While testing the API using Postman, I've noticed that sometimes the error is raised, but most of the time, the request is aborted whenever an authentication error occurs. Additionally, when I use the Python requests library for testing this API, I encounter a 'chunked encoding' error when the request is aborted. Could you please advise me on how to solve this problem? Also, could you explain why the request is aborted sometimes and not others? I want the API to return an 'unauthorized' error when incorrect credentials are provided, rather than aborting the request, as it currently does inconsistently. Sometimes it works as intended, but other times it simply aborts the request without providing the appropriate error response. How can I ensure that the API consistently returns an 'unauthorized' error when unauthorized access is detected? -
Want to retrieve the id of the latest object created in a model
So I am creating a login page. I am trying to register a user and then login. In the registration of my user, the user is prompted to fill in details in a form, and then the next step is to create username and passoword. So the problem I am facing is that the personal information entered is a different model, and I want to retrieve the id of the latest object created so that I can link them with the username and password. Here is my code for it Models.py class UserData(models.Model): ROLE_CHOICES = ( ('Recruiter', 'Recruiter'), ('Manager', 'Manager'), ('Business Development Partner', 'Business Development Partner'), ('Business Development Partner Manager', 'Business Development Partner Manager'), ('Account Manager', 'Account Manager'), ) fullName = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=10, blank=True, null=True) aadhaarNumber = models.CharField(max_length=12, blank=True, null=True) dateOfBirth = models.DateField(null=True, blank=True) maritalStatus = models.CharField(max_length=20, blank=True, null=True) emergencyContact = models.CharField(max_length=255, blank=True, null=True) address = models.TextField(blank=True, null=True) phoneNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) emailID = models.EmailField(validators=[EmailValidator()], blank=True, null=True) emergencyContactNumber = models.IntegerField(validators=[MinValueValidator(0000000000), MaxValueValidator(9999999999)], blank=True, null=True) jobTitle = models.CharField(max_length=100, blank=True, null=True) departmentName = models.CharField(max_length=100, blank=True, null=True) joiningDate = models.DateField(blank=True, null=True) employmentType = models.CharField(max_length=100, blank=True, null=True) prevCompany = models.CharField(max_length=255, blank=True, null=True) prevDesignation = models.CharField(max_length=100, blank=True, null=True) relevantSkills = … -
Asynchronous scraper + Django
I'm trying to create an application that displays information to the user from an asynchronous scraper. The scraper must work independently and continuously. The user, when visiting the desired page of the site, must automatically subscribe to the flow of an independently working scraper. For example: the scraper works using while True. It collects, processes and sends processed data. The user has visited the site and should be able to see the data that the scraper gave during its last iteration. When the scraper again collected, processed and returned the data, the user’s data should be automatically updated, and so on in a circle. Unfortunately, I can’t show you the project code due to confidentiality. Next I will describe the methods that I found and tried to apply. All of them are somehow related to Django Channels and multiprocesses and threads. Which of these methods is the most correct and how to connect your scraper correctly? Maybe I missed some other method, I don't know. Multiprocessing, Pipe. It was suggested to create a separate script process (in my case, an asynchronous scraper) and use Pipe to pass this data to another script (in my case, Django View). Websockets. Create an … -
Extract data from DB or populate it with fixtures before running tests
My pytest runs do not extract the db in the real database which I believe is normal as test DB is initially empty. Part of my code requires that I fetch the id of a page in an existing model. def result_page_get_id_from_slug(slug): print(ContentPage.objects.values().last()) obj = ContentPage.objects.get(slug=slug) return obj.id There's no way I can do this in tests sice test db is empty. So I keep gettign the following error: home.models.ContentPage.DoesNotExist: ContentPage matching query does not exist. When I try to print all objects during testing I get None meaning that ContentPage model is empty during test run. print(ContentPage.objects.values().last()) How can I populate it please. Thanks -
Django is not raising validationerror
class confirm_password_form(forms.Form): password = forms.CharField(label="Password",widget = forms.PasswordInput,required=True) confirm_password = forms.CharField(label="Confirm_Password",widget = forms.PasswordInput,required=True) def clean(self): print("this is clean") cleaned_data = super().clean() password = self.cleaned_data["password"] confirm_password = self.cleaned_data["confirm_password"] print("in clean password ",password) print("in clean confirm_password",confirm_password) if password!=confirm_password: print("this is not equal condition") raise forms.ValidationError("both password should be match") "In above code django is not raising the validationerror. It is printing 'this is not equal condition' but it is not raising error. I have tried available solutions. -
Django HttpStreamingResponse Not Streaming
I have a very interesting issue with the Django HttpStreamingResponse. Our server calls OpenAI Text Completion API in streaming mode, upon receiving the chunks from OpenAI, we incrementally parse the chunks and stream complete JSON objects back to our clients. Below are some code snippets: views.py class StreamViewSet(ModelViewSet): ... def stream(self, request): ... json_stream = agent.get_json_objects() return StreamingHttpResponse(json_stream, content_type="application/json") agents.py def stream(self): yield from self.json_agent.get_json_stream() json_agent.py def get_data_stream(self): # This calls OpenAI text completion API with stream=True stream_response = self.get_text_completion(user_preference, stream=True) # Create an incremental json parser json_stream_parser = JsonStreamParser() for chunk in stream_response: if chunk.choices and chunk.choices[0].delta.content is not None: json_stream_parser.feed(chunk.choices[0].delta.content) yield from json_stream_parser.parse() json_parser.py class JsonStreamParser: """A simple JSON stream parser that can parse a stream of JSON objects. Note it only works for an array of JSON objects, which means the input must contain a valid JSON array, at any point of the stream, that starts with '[' and ends with ']'. It will parse the JSON objects in the array and ignores anything outside of the array. """ def __init__(self): self.buffer = "" self.index = 0 self.open_braces = 0 self.start_index = -1 self.array_started = False def feed(self, data): self.buffer += data def parse(self): parsed = [] … -
Custom Django admin login with django allauth package
I want a functionalities where when user login to admin page, either using username and password, or using google sso (using allauth package). they still need to go for a certain check. Now I have this views where i state my checks: views.py def custom_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): user = form.get_user() # Check if the user belongs to a specific group print(user) check_in_wd = check_user_in_wd(user) if (user.groups.exists() or user.is_staff) and check_in_wd: login(request, user) return redirect('/admin/') # Redirect to admin dashboard after successful login else: messages.error(request, 'You are not authorized to access the admin page.') else: messages.error(request, 'Invalid username or password') else: form = AuthenticationForm() return render(request, 'admin/login.html', {'form': form}) urls.py urlpatterns = [ path('grappelli/', include('grappelli.urls')), # grappelli URLS path('admin/login/', custom_login, name='custom_login'), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] login.html - just for extra refs <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>App</title> </head> <body> {% extends "admin/login.html" %} {% load static %} {% load i18n %} {% block content %} <div id="content-main"> <form id="login-form" method="post" action="{% url 'admin:login' %}" novalidate> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <label for="id_username">{{ _('Username') }}:</label> {{ form.username }} </div> <div class="form-row"> <label for="id_password">{{ _('Password') }}:</label> {{ form.password }} … -
Django queryset filter data by timestamp range at last one hour
I am trying to filter data from the Django queryset where the timestamp range has to be exactly last seven days at the last one hour. For example, I want to filter out data from today (March 31st, 2024) until March 24th, 2024 but only within the last hour (10:00 - 11:00 a.m.). What I have done so far, yet still no further improvements: qs = SuccessRateTodayData.objects.select_related('region')\ .order_by('-timestamp', 'region__region_name')\ .filter(Q(timestamp__range=(start, end))) I have tried using raw query in PostgreSQL. It's something like this: SELECT regionname, round(avg(completed)::numeric, 2) avg_completed, round(avg(failed)::numeric, 2) avg_failed FROM ( SELECT timestamp2, regionname, completed, failed, num_read, numofdata FROM "SuccessRateTodayData" WHERE timestamp2 > current_date - interval '7 days' AND (timestamp2::time BETWEEN '10:00:00' AND '11:00:00') ORDER BY regionname, timestamp2 ) t GROUP BY regionname Expected Result: Any help would be appreciated. Thank you. -
How to fix the issue with some post functions not working during autopagination?
I need help solving a problem with automatic pagination. When automatic pagination occurs from the home_list.html template to the home.html template, all functions of the template stop working, even though the template itself is paginated correctly. The functionality stops working after pagination, namely: "edit" and "delete" the published post, "Add comment", "Edit comment", "Save edited comment", "Delete comment". In the home.html template, these functions work in the {% for post in post_lists %} loop, but after automatic pagination from the home_list.html template in the {% for post in posts %} loop, these functions do not work. How can I fix this? home.html <div id="post_contenter"> {% for post in post_lists %} <div class="post_content" id="post_content"> <!-- Add identifier post_content --> <div class="post_header"> <div class="post_user_avatar"> {% if post.author.avatar %} <img style="width:50px; height: 50px;" src="{{ post.author.avatar.url }}" class="user-picture-small"> {% else %} <img style="width:50px; height: 50px;" src="{% static 'twippie/img/avatar.png' %}" class="card_user_picture_small"> {% endif %} </div> <div class="post_user_info"> <div class="post_user_fullname"><a href="{% url 'user:profile_username' post.author.username %}" class="post_user_fullname_style">{{ post.author.first_name }} {{ post.author.last_name }}</a></div> <div class="post_user_username"><a href="{{ user_profile.username }}" class="post_user_nickname_style">@{{ post.author }}</a> {% if post.author.verification %} <span class="verified_user_small"></span> {% endif %} </div> <div class="post_user_date"><a href="{{ post.get_absolute_url }}" class="post_user_date_style">{{ post.time_create }} {{ post.time_create|naturaltime }}</a></div> </div> </div> <div class="post_user_more"> <div class="dropdown … -
Django Admin Panel and Sub URLs Returning 404 Error on Deployment
have recently deployed my Django project to a server, and while the index URL (mannyebi.com) loads correctly along with static files, accessing sub URLs such as mannyebi.com/blogs or even the admin panel (mannyebi.com/admin) results in a 404 error. Locally, the project runs smoothly, indicating the issue may stem from the deployment configuration. I've ensured that all necessary URL patterns are defined in the urls.py files and that Django's admin app is properly installed and configured. However, despite these measures, I'm still encountering difficulties accessing sub URLs beyond the homepage. Is there a specific configuration step or server setting that I might be overlooking to resolve this 404 error and enable access to sub URLs on my deployment? Any insights or troubleshooting suggestions would be greatly appreciated. I deployed my Django project to a server. Upon navigating to sub URLs such as mannyebi.com/blogs or mannyebi.com/admin, I encountered a 404 error. I verified that all necessary URL patterns were defined in urls.py and that Django's admin app was properly configured. I expected these URLs to load correctly, similar to how they did on my local development environment. However, despite these efforts, the 404 errors persisted. I'm seeking guidance on resolving this issue … -
How to return HTTP Get request response from models class in Django project
I am trying to Get a response from the OpenAi assistants API using a Django project. I implement a model class inside models.py as such: from django.db import models from typing_extensions import override from openai import AssistantEventHandler from django.http import HttpResponse # Create your models here. class Eventhandler(models.Model,AssistantEventHandler): class meta: managed = False @override def on_text_created(self, text) -> None: print(f"\nassistant > ", end="", flush=True) @override def on_text_delta(self, delta, snapshot): print(delta.value, end="", flush=True) def on_tool_call_created(self, tool_call): print(f"\nassistant > {tool_call.type}\n", flush=True) def on_tool_call_delta(self, delta, snapshot): if delta.type == 'code_interpreter': if delta.code_interpreter.input: print(delta.code_interpreter.input, end="", flush=True) if delta.code_interpreter.outputs: print(f"\n\noutput >", flush=True) for output in delta.code_interpreter.outputs: if output.type == "logs": print(f"\n{output.logs}", flush=True) Now, what is important is that the Eventhandler class sends the response back to the client! I am a getting an exception of type: ValueError: The view theassistantcallerapp.views.callerview didn't return an HttpResponse object. It returned None instead. Now, callerview is the view inside views.py. It maps to the URL that will start the GET request to the OpenAi Assistants API. This implementation I am using is for streaming responses. Now, here is the view insides views.py and NOTICE HOW THE EVENTHANDLER CLASS IS USED #inside views.py # this is callerview(request, paramm): thread = … -
Issue with Quantity Increment in Django E-commerce Cart
Description: I'm encountering an unexpected behavior in my Django e-commerce website where the quantity of items in the cart increments at an exponential rate instead of a linear one. Here's a breakdown of the problem and the relevant code snippets: Problem Description: When adding an item to the cart, the quantity appears to double with each click of the "add" button. For instance, if I add an item once, it shows a quantity of 3 instead of 1. Then, upon adding it again, the quantity jumps to 6 instead of 2, and so forth. Similarly, when decreasing the quantity using the "remove" button, it doesn't decrement linearly but exhibits similar exponential behavior. Code Snippets: cart.html: This snippet shows the HTML code responsible for displaying the quantity and buttons to add or remove items from the cart. <div class="li-cartstyle cartbodyinformation-quantity"> <p class="quantity-input">{{ item.quantity }}</p> <div class="cartquantity-buttons"> <i data-product={{ item.product.id }} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i> <i data-product={{ item.product.id }} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i> </div> cart.js: This JavaScript code handles the interactions with the cart, such as adding or removing items. // var user = '{{request.user}}' var updateBtns = document.getElementsByClassName('update-cart') var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser'; for(var i=0; i … -
Can't install Pipenv on Windows
i'm building the backend of an app in python and i wanted to use Django, the problem is, i installed pipenv with pip3 the first time and it run smoothly, now if i try to install with pip only it tells me: Requirement already satisfied: pipenv in c:\users\marco\appdata\roaming\python\python39\site-packages (2023.12.1) Requirement already satisfied: virtualenv>=20.24.2 in c:\python39\lib\site-packages (from pipenv) (20.25.1) Requirement already satisfied: certifi in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (2024.2.2) Requirement already satisfied: setuptools>=67 in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (69.2.0) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (4.2.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.8) Requirement already satisfied: filelock<4,>=3.12.2 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.3) WARNING: You are using pip version 21.2.3; however, version 24.0 is available. You should consider upgrading via the 'C:\Python39\python.exe -m pip install --upgrade pip' command. but if i try to run pipenv --version powershell tells me: pipenv : Termine 'pipenv' non riconosciuto come nome di cmdlet, funzione, programma eseguibile o file script. Controllare l'ortografia del nome o verificare che il percorso sia incluso e corretto, quindi riprovare. In riga:1 car:1 + pipenv + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException (wich by the way is the "not recognized as the name of … -
use dict from python in django html template and also in js
I am having a dict statistics in my view.py and give it as param in my context to my index.html. There I want to use it in my html like {{ statistics.key1 }}. But I also want to use it in js. When using json.dumps like this in my view.py: "statistics": json.dumps(statistics, cls=DjangoJSONEncoder), I can use it like this in my js: var statistics = JSON.parse('{{ statistics | escapejs }}'); But then I can't use it as a dict anymore in my html. Makes sense, as it is now a JSON-String. But when I just pass it like a dict, I can use it in my html. but var statistics = '{{ statistics | escapejs }}' gives me a JSON with single quotes so I can't just parse it. How can I do both? Still use the dict as normal in my HTML and also parse it to use it in js? -
'pyodbc.Cursor' object has no attribute 'callproc', mssql with django
I cannot execute a procedure stored on mssql server from django. Here is the configuration for the db DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'OPTION':{ 'driver': 'ODBC Driver 17 for SQL Server', 'trusted_connection': 'yes' } } } In my view: def test(request): if request.method == "POST": with connection.cursor() as cursor: P1 = request.data["p1"] P2 = request.data["p2"] try: cursor.callproc('[dbo].[SP_TEXT]',[P1,P2]) if cursor.return_value == 1: result_set = cursor.fetchall() print(result_set) finally: cursor.close() return Response({"msg":"post"}) else: return Response({"msg": "get"}) I use sql server standard 2022 Need help please -
Django Bootstrapv5 carousel multiple item problem
I want my carousel items to contain a maximum of 5 card tags. However, when I add more cards and it exceeds five, it doesn't create another carousel item, but simply overflows into the same carousel. How i can fix this problem. This is my code: <div class="carousel-box"> <div id="carousel-1" class="carousel slide" data-bs-interval="false" data-bs-wrap="false"> <div class="carousel-inner"> {% for knowledge in knowledges %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <div class="row"> {% for photo in photo01s %} {% if photo.category01 == knowledge %} <div class="card" style="background-image: url('{{ photo.image01.url }}');"></div> {% endif %} {% endfor %} </div> </div> {% endfor %} </div> </div> I have written it like this, but it's not effective. <div class="carousel-box"> <div id="carouselExample" class="carousel slide" data-bs-interval="false" data-bs-wrap="false"> <div class="carousel-inner"> {% for knowledge in knowledges %} {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <div class="row"> {% with photo_count=0 %} {% for photo in photo01s %} {% if photo.category01 == knowledge %} {% if photo_count < 5 %} <div class="card" style="background-image: url('{{ photo.image01.url }}');"> </div> {% endif %} {% increment photo_count %} {% endif %} {% endfor %} {% endwith %} </div> </div> {% endfor %} </div> </div>