Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send response json from celery to my view Django
I want to use request_cache from 3rd party API and im looking for way to synch that every 5 minutes and if API is not responding or it got errors i want to use last json which i got from requests_cache I actually want to use celery for mb synch my request every 5 minutes and update that request but is this right way to do that? Or i just need to use expire_after in my view and i dont need to use celery Any solutions how can i do that? views.py def get_queryset(self): url = config('REPORT_PROJECT_BUDGET') session = requests_cache.CachedSession('project_budget_cache') response = session.get(url, auth=UNICA_AUTH) session.settings.expire_after = 300 # Im not sure if its right decision -
I can't see the buttons because of the image sizes in Django
I am trying to develop an application to display some food items in Django. Images overlay buttons when I try upload some of them. I tried solutions but couldn't fix the problem. I will be happy if you help me. Have a nice day. {% extends 'foodApp/base.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% block body %} {% for item in item_list %} <div class="row m-5"> <div class="col-md-3 offset-md-2"> <img class="card" height="auto" src="{{ item.item_image }}"/> </div> <div class="col-md-2"> <a href="{% url 'foodApp:detail' item.id %}" class="btn btn-success">Details</a> </div> </div> <div class="row"> <div class="offset-md-2 col-md-8"> <hr> </div> </div> {% endfor %} {% endblock %} this is the old code <ul> <li> <a href=""> {{ item.id }} -- {{ item.item_name }}</a> </li> </ul> </body> </html> It is my index source code. enter image description here -
"Request failed with status code 500" when I try opening my products page
This is my first time using redux and django. I click the link to one of my products that takes me to the products page, but I get a 500 error instead. My django server is running in the back and I know it's working because I get an error response in my terminal. I suspect my issue might be my views.py but I'm not sure since I'm not very familiar with django yet. ProductPage.js import React, { useState, useEffect } from "react"; import { Link, useParams } from "react-router-dom"; import { Row, Col, Image, ListGroup, Card, Button } from "react-bootstrap"; import Rating from "../components/Rating"; import Loading from "../components/Loading"; import ErrorMessage from "../components/Error"; import { useDispatch, useSelector } from "react-redux"; import { listProductsDetails } from "../actions/productActions"; function ProductPage() { const { id } = useParams(); const dispatch = useDispatch(); const productDetails = useSelector((state) => state.productDetails); const { loading, error, product } = productDetails; useEffect(() => { dispatch(listProductsDetails(id)); }, [id]); return ( <div> <Link to="/" className="btn btn-light my-3"> Go Back </Link> {loading ? ( <Loading /> ) : error ? ( <ErrorMessage variant="danger">{error}</ErrorMessage> ) : ( <Row> <Col md={6}> <Image src={product.image} alt={product.name} fluid /> </Col> <Col md={3}> <ListGroup variant="flush"> <ListGroup.Item> <h3>{product.name}</h3> … -
Need to set up an event listener in django
I need to listen to an external API from another application.Both applications have same number of users.so change in any app will need to be update on another app. SO planning to setup an event listener to communicate b/w applications. Appreciate any help to setup this in DJango. -
I need to make VoIP calls with python django
I have Auto Dialer web page's frontend now I need to make the backend, that should send VoIP calls to given files phone numbers and when answered play given audio file. I have no idea how to do that:( please can someone help -
Is it possible to create a admin page using curd operation in django?
I want to create a page where i can create update read delete (CURD) a user data like email password username role (Admin/normal user) etc., and all this update will automatically authenticate automatically. Basically i want to create a custom admin system. I have tried the curd operation from the tutorials but im unable to understand how do the connection between my table and djano user auth table. -
Overriding method python class of a pip module to update its behavior globally
Using OOP I want to do something like from django.contrib import admin class NavigateFormAdmin(admin.ModelAdmin): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): context['next_record_id'] = custom_function_to_calculate(context['obj'].id) res = super().render_change_form(request, context, add, change, form_url) return res And expect that whenever render_change_form of admin.ModelAdmin is called, it should first my overridden method (above) which then should call the original (parent) method. but it makes no difference, because my overridden method never gets called rather on any call to render_change_form the method from original class admin.ModelAdmin is called. Using undesired monkey patching I am able to achieve what I need by adding following code to any of my py file that is read by interpreter at the start of my project/service execution from django.contrib import admin from django.template.response import TemplateResponse # and also all the other imports used in original medthod class NavigateFormAdmin(admin.ModelAdmin): def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): opts = self.model._meta app_label = opts.app_label preserved_filters = self.get_preserved_filters(request) # and all the code of existing function has to be repeated here context['next_record_id'] = custom_function_to_calculate(context['obj'].id) res = TemplateResponse(request, form_template, context) return res admin.ModelAdmin.render_change_form = NavigateFormAdmin.render_change_form Now on every call to admin.ModelAdmin.render_change_form off-course NavigateFormAdmin.render_change_form is executed But I need to use super() like (the … -
ERROR: Could not find a version that satisfies the requirement tappythonsdk from versions: noneERROR: No matching distribution found for tappythonsdk
can someone with more experience help me? ERROR: Could not find a version that satisfies the requirement noon-payment-gateway (from versions: none) ERROR: No matching distribution found for noon-payment-gateway im tried to use this command pip install tap-python-sdk This Package for Tap payment getaway for saudi arabia "SAR" Package for payment to build saudi arabia payment getaway with django -
Django - runserver command doesnt do anything
I activate the venv and when I try to run the python manage.py runserver command on VScode powershell it doesnt do anything, no errors, nothing, I enter the localhost to see if the server was activated with no notice but it doesnt appear. Note that the project was first made by a friend that uses Linux and I imported the project using Github on Windows, im thinking that there may be problems because of that? I tried running it on cmd and i couldnt run the activate command this time, apparently I need to use power shell to run linux like commands? Sorry Im a student and im not very knowledgeable on Linux. -
how to Django Admin Customization with self made design
Instead of using default Django Admin panel, I create My Own Admin Dashboard With HTML and CSS and other , So I want to apply default Django Admin panel Features like add, update, delete, filters, user Creation features to my Customize Admin Dashboard. Django default Admin dashboard Customize with my own design. -
Is there any auxiliary tool or quick way to upgrade django 3.0.5 to django 4.x?
My django is built from 3.0.5, and now the system is very large. If I want to upgrade to Django 4.x, I will encounter many problems. Are there many people who have encountered such troubles like me, so I wonder if anyone has a solution? -
Not receiving POST request
can someone help me? I am trying to when button is clicked and user clicks on proceed, send a POST request to the server in which it would switch user status from active to archive and vice versa. However, I am not receiving post request even though I have updated the form method to post and button to submit. I cannot find the root cause of the problem. Help is much appreciated! Thanks! Do let me know if there are any other codes that I should provide! HTML & Javascript: // Get the buttons var archiveBtn = document.getElementById("archive-btn"); var unarchiveBtn = document.getElementById("unarchive-btn"); var deleteBtn = document.getElementById("delete-btn"); // Get the modal forms var archiveForm = document.getElementById("archive-form"); var unarchiveForm = document.getElementById("unarchive-form"); var deleteForm = document.getElementById("delete-form"); // Add event listeners to the buttons archiveBtn.addEventListener("click", function() { archiveForm.submit(); }); unarchiveBtn.addEventListener("click", function() { unarchiveForm.submit(); }); deleteBtn.addEventListener("click", function() { deleteForm.submit(); }); <div id="archive-modal" class="modal fade " tabindex="-1" role="dialog" aria-modal="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-body p-4"> <div class="text-center"> <i class="dripicons-warning h1 text-warning"></i> <h4 class="mt-2">Are You Sure?</h4> <p class="mt-3">Archive User</p> <button type="button" class="btn btn-danger my-2" data-bs-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-primary my-2" data-bs-dismiss="modal">Proceed</button> <form method="post" action="{% url 'app:users' %}" id="archive-form" style="display:none;"> {% csrf_token %} <input type="hidden" name="user_id" … -
What is the best way to increment these likes and checks model attributes in a callback function using an if-elif-else statement?
I dont want to create two callback functions. I want this callback to execute in a conditional way using an if-elif-else statement. Firstly, will the code work well as it is? So if not, what is the best way to put the house.likes and house.checks in an if-else or if-elif-else statement? def callback(ch, method, properties, body): print('Received in config') id = json.loads(body) print(id) house = House.objects.get(id=id) house.likes = house.likes + 1 house.save() print('House likes increased!') house.checks = house.checks + 1 house.save() print('House checks increased!') I am yet to try refactoring it...still studying the code block. I don't want to break things. -
Strange errors using factory_boy and DjangoModelFactory
I've created several factories including a user factory that looks like so class UserFactory(factory.django.DjangoModelFactory): class Meta: model = models.User django_get_or_create = ('phonenumber',) uuid = factory.Faker('uuid4') email = factory.Faker('email') phonenumber = factory.Sequence(generate_phone_number) I'm using the django unit test TestCase model like so class ApiV1TestCase(TestCase): def setUp(self): self.user = UserFactory.create() and getting the following error: *** django.db.utils.IntegrityError: duplicate key value violates unique constraint "accounts_user_pkey" DETAIL: Key (id)=(1) already exists. when I run it several times I get a continual error with what looks like a correctly autoincremented ID field, ie. Key (id)=(2) already exists. ... Key (id)=(3) already exists. on each subsequent create() call. If I check the test database, I see that User.objects.all() is empty in all of these cases. Alternatively I'm able to successfully run UserFactory.build() u.save() however this isn't great for obvious reasons (ie. I want to override an auto_now datetime field in some tests) I've also noticed some strange behavior, if I check transaction.get_connection().in_atomic_block from django.db.transaction I get True which seems to indicate somehow that I'm in an atomic block? I'm not sure if this is normal behavior. -
How to unit testing for json file is loaded in django views.py
I want to unit testing for json file is opened in views.py in django def get_json_data(): json_data = json.load(open(JSON_DIRECTORY+'my.json')) return json_data Please help me how to unit testing for json file is loaded or not def test_read_file_data(self): def read_file_data(filename, path): os.chdir(path) with open(filename, encoding="utf8") as data_file: json_data = json.load(data_file) return json_data sample_json = { } sample_json = json.dumps(sample_json, ensure_ascii=False) path = my file path filename = real file self.assertEqual(read_file_data(filename, path), sample_json) In json there is null as well so I do not know how to deal with the null -
Ajax filters displays all data but does not filter. DJANGO AJAX
i'm using ajax filtering to filter my products by color, brand, size. The data filtering successfully but it shows everything. I'm hoping for your help and thank you for your attention Trying to filter products... product-filter.js:20 {data: '\n\n \n <div class="col-md-4 mb-0">\n … </div>\n </div>\n </div>\n \n'}data: "\n\n \n <div class=\"col-md-4 mb-0\">\n[[Prototype]]: Object product-filter.js:21 Data filtered successfully ajax $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ let filter_object = {}; $(".filter-checkbox").each(function(index,ele){ let filter_value = $(this). val(); let filter_key=$(this). data('filter'); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(element){ return element.value; }); }); $.ajax({ url:'/filter_products', data:filter_object, dataType:'json', beforeSend:function(){ console.log('Trying to filter products...'); }, success:function(response){ console.log(response); console.log('Data filtered successfully'); $("filteredProducts").html(response.data) } }); }); }); views.py def filter_products(request): color = request.GET.getlist('color[]') brand = request.GET.getlist('brand[]') size = request.GET.getlist('size[]') products = Product.objects.all().order_by('-id').distinct() if len(color)>0: products=products.filter(color__id__in=color).distinct() if len(brand)>0: products=products.filter(brand__id__in=brand).distinct() if len(size)>0: products=products.filter(size__id__in=size).distinct() t = render_to_string('ajax/product-list.html',{'products':products}) return JsonResponse({'data':t}) def search(request): data1 = wishData(request) wishItems = data1['wishItems'] data = cartData(request) q = request.GET['q'] cartItems = data['cartItems'] products = Product.objects.filter(name__icontains=q).order_by('id') context = {'products': products, 'cartItems': cartItems,'wishItems': wishItems} return render(request, 'store/store.html', context) def product_view(request, id): product = Product.objects.filter(id=id).first() data = cartData(request) cartItems = data['cartItems'] data1 = wishData(request) wishItems = data1['wishItems'] context = {'product':product, 'cartItems':cartItems, 'wishItems':wishItems} return render(request, 'store/product_view.html', context) def store(request): data1 = wishData(request) wishItems = data1['wishItems'] data = cartData(request) cartItems = data['cartItems'] … -
Why does my dependent dropdown form act up?
I am attempting to implement a dependent dropdown form for my project. I want the makes dropdown to be dependent of the year of the vehicle. The models dropdown entries should be dependent on the year and make dropdown entries selected. Finally, the repairs dropdown should be dependent on the year, make, and model selected. However, this is not the case. In my django database, I have two entries titled "Chevrolet" that are connected to years 1980 and 1981 via ForeignKey. Both of these entries are connected to an entry titled "Camaro". Another entry I have stored in my backend database has 1981 as the year, "Ford" as the make (connected to 1981 via ForeignKey), and "LTD Crown Victoria" and "F-150" as models. While the year and makes appear as they should, the other entries do not. I can only get the appropriate models to appear in the dropdown box after I select 1981 as the year and "Ford" as the model. Afterwards, I am able to see the models connected with the 1981 entry for "Chevrolet". Code from my Home.html file {% load static %} <!doctype html> <html lang="en"> <link rel="stylesheet" href="{% static 'css/edits.css' %}"> <head> <meta charset="UTF-8"> <meta … -
Completing and order using choice fields
I am trying to make it so when an order processed and payment is made, the payment status is changed to complete. At the moment my orders stay on pending consistently. What should be happening is that the order is completed the page is redirect to home page, cart is emptied and payment status changes to 'Complete' Models: class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] customer = models.ForeignKey( Customer, on_delete=models.PROTECT, null=True, blank=True) order_id = models.IntegerField(null=True) order_date = models.DateTimeField(auto_now_add=True) payment_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING ) def __str__(self): return str(self.id) @property def get_cart_items(self): order_items = self.orderitem_set.all() total = sum([item.quantity for item in order_items]) return total @property def get_cart_total(self): order_items = self.orderitem_set.all() total = sum([item.get_total for item in order_items]) return total views: if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, payment_status='P') #TODO: add float field? total = data['form']['total'] order.order_id = order_id if total == order.get_cart_total: order.payment_status = 'C' order.save() JS var total = '{{order.get_cart_total}}' var form = document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form Submitted..') document.getElementById('form-button').classList.add('hidden'); document.getElementById('payment-info').classList.remove('hidden'); }) document.getElementById('make-payment').addEventListener('click', function(e){ submitFormData() }) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'first_name':null, 'last_name':null, 'email':null, 'total':total, } var url = … -
django channels work fine locally but fail on server
I have a simple chat application using django and django-channels. I was follow django-channels tutorial. It work fine locally but in production it failed. this is my js code for websocket initial: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); this is error that raise when im goint to chat page: Mixed Content: The page at 'https://site-url.ir/chat/room/1/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://site-url.ir/ws/chat/room_1/'. This request has been blocked; this endpoint must be available over WSS. room.js:18 Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. I dont know what can i do for fix this bug. -
Django - combining querysets from different models and serializing them
I am a newbie trying to build an e-commerce website for fun. Firstly, I take the query parameters from the url, then find the fitting products and then try to find the corresponding images. However I cannot find a way to: combine a queryset of products and a queryset of images (connected with each other by a foreign key) serialize them into a JSON, to show on the frontend I am using postgresql. Sample url http://localhost:3000/products/?slider=%5B500%2C8000%5D&service=1&stars=%5B3%2C4%2C5%5D models.py class Hotel(models.Model): name = models.CharField(max_length=200, unique=True) location = models.CharField(max_length=200) price_per_person = models.FloatField() service = models.PositiveSmallIntegerField() stars = models.PositiveSmallIntegerField() description = models.TextField() class Image(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='images', null=True) views.py @api_view(["GET"]) def getProductsView(req): productsSet = Hotel.objects.all() for key, value in req.GET.items(): value = json.loads(value) if key == "stars": orStatement = Q(stars=value[0]) for star in value[1:]: orStatement = orStatement | Q(stars=star) productsSet = productsSet.filter(orStatement) elif key == "slider": productsSet = productsSet.filter(price_per_person__range=(value[0], value[1])) else: productsSet = productsSet.filter(**{key: value}) productsSet = productsSet[:25] imageSet = Image.objects.filter( hotel_id__in=[i for i in productsSet.values_list("id", flat="True")] ) # Tried # productsSet.union(imageSet) # but the result didn't change serializer = HotelSerializer( productsSet, context={"request": req}, many=True ) return Response(serializer.data) I tried calling django's union, but to no avail and I … -
Django reverse accessor clash - multiple uses of a model
I have two models, Photo and Story. The Story model uses the Photo a couple different ways - for a thumbnail, a header photo, and a gallery. I am storing an optional Story reference in the Photo model. This was causing a E.304 error: (fields.E304) Reverse accessor for 'stories.Story.header_image' clashes with reverse accessor for 'stories.Story.thumbnail'. I added related_name='+' to both the thumbnail and header_image fields. This disallows the backward relation and got rid of my reverse accessor clash issue. I was able to set up a PhotoInline in the Django admin, but also realized that there is now no way for a user to add a thumbnail or header_image inline - the typical "edit" and "add" options aren't available. What do I need to change about my models or admin config to allow for that? I tried changing the related_name params to name the relationships instead of disallowing them, but that didn't seem to help - not sure if I would need to use those values somewhere. class Story(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) thumbnail = models.ForeignKey('Photo', on_delete=models.CASCADE, null=True, blank=True, related_name='+') header_image = models.ForeignKey('Photo', on_delete=models.CASCADE, null=True, blank=True, related_name='+') content = tinymce_models.HTMLField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = … -
Validate Model wasn't added to m2m field in another Model yet
I have 2 models: class UserInventory(models.Model): user = models.OneToOneField(verbose_name='user', to='users.User', on_delete=models.CASCADE) # items promocodes = models.ManyToManyField(verbose_name="promos", to="inventory.PromocodeItem", blank=True) class PromocodeItem(models.Model): name = models.CharField(verbose_name='code name', max_length=128) code = models.CharField(verbose_name='code', max_length=512, db_index=True) is_used = models.BooleanField(verbose_name='used?', default=False) My API can add codes to the user_inventory model. I want to create a manual admin APIView to give codes to users. In this view, I also want to check if this code already exists in anyone's inventory. I have this code: def post(self, request, code_id, user_id): code = PromocodeItem.objects.filter(id=code_id).first() user = User.objects.filter(id=user_id).first() inv = UserInventory.objects.get_or_create(user=user) // Here I need to validate that the code model has not been added to anyone`s user inventory yet. inv.promocodes.add(code) return Response("ok") Which is the best way to do this? -
unable to represent IMG in CSS and HTML
enter image description here I want to do coffee Store, when you look at Background.png in file section It's red, I have no idea why, but this is a problem. -
Uploading a .YAML file using Django and reading it's contents to display a graph/plot on the webpage
I want to be able to upload .yaml files using the Django Admin interface and then access the content of that file to do preprocessing and outputting a graph using plotnine on the webpage. Example code of preprocessing and plotting a graph: import yaml import pandas as pd import numpy as np import plotnine as p9 slurm_data = {} with open('slurm-22.05.5-02_27_2023-16_33_29.yaml', 'r') as f: all_slurm_data = yaml.load_all(f, yaml.FullLoader) for d in all_slurm_data: for k,v in d.items(): slurm_data[k] = v time_window = 60 data_frames = [] for slurm_partition_name, slurm_partition_data in slurm_data.items(): data_frames.append(pd.DataFrame.from_dict(slurm_partition_data)) data_frames[-1]['node_type'] = slurm_partition_name data_frames[-1]['days_scheduled'] = np.random.randint(0,time_window, size=len(data_frames[-1])) data_frames[-1]['days_free'] = time_window - data_frames[-1]['days_scheduled'] data_frames[-1]['projected_utilization'] = data_frames[-1]['days_scheduled'] / float(time_window) slurm_data_frame = pd.concat(data_frames) slurm_data_frame.hist(bins=30) -
configure Django settings for static files with Heroku
I am trying to deploy my Django website using Heroku. So far the site has deployed successfully but the only problem is collecting the static files. I am stuck with how I am supposed to configure my settings.py file so that the website knows where to find these static files. folder structure -website ---App ------Static ---------App ---Website ---staticfiles ---manage.py ---Procfile ---requirements.txt ---runtime.txt settings.py DEBUG = False BASE_DIR = Path(__file__).resolve().parent.parent MIDDLEWARE = [ ... "whitenoise.middleware.WhiteNoiseMiddleware", ... ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "App/static") ] django_heroku.settings(locals()) STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" error msg whitenoise.storage.MissingFileError: The file 'App/static/app/styling-images/search_button.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0000016932C5D190>. The CSS file 'App\styles.css' references a file which could not be found: App/static/app/styling-images/search_button.png Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location.