Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template render annotated data along with Model data in UI for Many to Many relationship objects
I am looking for a solution to show a Models data elements along with this annotated data, e.g. I have a TestRun model which has M2M relationship with TestCases, so on the UI page for testruns list page want to show TsetRun data along with the count of testcases grouped by its status. e.g. TestRun.ID = 1, TestRun.Name = Regression Total TCs in TR = 4 Passed TC = 2 | Blocked TC = 1 | Failed TC = 1 along with a table for each run record to show the above 4 testcases like TC_ID|TC_NAME|TC_STATUS| 1 |TC_101 | Passed | 4 |TC_102 | Passed | 5 |TC_105 | Failed | 7 |TC_107 | Blocked | I have following models class TestRun(models.Model): testcases = models.ManyToManyField(TestCase, through="TestRunCases") project = models.ForeignKey(Project, related_name="project_testruns", on_delete=models.PROTECT) name = models.CharField(max_length=255) class TestRunCases(models.Model): testcases = models.ForeignKey(TestCase, on_delete=models.CASCADE) testrun = models.ForeignKey(TestRun, on_delete=models.CASCADE) testcase_status = models.ForeignKey(TestCaseStatus, null=True, default=1, on_delete=models.PROTECT) I want to show the count of test cases for each run with status, e.g. For TestRun.id=1, Total TC#=3,Passed=2, Failed=1, template eg. provided below I tried using following in my views, using CBV def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["testcases"] = ( TestRunCases.objects.filter(testrun_id__in=testrun_qs) .values("testrun_id", "testcase_status__status_value") .annotate(status_count=Count("id")) ) return context And … -
Delete an instance before saving a new one (Django model save method)
I want to limit my model's records to a maximum of 10 rows per user (the model has a foreign key to user model). What is the best practice for that? I thought about overriding save method, perform a check, and delete before saving: def save(self, *args, **kwargs): if MyModel.objects.filter(user=self.user).count() >= 10: oldest_record = MyModel.objects.filter(user=self.user).order_by('created_at').first() oldest_record.delete() super().save(*args, **kwargs) But I wonder if it is a good solution, if it's better (and what's the way to do it) to enforce that at database level, and potential problems when same user saves two instances at the same time (though very unlikely). Any experiences with something similar? -
How to wait until the receive function is not invoked (set the client input in kc.input())?
I am trying to build a Python IDE using the Jupyter client kernel. My problem is: Not being able to provide the client input in the kc.input() that I receive after sending the prompt: : await self.send(text_data=json.dumps({'input_request':mseg["content"]["prompt"]})) need help here if msg["msg_type"] == "execute_input": mseg = kc.get_stdin_msg(timeout=1) await self.send(text_data=json.dumps({'input_request': mseg["content"]["prompt"]})) ***I want it to wait until it doesn't receive input (invoke the receive function)*** print("Stored input:", self.input_received) kc.input(5) I try to declare the kc = BlockingKernelClient() in the class so can use in if i received any input but kernel get stop till then. Full Code import json from channels.generic.websocket import AsyncWebsocketConsumer from jupyter_client import BlockingKernelClient from jupyter_client import KernelManager class CodeExecutionConsumer(AsyncWebsocketConsumer): input_received = '' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): await super().receive(text_data) data = json.loads(text_data) code = data.get('code', '') input_text = data.get('input','') if input_text: print("input text:",input_text) await self.handle_input(input_text) else: result = await self.execute_code(code) print(code,result) # await self.send(text_data=json.dumps({'result': result})) async def handle_input(self, input_text): print("Received input:", input_text) self.input_received = input_text async def execute_code(self, code): kc = BlockingKernelClient() kc.load_connection_file(connection_file="./confs/c1.json") kc.start_channels() try: msg_id = kc.execute(code) while True: msg = kc.get_iopub_msg(timeout=1) if msg["msg_type"] == "stream" and msg["content"]["name"] == "stdout": result … -
Improving Django Application Performance: Comparing Blocking and Non-blocking Implementations
I encountered an unexpected error (apr_socket_recv: Connection reset by peer (54)) while load testing my Django application with Apache Benchmark (ab). This error occurs when I increase the load to 50 concurrent requests. Surprisingly, even with 20 concurrent requests, there's no significant performance improvement with non-blocking (Can see same throughput as of blocking) The application consists of two implementations: one using a blocking approach with the default WSGI server and the other utilizing a non-blocking asynchronous approach with ASGI and the Daphne server. The blocking implementation relies on synchronous requests with the requests library, while the non-blocking approach utilizes aiohttp within an asynchronous view function. Both implementations aim to make POST requests to an external API endpoint and return responses. Despite expecting better performance with the asynchronous approach, the error persists and the performance remains stagnant. I'm seeking insights into the root cause of this error and potential solutions to improve performance under heavier loads. Additionally, any advice on optimizing the asynchronous implementation or suggestions for better load-testing strategies would be greatly appreciated I'm using ab as a benchmarking tool. The command which I used for benchmarking: ab -c 50 -n 600 -s 800007 -T application/json "http://127.0.0.1:8001/test" Blocking Code: from … -
Spinner and page reset after views.py completes processing | DJANGO
I have a Django web application where users can generate and download Excel files. To provide feedback to users while the file is being generated, I've implemented a spinner animation using HTML and JavaScript. However, I'm facing difficulty in stopping the spinner animation after the file download is complete. Here's my HTML and JavaScript code for the spinner: <style> .spinner-container { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; } .spinner { width: 50px; height: 50px; border: 5px solid rgba(0, 0, 0, 0.1); border-left-color: #333; border-radius: 50%; animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } </style> <button type="submit" onclick="showSpinner()">GENERATE</button> <div id="spinner" class="spinner-container"> <div class="spinner"></div> </div> <script> function showSpinner() { document.getElementById("spinner").style.display = "block"; } function hideSpinner() { document.getElementById("spinner").style.display = "none"; } </script> And here's my Django views.py code for downloading the file: from django.http import HttpResponse import pandas as pd def downloadFile(request): try: # Generate the Excel file with pd.ExcelWriter('NEW-DOWNLOAD.xlsx', engine='openpyxl') as excel_file_path: # Write dataframes to sheets dataframes = { 'SUMMARY': data, 'CHART': CHART } for sheet_name, df in dataframes.items(): df.to_excel(excel_file_path, sheet_name=sheet_name, index=True) # Read the entire file as bytes with open('NEW-DOWNLOAD.xlsx', 'rb') as f: file_data = f.read() … -
no_color in overridden django command does not work
I have overridden django check command in ~/<project_name>/commands/management/commands/check.py looking like this: from django.core.management.commands import check class Command(check.Command): help = 'My Customized Version of the Original check Command' def handle(self, *args, **options): print('>>> Running customized check') options['deploy'] = True options['no_color'] = True super(Command, self).handle(*args, **options) Running manage.py check 2>/tmp/check-output triggers the command, but the problem here is in spite of setting 'no_color', the output is still colored and I have to run it as manage.py check --no-color 2>/tmp/check-output -
Django (REST) backend server hosting using Google Cloud
This is my first time trying to host a backend server to any cloud platform and I am trying to host it using Google Cloud. This is a pet project of mine and the frontend of my webapp is alreday hosted by myself using firebase. My issue is I tried depolying the cloud app for my backend, but I am getting a 500 server error even though the files were uploaded without any issues. Another thing is I am quiet not sure about my file structure. [Backend File Strucutre](https://i.stack.imgur.com/PLAtJ.png) [API folder](https://i.stack.imgur.com/AGGKQ.png) [enchant_ease_backend File](https://i.stack.imgur.com/AQ4hH.png) [My backend folder](https://github.com/ThisalHerath/express-hello-world) I tried removing my requirements.txt file since in the Google cloud app engine dashboard I got few errors with my dependencies but id did not worked out and I spent almsot few hours watching tutorials but nothing worked out. Can someone guide me through the hosting process or tell me what i have done wrong or something that need to be changed? -
Django data is not being stored on Postgres Db
Up until January, my Django app was saving data to this DB but now it is not working. The migrations pass and declare ok on the CLI but it doesn't get saved in the DB. It still works with SQLite3 DB but I get this error { "error": "'NoneType' object has no attribute 'rsplit'" } I did not make any big change to the settings prior to this -
in Django i'm trying to rendering a list of objects from a different models in a class based detail view
I have two models Vendors and Products. Products has a foreign key of vendors. What I'm trying to do is when you go to a detail view of vendor it shows then vendor model information then a list of Products from that vendor. I currently just testing flow and getting to know django so a lot this code is very generic and i know i need to clean it up. Here is my models class Vendor(models.Model): name = models.CharField(max_length=126, unique=True, blank=True, null=True) contact_number = models.CharField(max_length=126, blank=True, null=True) address = models.CharField(max_length=126, blank=True, null=True) email = models.EmailField(max_length=126, blank=True, null=True) is_active = models.BooleanField(default=True) def __str__(self): return self.name def productFilepath(instance, filename): year = datetime.now().strftime("%Y/") return os.path.join(instance.vendors.name, year, filename) class Product(models.Model): vendors = models.ForeignKey(Vendor, on_delete=models.CASCADE) collection = models.CharField(max_length=126, unique=True, blank=True, null=True) product = models.CharField(max_length=126, blank=True, null=True) size = models.CharField(max_length=126, blank=True, null=True) vendor_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) retail_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=126, unique=True, blank=True, null=True) year = models.PositiveSmallIntegerField(blank=True, null=True) quarters_in_year = { 'q1': 'Q1', 'q2': 'Q2', 'q3': 'Q3', 'q4': 'Q4', } quarter = models.CharField(max_length=2, choices=quarters_in_year.items(), blank=True, null=True) image = models.FileField(upload_to=productFilepath, blank=True, null=True) here are my views class VendorDetailView(DetailView): model = Vendor template_name = 'deliveries/vendor_detail.html' class Productlist(ListView): model = Product template_name = … -
How to couple Django connection.cursor() with rest_framework generics?
Working on a project where we want to bypass Django ORM and use direct SQL queries instead. We will have lots of simple APIs, hence wanted to use rest_framework generics view classes. But querysets implemented via connection.cursor() don't update when data changes. I.e. if a POST is made to a generics.ListCreateAPIView, the new data gets saved to the DB, but consecutive GET requests still show the dataset as it was before the POST. MODELS: from django.db import models class identifier_type(models.Model): type_name = models.CharField(max_length=25, unique=True) SERIALIZERS: from rest_framework import serializers from .models import * class IdentifierTypeSerializer (serializers.ModelSerializer): class Meta: model = identifier_type fields = ['id', 'type_name'] VIEWS: from rest_framework import generics from .models import identifier_type from .serializers import IdentifierTypeSerializer from .queries import identifier_type_select_all from .utils import dict_fetch_all class IdentifierTypesCR(generics.ListCreateAPIView): queryset = dict_fetch_all(identifier_type_select_all) # does not update GET after PUT # queryset = identifier_type.objects.all() # alternative- Django ORM updates GET after PUT serializer_class = IdentifierTypeSerializer UTILS: from django.db import connection def dict_fetch_all(query, *args): cursor = connection.cursor() cursor.execute(query, *args) desc = cursor.description rows = cursor.fetchall() if rows: return [dict(zip([col[0] for col in desc], row)) for row in rows] else: return None QUERIES: identifier_type_select_all = "SELECT * FROM staticdata_identifier_type" URLS: from django.urls import path … -
Django how do I use system timezone?
For whatever reason, django is defaulting to use America/Chicago when TIME_ZONE is not specified. My server runs in local devices, so the system timezones is all over the place and could change if people move around. Is there a way to accomplish this? I just want os.environ["TZ"] to not be set, is this possible? Django on startup will set it to that variable to chicago -
Our website was deployed on heroku, and now we are developing our mobile app on flutter using the same heroku db, what should I do?
Our website was deployed on heroku, and now we are developing our mobile app on flutter using the same heroku db, what should I do? We want the website and the app to share the same database. Should I just add api endpoint to the original framework? I am just so confused -
How to change the value of a field when the user clicked the notification button
I am developing a notification system in Django where users receive notifications when someone comments on an article they posted in the app. However, I am encountering an issue where I cannot modify the value of a field in the notification model when a user clicks a notification button in the template. Let me provide an example: When I ask a question on Stack Overflow and someone comments on the question, I receive a notification stating that someone has commented on my question. When I click the URL in the template, the red badge disappears, indicating that the author of the question has already read the comment on that question. This is precisely the functionality I am aiming to achieve here. However, using the current method in my views.py file, the method returns an error stating: 'int' object has no attribute 'is_read'. def all_article(request): articles = Article.objects.all() notifications = Notification.objects.filter(user=request.user) unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count() if unread_notifications.is_read == False: unread_notifications.is_read == True unread_notifications.save() return render(request, 'article.html', {"articles":articles, "notifications":notifications, "unread_notifications":unread_notifications}) models.py: class Notification(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField() link = models.URLField(unique=True) is_read = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) template: <nav class="navbar navbar-light bg-light shadow-sm bg-body"> <div class="container"> … -
Can't render views of html in django
My models from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): USER_TYPE_CHOICES = ( ('user_type1', 'User Type 1'), ('user_type2', 'User Type 2'), ) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES) groups = models.ManyToManyField( 'auth.Group', related_name='customusers', # Override the default related name ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='customusers_permissions', # Specify a related name for custom user permissions ) My views.py: from django.shortcuts import render, redirect from .forms import CustomUserCreationForm # Assuming you have a CustomUserCreationForm def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() # Redirect to a success page or another page return redirect('success') # Replace 'success' with the URL name of your success page else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) My html trample: <meta charset="UTF-8"> <title>User Registration</title> <h1>Register</h1> {% if form.errors %} <p style="color: red;">There are errors in your form.</p> <ul> {% for field, errors in form.errors.items %} {% for error in errors %} <li>{{ field }}: {{ error }}</li> {% endfor %} {% endfor %} </ul> {% endif %} <form method="post"> {% csrf_token %} <label for="username">Username:</label> {{ form.username }}<br> <label for="email">Email:</label> {{ form.email }}<br> <label for="password">Password:</label> {{ form.password }}<br> <label for="user_type">User Type:</label> <select name="user_type" id="user_type"> {% for choice in form.user_type.field.choices %} <option value="{{ choice.0 … -
Deployment of nginx with django on port 80 and node.js in port 3001
I am using the following github repository https://github.com/sebaburella/Api-Whatsapp and i want to use the funcionality of this in a django proyect but I dont know nothing about node This github repository it supposedly works as an alternative of the oficial whatsapp api. My nginx configuration is the following froma this tutorial https://tonyteaches.tech/django-nginx-uwsgi-tutorial/ upstream django { server unix:///home/udoms/microdomains/microdomains.sock; } # configuration of the server server { listen 80; server_name micro.domains www.micro.domains; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/udoms/microdomains/media; } location /static { alias /home/udoms/microdomains/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/udoms/microdomains/uwsgi_params; } } -
meson-python: error: Could not find ninja version 1.8.2 or newer while installing pandas
I am deploying my Django app on shared hosting via name cheap. I am using cPanel shell terminal. I have some dependencies on requirements.txt file. I am installing it via terminal session but unable to install numpy or pandas it shows the following error. So the problem here is I already have installed the ninja version 1.11.1 and required is 1.8.2 or newer so basically it is not detecting the ninja. I also have downgraded the ninja version and tried different combinations but nothing works. Any help will be appriciated. ((app:3.11)) [abc@server123 simply]$ pip install pandas Collecting pandas Using cached pandas-2.2.1.tar.gz (4.4 MB) Installing build dependencies ... error error: subprocess-exited-with-error × pip subprocess to install build dependencies did not run successfully. │ exit code: 1 ╰─> [35 lines of output] Collecting meson-python==0.13.1 Using cached meson_python-0.13.1-py3-none-any.whl.metadata (4.1 kB) Collecting meson==1.2.1 Using cached meson-1.2.1-py3-none-any.whl.metadata (1.7 kB) Collecting wheel Using cached wheel-0.43.0-py3-none-any.whl.metadata (2.2 kB) Collecting Cython==3.0.5 Using cached Cython-3.0.5-py2.py3-none-any.whl.metadata (3.2 kB) Collecting numpy<=2.0.0.dev0,>1.22.4 Using cached numpy-1.26.4.tar.gz (15.8 MB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Installing backend dependencies: started Installing backend dependencies: finished with … -
Javascript does not redirect and time is stay same in Django Application. How to solve it?
Hi everyone I try to build web application with using django and js. It is kind of chat application there are rooms and each room have time after time is up. I want to delete room. While I making test, I realize if one user in room,other user in list page, room does not delete when 1 user in room and other list page. Time is stay 1 seconds How can ı solve this problem. Can you help me? Thank You. room_detail_page function updateRemainingTime() { // Sunucuya AJAX isteği gönder var xhr = new XMLHttpRequest(); xhr.open('GET', '/remaining-time/' + roomName + '/', true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var remainingTime = JSON.parse(xhr.responseText); // Kalan süreyi güncelle document.getElementById('remaining-time').textContent = remainingTime.minutes + ':' + remainingTime.seconds; if (remainingTime.minutes <= 0 && remainingTime.seconds <= 0) { deleteRoom(roomName); } } }; xhr.send(); } function deleteRoom(roomId) { var xhr = new XMLHttpRequest(); xhr.open('POST', '/delete-room/' + roomId + '/', true); xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { window.location.href = '/home'; location.reload() } }; xhr.send(); } setInterval(updateRemainingTime, 1000); room_list_page function updateRemainingTime(roomId) { // Sunucuya AJAX isteği gönder var xhr … -
why set password method doesn't working in django?
I implemented the user manager class but my set_password method only works for super users and I have problem with regular users log in this is my manager.py: from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, username, phone_number, password, **extra_fields): if not phone_number: raise ValueError('Phone number must be set!') user = self.model(username=username, phone_number=phone_number, **extra_fields) user.set_password(user.password) user.save(using=self._db) return user def create_superuser(self, username, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, phone_number, password, **extra_fields) this is my user model: from django.db import models # Create your models here. from django.core.validators import RegexValidator from django.db import models from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import AbstractUser from .manager import UserManager `class User(AbstractUser): GENDER_CHOICE = ( ('he', 'male'), ('she', 'female') ) HOBBIES = ( ('sport', '🏆'), ('music', '♫'), ('movie', '🎬'), ('sleeping', 'ᶻ 𝗓 𐰁'), ('photography', '📷') ) username = models.CharField(max_length=25, unique=True) phone_number = models.CharField(max_length=11, validators=[RegexValidator( regex=r"^09[0|1|2|3][0-9]{8}$" )]) biography = models.CharField(max_length=20, default=None, null=True, blank=True) hobbies = models.CharField(choices=HOBBIES,max_length=250,null=True,blank=True) gender = models.CharField(choices=GENDER_CHOICE, max_length=250, null=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['phone_number', 'password'] objects = UserManager()` I've tried set_password mthod in my manager file but it only works for super users and it doesn't hash regular users's password and i have problem with log in for regular users because … -
Django form not submiting to server
When I create a new user account I set the terminal to print working if the create account form works and the terminal does that but the created accounted doesn't show on django admin panel which means the account wasn't created and since the account wasn't created I don't get redirected to create profile page my views.py from django.shortcuts import redirect, render from django.contrib.auth.models import User, auth from django.http import HttpResponse from django.contrib import messages from .models import UserProfile from .forms import UserRegistrationForm, UserProfileForm from django.contrib.auth import login from django.http import JsonResponse from .models import Posts from .models import Videos # Create your views here. def home(request): post = Posts.objects.all() video = Videos.objects.all() return render(request,'Index.html',{'Home':'Title', 'Posts':post, 'Videos':video,}) def createAccount(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) profile_form = UserProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): username = user_form.cleaned_data['username'] email = user_form.cleaned_data['email'] password = user_form.cleaned_data['password'] password2 = user_form.cleaned_data['password2'] # Add this line if password != password2: # Check if passwords match user_form.add_error('password2', 'Passwords do not match') # Add error message elif User.objects.filter(username=username).exists(): user_form.add_error('username', 'This username is already taken.') elif User.objects.filter(email=email).exists(): user_form.add_error('email', 'This email is already registered.') else: user = user_form.save() profile = profile_form.save(commit=False) profile.user = user profile.save() login(request, user) messages.success(request, 'Your account … -
Problem in importing model files from same module
Below is the pic of my Django Project structure. Django Structure I am trying to import model in data_models folder but it saying no module found. I have attached the pic for reference. Please guide me. Error Image I have tried many thing like removing it from main directory but still not working fine. -
django admin. So that in "select" there is a selection from certain records using the appropriate additional key
help to make sure that in "specsAdmin" in the line "Characteristic:" only those options (after selecting the product) that have the same category id as the product are displayed problem here is such a code in model.py class specs(models.Model): """ Характеристика к товару """ tovar = models.ForeignKey(Tovars, on_delete=models.CASCADE) gl_category = models.CharField("Категория xарактеристики", max_length=50, null=True) category = models.ForeignKey("detail", verbose_name="Характеристика", on_delete=models.CASCADE) description = models.TextField("Значение") def clean(self, *args, **kwargs): if self.tovar == self.category: return super().clean(*args, **kwargs) raise ValidationError('товар и характеристика к товару должны совпадать') class Meta: verbose_name = "Характеристика к товару" verbose_name_plural = "Характеристики к товару" def __str__(self): return self.tovar def get_absolute_url(self): return reverse("specs_detail", kwargs={"pk": self.pk}) class detail(models.Model): """ Описание характеритики """ category = models.CharField("Характеристика", max_length=50) сategory_tovar = models.ForeignKey(Category, verbose_name="Категория", on_delete=models.CASCADE) details = models.TextField("Описание характерискики", null=True, blank=True) class Meta: verbose_name = "Описание характеритики" verbose_name_plural = "Описание характеритики" def __str__(self): return self.category def get_absolute_url(self): return reverse("detail_detail", kwargs={"pk": self.pk}) and such in admin.py @admin.register(specs) class specsAdmin(admin.ModelAdmin): """ Характеристика к товару """ list_display = ('tovar', 'gl_category', 'category', 'description') search_fields = ('tovar', 'name') @admin.register(detail) class detailAdmin(admin.ModelAdmin): """ Описание характеритики """ list_display = ('category', 'details', 'сategory_tovar') search_fields = ('category',) this is the detailAdmin detailAdmin detailAdmin this is the specsAdmin specsAdmin -
How do I pass Bing Web Search API Data from Django to display in React
I've got it where I can print the data from my search result in a Django folder called api.py using Python. But now, how do I move this data into react to display it? Could anyone help give me a detailed way to do this. Much Thanks in advance! I also have the Bing API key stored in a .env file currently in the same file level as the api.py file. Bing Web Search API: https://learn.microsoft.com/en-us/bing/search-apis/bing-web-search/reference/endpoints code: in api.py file `from pprint import pprint import requests from decouple import config subscription_key = config('subscription_key', default='') search_url = "https://api.bing.microsoft.com/v7.0/search" search_term = 'iphone 13' headers = {"Ocp-Apim-Subscription-Key": subscription_key} params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"} response = requests.get(search_url, headers=headers, params=params) response.raise_for_status() search_results = response.json() pages = search_results\['webPages'\] results = pages\['value'\] pprint(results\[0\])` This is the data I'm getting in the terminal: I've tried looking through stackoverflow and the whole internet, haven't found anyone really using this API.. -
how do i solve my problem for my coding bootcamp walkthrough project?
Hello i am a beginner when it comes to coding and i was wondering if anyone could help me with an issue im doing the django module 'i think therefore i blog' and i am pretty sure i followed the instructions exactly but it is not working how it is intended to. basically when i "enter python3 manage.py migrate" into the terminal i get this error ``` `Traceback (most recent call last): File "/workspaces/djangoblog/manage.py", line 22, in <module> main() File "/workspaces/djangoblog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/codeany/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/codeany/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/codeany/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/codeany/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/codeany/.local/lib/python3.9/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/home/codeany/.pyenv/versions/3.9.17/lib/python3.9/importlib/__init__.py", line 122, in import_module raise TypeError(msg.format(name)) TypeError: the 'package' argument is required to perform a relative import for '.herokuapp.com'` i was wondering what i did wrong and how to fix it. here is my repository "https://github.com/benbarker04/djangoblog" any help would be appreciated -
Apache2 Too Many Redirects in HTTPS Rewrite Virtual Host
I keep getting too many redirects on one of my virtual hosts, but not the other. I'm sure there is some very small error I made I just don'r recognize. I've attached both Apache2 site configs below. I've tried several different versions of the rewrite conditions, and nothing has changed. I restart apache each time. The rewrite rules that make the most sense to me are these, which due to OR precedence should be (www.stage OR stage) AND HTTPS=OFF by my calculations. It appears the HTTPS check never occurs though? And I'm entirely confused why a direct copy of the working config doesn't work for this new site. RewriteCond %{SERVER_NAME} =www.stage.example.com [OR] RewriteCond %{SERVER_NAME} =stage.example.com RewriteCond %{HTTPS} off RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] I have several sites running in microk8s pods on the server with Apache2 and the virtual hosts pass the traffic to the appropriate port. The main difference between the two sites is one is written in PHP (working) and the new one is in DJango. But I have another site that is a working site in Django, so I doubt that is the issue. # example.com.config # Staging branch, unstable wip # Config also includes 2 other virtual … -
How to render a dictionary passed as Django Form Class parameter
I've got a template that renders two predefined forms depending on two different POST requests handled by a single view method to keep just one URL end point for the whole interaction. Form one doesn't take any parameters but form two does take an external API response a one. How can render the dictionary contents of that response as choice fields in form two class? view.py from django.shortcuts import render, HttpResponse from django.template import loader from .forms import QuestionForm, QuestionLevelForm from urllib import urlopen def process_question(request): if 'level' in request.POST: url = 'http://opentdb.com/api.php?amount=1&category=9&type="multiple"&level=' url += request.POST["level"] try: response = urlopen(url) except URLError as e: if hasattr(e, 'reason'): HttpResponse('Reaching server failed: ', e.reason) elif hasattr(e, 'code'): HttpResponse('Couldn\'t fufill request', e.code) else: question = response["results"][0] # API response passed to Form class instance as parameter form = QuestionForm(question) return render(request, "log/question.html", {"question": question, "form": form}) elif 'answer' in request.POST: return HttpResponse('NOT IMPLEMENTED: Check answer') else: form = QuestionLevelForm(); return render(request, "log/question.html", {"form": form}) forms.py from django import forms from django.forms import widgets class QuestionLevelForm(forms.Form): choices = (('', '---Please choose a level---'), ('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard')) label = forms.CharField(label="Choose your question level") select = forms.CharField(widget=forms.Select(choices=choices)) class QuestionForm(forms.Form): # Gets question dictionary …