Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 {% … -
Django form class data in HTML Template
I am having a hard time getting my data from my form class into my html template. I have the following form class: class AnswerForm(forms.Form): def __init__(self, product, *args, **kwargs): super(AnswerForm, self).__init__(*args, **kwargs) self.fieldsets = {} for index, multiplier in enumerate(product.multiplier_list): rowLength = len(str(multiplier * product.multiplicand)) fieldsetFields = [] for i in range(5, 0, -1): field_name = f'field_{i}' self.fields[field_name] = forms.CharField( label=f'Answer {i}', widget=forms.TextInput(attrs={'class': 'answer-cell', 'tabindex': i, 'maxlength': 1}), required=i <= rowLength ) fieldsetFields.append(self.fields[field_name]) # Determine if row or result if index + 1 == len(product.multiplier_list): fieldsetId = f'fieldset-{product.type}result' else: fieldsetId = f'fieldset-{product.type}row' self.fieldsets[fieldsetId] = fieldsetFields And the form in my html template looks like this: <!DOCTYPE html> <html> <head> <title>Your Page Title</title> </head> <body> <form method="post"> {% csrf_token %} {% for fieldset_id, fields in form.fieldsets.items %} <fieldset id="{{ fieldset_id }}"> {% for field in fields %} <div class="form-group"> {{ field }} </div> {% endfor %} </fieldset> {% endfor %} <button type="submit">Submit</button> </form> </body> </html> I always receive the following output: django.forms.fields.CharField object at 0x0000013E23A3F730&g It worked before without the wrapped fieldset around it. -
DRF, Django Rest Framework. Render results as html
I need to have a page with simple html which shows not pure JSON but formatted data with meta information. I have this snipped of code. class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer router = SimpleRouter() router.register(r'product', ProductViewSet) urlpatterns = [ path('product/list/<int:pk>', ProductViewSet.as_view({'put': 'update'}), name='product-view'), path('product/', ProductViewSet.as_view({'get': 'list'}), name='product-view'), ] I have this as result. enter image description here -
pytelegrambotapi (telebot) how create pagination button i use django+telebot
enter image description here button.py from telebot import types def quarter_keyboard_uz(district_id): keyboard = types.InlineKeyboardMarkup() quarters = Quarter.objects.filter(district_id=district_id) for quarter in quarters: button = types.InlineKeyboardButton(quarter.name_uz, callback_data=f'quarter_{quarter.id}') keyboard.add(button) return keyboard bot.py import telebot elif current_state == "wait_district": user = BotUser.objects.get(chat_id=chat_id) district_id = call.data.split('_')[-1] district = District.objects.get(pk=district_id) user.district = district user.user_state = "wait_quarter" user.save() district.save() if current_language == 'UZ': bot.send_message(chat_id, "itimos o'z mfyigizni tanlang", reply_markup=quarter_keyboard_uz(district_id)) elif current_language == 'RU': bot.send_message(chat_id, "выберите общественное собрание вашего района", reply_markup=quarter_keyboard_ru(district_id)) elif current_state == "wait_quarter": user = BotUser.objects.get(chat_id=chat_id) quarter_id = call.data.split('_')[1] quarter = Quarter.objects.get(pk=quarter_id) user.quarter = quarter user.user_state = "wait_adress" user.save() quarter.save() if current_language == 'UZ': bot.send_message(chat_id, "itimos o'z adresingizni kiriting") elif current_language == 'RU': bot.send_message(chat_id, "Пожалуйста, введите ваш адрес") -
Django transaction and racing condition
I have the following Django code: with transaction.atomic(): items = Item.objects.all() for item in items: item.count += 1 Item.objects.bulk_update(items, ['count']) Does this code still contains the racing condition, despite the transaction? My understanding is that transaction doesn't lock the rows for read, so several threads running the same code might read the same count value so as a result it might not be incremented proper number of times? -
CSV File Downloaded as true.txt When Programmatically Triggered in JavaScript
I'm encountering a peculiar issue with downloading .csv files programmatically in a web application. When I click on a presigned URL (pointing to an AWS S3 object) directly from the console log or navigate to it manually, the .csv file downloads correctly with the proper filename and extension. However, when I try to trigger the download programmatically using JavaScript, the file gets downloaded as true.txt instead. Here's the frontend code snippet: const DownloadData = async () => { const token = localStorage.getItem("token"); const backendUrl_fetchdata = `http://127.0.0.1:8000/fetch-data/`; try { const response = await axios.post( backendUrl_fetchdata, { // request payload }, { headers: { Authorization: `Token ${token}`, }, withCredentials: true } ); if (response.status === 200 && response.data.urls) { response.data.urls.forEach(({ url, filename: expectedFilename }) => { console.log("Downloading file from URL:", url); if (expectedFilename.endsWith('.csv')) { // Attempt to download CSV const link = document.createElement("a"); link.href = url; link.setAttribute("download", expectedFilename); document.body.appendChild(link); link.click(); document.body.removeChild(link); } }); } } catch (error) { console.error("Error fetching URLs:", error); } }; Backend (Django): The backend generates presigned URLs for the files stored in AWS S3. These URLs are sent to the frontend as part of the response. Observations: The console.log accurately prints the URL, and clicking it initiates the … -
How to prevent OpenTelemtry traces from being printed to console?
I setup otel traces in my django app, by overriding Gunicorn's post_fork: import os from opentelemetry import trace from opentelemetry.exporter.otlp.proto.http.trace_exporter import \ OTLPSpanExporter from opentelemetry.instrumentation.django import DjangoInstrumentor from opentelemetry.instrumentation.logging import LoggingInstrumentor from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor def post_fork(server, worker): """Configue OpenTelemetry traces.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'solutions.settings') resource = Resource.create(attributes={ "service.name": "solutions" }) trace.set_tracer_provider(TracerProvider(resource=resource)) span_processor = BatchSpanProcessor( OTLPSpanExporter(endpoint="http://grafana-agent-traces.prometheus:4318/v1/traces") ) trace.get_tracer_provider().add_span_processor(span_processor) DjangoInstrumentor().instrument() LoggingInstrumentor().instrument(set_logging_format=True) Traces are successfully exported but are also printed to console. How to avoid that? I have tried to add this, but it has no effect: logging.getLogger("opentelemetry").setLevel(logging.WARNING) -
after changing a user password then the session got flushed
when i changed user password the user becomes anonymous means the session get flushed after.How to solve this issue. Why this happens when the password changed. the url has given below path('psswdReset/',psswdReset, name = 'psswd_reset') def psswdReset(request): if request.method == 'POST': new_psswd = request.POST.get('new_psswd') psswd = request.POST.get('psswd') password_is_correct = check_password(psswd, request.user.password) if password_is_correct: user = CustomUser.objects.get(id=request.user.id) user.password = make_password(new_psswd) user.save() messages.success(request, 'Password changed successfully!') return render(request,'User/userPsswdReset.html',{}) print('anonymouse', request.user.is_anonymous) return render(request,'User/userPsswdReset.html',{}) -
request.user always returns Anonymous user, even though request.META gives proper token when decoded in JWT it gives user_id
settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', "allauth.account.auth_backends.AuthenticationBackend", ] views.py def google_login_view(request): if not request.user.email: return HttpResponse("An email is required to login.", status=400) email_from_google = request.user.email try: user = User.objects.get(email=email_from_google, is_active=True) user_details = UserDetails.objects.get(email=email_from_google, is_active=True) except (User.DoesNotExist, UserDetails.DoesNotExist): return HttpResponse("User not found. Please register.", status=404) # generate_token_pair is defined in tokens.py access_token, refresh_token, access_token_exp, refresh_token_exp = generate_token_pair(user) current_time = datetime.now() access_token_expiration_timestamp = access_token_exp.timestamp() access_token_expiration_datetime = datetime.fromtimestamp(access_token_expiration_timestamp) # Check if the access token has expired if access_token_expiration_datetime < current_time: # Check if the refresh token is still valid if refresh_token_exp >= current_time: with transaction.atomic(): new_access_token, _, new_access_token_exp, _ = generate_token_pair(user) user.access_token = new_access_token user.save() # Log the user back in with the new access token login(request, user, backend='allauth.socialaccount.providers.google.backends.GoogleOAuth2') redirect_url = f"{settings.FRONTEND_REDIRECT_URL}?access_token={new_access_token}" return redirect(redirect_url) else: logout(request) # Ensure the user is logged out return redirect(settings.LOGIN_URL) else: login(request, user, backend='allauth.socialaccount.providers.google.backends.GoogleOAuth2') redirect_url = f"{settings.FRONTEND_REDIRECT_URL}?access_token={access_token}" return redirect(redirect_url) @authentication_classes([JSONWebTokenAuthentication]) @api_view(['POST']) def send_client_feedback_email(request, project_id): try: pass I have above setup Now when I Add PDB set trace in google login view I get a request.user of current logged in user. Now when I try to use my POST METHOD and when I add request.user It returns Anonymous … -
Plotting a bargraph in django using matplotlib
so here is my code. The bargraph is not showing in the dashboard page. This is my views.py code. expenses = Expense.objects.filter(user=user) incomes = Income.objects.filter(user=user) expense_date_list=[] amount_list=[] for expense in expenses: expense_date=expense.date.strftime("%Y-%m-%d") amount=expense.amount expense_date_list.append(expense_date) amount_list.append(amount) data=plt.bar(expense_date_list, amount_list) fig=plt.gcf() buf=io.BytesIO() fig.savefig(buf, format='png') buf.seek(0) data=urllib.parse.quote(base64.b64decode(buf.read())) context = { 'expenses': expenses, 'incomes': incomes, 'user':user, 'data':data`} return render(request, 'dashboard.html', context) -
Django:TemplateDoesNotExist at /accounts/login/
accounts/models.py from django.db import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms # Create your models here. class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True,label='email',error_messages={'exists':'This already exists'}) firstname = forms.CharField(required=True,label='firstname') lastname = forms.CharField(required=True,label='lastname') class Meta: model = User fields = ('firstname','lastname','username','email','password1','password2') def __init__(self, *args, **kwargs): super(UserCreateForm, self).__init__(*args, **kwargs) self.fields['firstname'].widget.attrs['placeholder'] = 'First Name' self.fields['lastname'].widget.attrs['placeholder'] = 'Last Name' self.fields['username'].widget.attrs['placeholder'] = 'Username' self.fields['email'].widget.attrs['placeholder'] = 'Email' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Confirm Password' def save(self, commit=True): user = super(UserCreateForm,self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(self.fields['email'].error_messages['exists']) return self.cleaned_data['email'] accounts/views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, auth from accounts.models import UserCreateForm from django.http import JsonResponse import random from django.core.mail import send_mail from django.conf import settings def registerpage(request): if request.method == 'POST': #login form = UserCreateForm(request.POST) if form.is_valid(): new_user = form.save() new_user = authenticate( username = form.cleaned_data['username'], password = form.cleaned_data['password1'], ) login(request, new_user) return redirect('home') else: #registration form = UserCreateForm() context = {'form':form} return render(request, 'store/auth/register.html', context) accounts/urls.py from django.urls import path,include from . import views urlpatterns = [ path('register', views.registerpage, name='register'), path('', … -
Need Help {{ Can't install mysql client }}
I'm just beginner for codeing and i try to connect Django with Mysql. But When i pip install myslqclient it error code below : ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\envdjango\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-ktopnk4j\\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-ktopnk4j\\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Admin\AppData\Local\Temp\pip-wheel-e994nvxe' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-ktopnk4j\mysqlclient_9607a86bf5aa4a55ac82c8bd2f6752ec\ Complete output (23 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\admin\envs\envdjango\scripts\python.exe' -u -c 'import io, … -
List Data from Multiple Models in Single HTML Table
I am trying to render data from 3 models in single html table. I have tried an error few times but failed. Below is my code. The workstation, printer and laptop have foreign of site ID. I want to list all the workstation, laptop and printer filter by a site. Below is my code: Models: class Site(models.Model): site_name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Site Name") site_address = models.CharField(max_length=30, blank=True, null=True, verbose_name="Site Address") def __str__(self): return self.site_name class Workstation(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Workstation Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") workstation_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Workstation Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name class Laptop(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Laptop Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") laptop_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Laptop Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name class Printer(models.Model): name = models.CharField(max_length=30, blank=True, null=True, verbose_name="Printer Name") serial = models.CharField(max_length=30, blank=True, null=True, verbose_name="Serial") printer_model = models.CharField(max_length=30, blank=True, null=True, verbose_name="Printer Model") sitename = models.ForeignKey(Site, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Site") def __str__(self): return self.name URL: urlpatterns = [ path('', views.SiteView.as_view(), name='site'), path('report/<sitename>', views.ReportView.as_view(), name='reportview'), ] Template 1: Site List <table> <tr> <th>Site</th> <th>Address</th> </tr> {% for site in site_list %} … -
Django join two or three models class into get request
models.py class CMDBInstanceProduct(models.Model): name = models.CharField(primary_key=True, max_length=50) def __str__(self): return self.name class CMDBStatus(models.Model): name = models.CharField(primary_key=True, max_length=50) def __str__(self): return self.name class Instance(models.Model): cmdbid = models.CharField(primary_key=True, max_length=15]) name = models.CharField(max_length=100) product = models.ForeignKey(CMDBInstanceProduct, on_delete=models.CASCADE) status = models.ForeignKey(CMDBStatus, on_delete=models.CASCADE) def __str__(self): return self.cmdbid class Instance_account(models.Model): fk_instance = models.ForeignKey(Instance, on_delete=models.CASCADE) name = models.CharField(max_length=200) views.py @api_view(('GET',)) def accountlist(request): accountlists = Instance_account.objects.all().prefetch_related('fk_instance') dict = {} records=[] for account_list in accountlists: list = {"name":account_list.name,"ci_name": account_list.fk_instance.ci_name ,"product": account_list.fk_instance.product} print (list) records.append(list) dict["pickup"]=records return JsonResponse(dict) my print(list) {'name': 'accountnameinstance', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} {'name': 'accountname', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} {'name': 'shareacc', 'ci_name': 'MKZSQLT99_PROD1', 'product': <CMDBInstanceProduct: MS-SQL Instance>} i get an error TypeError: Object of type CMDBInstanceProduct is not JSON serializable Anyone could help on this to solve JSON serializable? -
Django - is there a way to shuffle and run only a subset of tests?
We are using Django with tests. We have in total about 6,000 tests which take about 40 minutes to run. Is there a way to shuffle the tests and run only 200 (randomly chosen) tests? This should be done with a command line parameter with the number 200 (which may change), since usually we run all the tests.