Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Related model relationship
I have a model class customer(models.Model): ... related_customer = models.ManyToManyField(customer) ... So I want to define many to many fields relationship which should show all related customers for one particular customer, How can this be done? For example, "customer1" is related to "customer7", "customer9", and so on. -
I am looking for a way to connect to my database from my laptop, this database is on CPANEL, and i am making a Django Project
Basically what I want to achieve is that, I have a Django project. and I want to store the db of the project on my Server(CPanel). and access it from the Laptop. I tried searching about Remote MySql on Django but couldnt find anything, I am not using Google Cloud or PythonAnywhere, or heroku, is there a way? Please. Thanks. -
Create custom Values method in django
I want to create method semi to Values method in Django QuerySet. The values method problems are: Miss order of fields in querySet if I make myquery = MyModel.objects.values('field1','field2','field3') when i print querSet it give me [{'field2':'data','field1':'data','field3':'data'},...]. so this miss order will cause a problem at Union of queryset if the field is choices at model then values(...) will give me the key of dictionary instead of its value I want to create my custom values method using django Manager class MyModelManager(models.Manager): def values(self, *fields): # what the things that must I do to make my custom values class MyModel(models.model): # An example model objects = MyModelManager() -
Associating Users with their sessions
I have a website where a user is able to vote for polls anonymously or when they're logged in. Here's the model I'm working with: class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) session = models.ForeignKey(Session, on_delete=models.CASCADE, null=True) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) If the user is anonymous, the user field will be set to NULL and their session will be created. If the user decides to sign up, what they voted for should be retained. Instead, their votes are deleted since the session is no longer used by Django. I'd like to associate their votes to the logged in user. How can I do that? -
How to access formset filed Django
I'm using inlineformset_factory. I need to check product in self.data and grab product value inside __init__ method. Unable grab formset filed value, please help. class PurchaseOrderDetailsForm(forms.ModelForm): class Meta: model = PurchaseOrder_detail fields = ('product', 'product_attr', 'order_qnty', 'recvd_qnty', 'amount_usd', 'amount_bdt', 'unit_price', 'sales_price', 'commission_price') widgets = { 'product': Select2Widget, 'product_attr': Select2Widget, } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if 'product' in self.data: product_id = int(self.data.get('product')) self.fields['product_attr'].queryset = ProductAttributes.objects.filter(product_id=product_id) -
Should I use one model with 800+ fields or two models with with a generic data field?
Apologies for reposting, I tried to edit to be a non-opinionated question. This is more of a database design question. I have a Django application that manages consumer data, so, there is 800+ data points on a given consumer. I am not sure what the best way to translate this into a Django model is? The current option I have implemented is: class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) income=models.CharField(max_length=100, unique=True) owns_vehicle=models.BooleanField() # 800+ more fields This way works well, as it is easy to filter using Django Filters and there are few table joins so it is performant. However, I am wondering if there would be a better, more performant, or more maintainable way to accomplish this? Maybe using a JSONField and ForeignKey relationships? class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) class DataPoint(models.Model): consumer = models.ForeignKey(Consumer, on_delete=models.CASCADE) column_name = models.CharField(max_length=100, unique=True) value = models.JSONField() However, this is an API, that is reliant on filtering through URL calls, and this method would create more work in building custom filters since the dataset should be able to be filtered by each data point. Are there any resources for dealing with tables of this size in … -
maximum recursion depth exceeded when using Django redirects
I'm experiencing this error where when I try to redirect a user to a webpage using Django, it showed me this error maximum recursion depth exceeded views.py from django.shortcuts import render, redirect from django.http import HttpResponse def redirect(request): response = redirect("https://google.com") return response app's urls.py urlpatterns = [ path('', views.redirect, name="donate-home"), ] Project's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('donate/', include("support.urls")) ] Did I do something wrong? Did I not add something in settings.py? I'm new to Django -
Getting images URL from Amazon S3 is extremely slow on Heroku
I have a Django app deployed on Heroku, where users submit images via Amazon S3. Though, when serving the image using {{ image.url }} in my Django template, the server seems to request a signed URL from S3 for every single image, and this takes a few seconds for each image, making the site painfully slow (17 seconds to load 9 small images). I can see the request for each image in the logs: Sending http request: <AWSPreparedRequest stream_output=True, method=GET, url=https://x.s3.ap-southeast-1.amazonaws.com/x.jpg, ...> Is there a way of serving the images without waiting for a response from S3? How can I optimize this? Here is my S3 config in settings.py: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = "x" AWS_S3_FILE_OVERWRITE = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Django getting superuser to use in a model class
I want to get all users information to set up user profiles including superuser, but somehow my code doesn't get superuser data . Please have a look from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
how to send django query data on django admin site index.html
I want to show Django model data on the Django admin site index.html. ############# index.html ############# {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }} {% endblock %} {% block coltype %}colMS{% endblock %} {% block bodyclass %}{{ block.super }} dashboard{% endblock %} {% block breadcrumbs %}{% endblock %} {% block nav-sidebar %}{% endblock %} {% block content %} <div id="content-main"> {% include "admin/app_list.html" %} </div> {% endblock %} {% block sidebar %} {% endblock %} -
DJango authenticate function returning wrong?
Using https://docs.djangoproject.com/en/3.2/topics/auth/default/#how-to-log-a-user-in, I've tried to authenticate users on my website. However, the authenticate method always returns a None type. I am not sure why because the user does exist in my system and I am typing the password correctly. In my system, I have it so that the username is the email so that it matches with the login authentication. Here is the code where I check for validation: if request.method == 'POST': if form.is_valid(): email=request.POST['email'] password=request.POST['password'] user2 = User.objects.get(username=email) print(user2.first_name) print(user2.username) user = authenticate(username=email, password=password) if user is not None: login(user) return HttpResponseRedirect(reverse('index')) else: form.clean() else: print("form is invalid") In my case, the form is valid and user2 DOES exist in the database as I have checked it's email and username and they are all the same. Why is this happening? -
How to display query data in a chart? - Django
I am trying to display the query data in the char but I get this error: TypeError at /estadisticas list indices must be integers or slices, not str Request Method: GET Request URL: http://127.0.0.1:8000/estadisticas Django Version: 2.2 Exception Type: TypeError Exception Value: list indices must be integers or slices, not str def productos_mas_vendidos(self): data = [] ano = datetime.now().year mes = datetime.now().month try: for p in Producto.objects.all(): total = Detalle_Venta.objects.filter( … id_venta__fecha_venta__year=ano, id_venta_fecha__venta__month=mes, id_producto=p.id_producto).aggregate( resultado=Coalesce(Sum('subtotal'), 0)).get('restultado') data.append({ 'name': p.nombre, 'y': float(total) }) ▼ Local vars Variable Value ano 2021 data [] mes 1 p <Producto: Cuaderno> self <store_project_app.views.EstadisticasView object at 0x000001B731FCC700> -
Django- VSCode - css loaded from static files "sticks" and does not respond to editing
Well this one is a head scratcher for me. I create a class in my style.css static file: .not-visible { display:none; margin-top: 10px !important } I then apply this class to a button and the button disappears <div id = "btn-box" class = "not-visible"> <button type = "submit" class = "ui primary `button">save</button>` </div> I then edit my static css file to remove the display:none attribute to see if the button is visible again. .not-visible { margin-top: 10px !important } After performing this operation, saving the css file, reloading the server, and restarting my web browser, the button is still no visible even though I deleted that property. When I delete the not-visible class in the button div, the button becomes visible gain. if I repeat this exercise, except I code the css directly into the html file, to button disappears and reappears as expected when I add and then delete the display:none property. So my question is, howcome saved changes to static css files do not apply to my html file? -
Write contents of ace.js editor to file in Django
I am playing around with the idea of editing my Django templates from the server. I know this is a far shot from that but I wrote this bit of code: def editor(request): handle=open(os.path.join(settings.BASE_DIR, 'app/code/test.html'), 'r+') var=handle.read() context = { "message": "editor", "code": var } return render(request, 'app/editor.html', context) That reads a file and passes it's contents to the template where ace.js displays it in the editor. <div id="editor-container"> <div id="editor">{{code}}</div> </div> It displays just fine and I can edit the text, but if I wanted to save my edits, writing them to the file, the button would need to go to a save route because I'm not using ajax, but how would I pass the new version of the document to the view to be written to the file? -
TypeError: manager_method() argument after ** must be a mapping, not str
Sorry, I am new to django rest framework and am having some trouble. I am using a nested serializer that I would like to add a create() method for. In trying to do so: I have created the following serializers.py: class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = ( "id", "name", ) class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = ( "id", "name", ) class CSerializer(serializers.ModelSerializer): class Meta: model = C fields = ( "id", "name", ) class NSerializer(serializers.ModelSerializer): a = ASerializer() b = BSerializer() c = CSerializer() class Meta: model = N fields = ( "id", "a", "b", "c", "description", ) def create(self, validated_data): a_data= validated_data.pop("A") b_data= validated_data.pop("B") c_data= validated_data.pop("C") n = N.objects.create(**validated_data) for one in a.data: A.objects.create(n=n, **one) for two in b.data: B.objects.create(n=n, **two) for three in c.data: C.objects.create(n=n, **three) return n I want to be able to perform a POST on the data in the following format: { "id": 1, "a": { "id": 1, "name": "apple" }, "b": { "id": 5, "name": "red" }, "c": { "id": 2, "name": "medium" }, "description": "a description." } My models are appropriately linked via foreign keys and I can perform all requests just fine without the create() in … -
Difficult Django: Is it really impossible to redirect to a url without using test_func() if don't meet a certain criteria? (urgent)
I want to make it such that if the user has blocked me or if I have blocked the user, I want to redirect them back to the homepage and not allow them to view the detail page. Because this is a class based view, do you have any ways for me to achieve what I want and not affecting what already exists? I tried to do all sorts of things but didn't work, and none of my friends could solve this. I cannot directly use return redirect(HomeFeed:main) because I have other contexts in the same view which I need it to return in the template. I also do not want to use UserMixin's test_funct() which involves showing a 403 Forbidden Error because it isn’t user friendly and doesn’t show the user what exactly is happening. That’s why I want to do a redirect followed by django messages to inform them why they can’t view the page class DetailBlogPostView(BlogPostMixin,DetailView): template_name = 'HomeFeed/detail_blog.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog_post=self.get_object() blog_post.save() context['blog_post'] = blog_post account = Account.objects.all() context['account'] = account if blog_post.interest_set.exists(): context["interest_pk"]=blog_post.interest_set.first().pk if blog_post.author in self.request.user.blocked_users.all(): messages.warning(self.request, 'You cannot view post of ideas authors that you have blocked.', extra_tags='blockedposts') hi … -
How to fix problems converting string to datetime with Python / Django?
I have the following two imports: from datetime import datetime, timedelta import datetime as dt If I try date = dt.datetime.strptime(data['Time'][i],"%Y-%m-%d").date() I get the following error: AttributeError: 'datetime.date' object has no attribute 'endswith' If I try date = dt.strptime(data['Time'][i],"%Y-%m-%d").date() I get the following error: AttributeError: module 'datetime' has no attribute 'strptime' I am using Python 3.8.3 with Django 3 - why is it behaving like this and how can I fix this? -
How to have one mandatory and two optional positional arguments?
I need to run a python file as follows python runnning_program.py argument1 [argument2] [argument3] def main(argument1,argument2 = default2, argument3 = default2): code if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument("argument1") kwargs = vars(ap.parse_args()) main(**kwargs) How to add argument2 and argument3 as optional positional arguments? -
Prevent Django model field from being rendered
I'm adding a per-user secret key to one of my Django models for internal usage, but I want to make sure that it is not accidentally exposed to the user. Obviously, I can check all the forms using that model today and ensure that they exclude the field, but that is not future proof. Is there any way I can mark a field so it is never rendered or sent to the client even if a form otherwise includes it? -
Send image to server through js fetch
I am changing my form submission to make it more fluid via using fetch. In order to process the value of my input image: <input name="perfil" type='file' id="imageUpload /> And then, in order to upload it to Amazon S3, I do this in my views.py: if request.method == "POST" image = request.FILES['perfil'] im = Image.open(image) output = BytesIO() rgb_im = im.convert('RGB') rgb_im.save(output, format='JPEG', quality=90) output.seek(0) s3.Bucket('bucketname').upload_fileobj(output, request.user.email + '.profileImage') But now (because i'm trying to implement fetch), I am getting the image file like this: fetch(`url`, { method: 'POST', body: JSON.stringify({ image: document.querySelector('#imageUpload').files[0], }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) } The problem is that when I do request.body['image`] in the server (views.py), all I'm getting is this: "image":{} And I don't know how to process this file in JS before I send it to the server (that will end up uploading it to amazon s3) -
Django raising a TemplateDoesNotExist at /web/edit/
The HTTP is giving me the ModuleNotFoundError whichever link I go. The ModuleNotFoundError is giving me the following information: ModuleNotFoundError at /url/ No module named 'django.core.context_processors' Request Method: GET Request URL: http://127.0.0.1:8000/web/ Django Version: 3.1.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'django.core.context_processors' Exception Location: <frozen importlib._bootstrap>, line 984, in _find_and_load_unlocked Python Executable: /Users/william/Documents/coding/WDTP/wfw_fixed/env/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/william/Documents/coding/WDTP/wfw_fixed/wfw', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/william/Documents/coding/WDTP/wfw_fixed/env/lib/python3.9/site-packages'] Server time: Sat, 23 Jan 2021 00:07:14 +0000 -
Derived field upon model creation - Django models
I have those 3 Django models. class Order(models.Model): materials = models.ManyToManyField(Material, through='OrderMaterial') class Material(models.Model): description = models.CharField(max_length=150) unit_price = models.FloatField() class OrderMaterial(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) material = models.ForeignKey(Material, on_delete=models.CASCADE) legacy_unit_price = models.FloatField() amount = models.IntegerField() total_price = models.FloatField() I need to calculate the total for the OrderMaterial object is literally material.unit_price * amount the problem is that the unit_price can't change in the OrderMaterial if the price in Material changes. So I created a legacy_unit_price that will hold the old price of the material no matter what. How can I store the material.price inside legacy_unit_price only when CREATING the object? -
TypeError at /cart/ cannot unpack non-iterable Cart object
I am developing an eCommerce app in Django. I am still developing locally. As I try to access to http://127.0.0.1:8000/cart/ I get the error: TypeError at /cart/ cannot unpack non-iterable Cart object in cart_home cart_obj, new_obj = Cart.objects.new_or_get(request) TypeError: cannot unpack non-iterable Cart object variable value request <WSGIRequest: GET '/cart/'> and I can't understand what is wrong. Here is my models.py: from django.db import models from django.conf import settings from products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1 : new_obj = False print('Cart ID exists') cart_obj=qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id']=cart_obj.id else: print('Cart ID does not exists') return cart_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) timestamp = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) Here is my views.py: from .models import Cart def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) products = cart_obj.products.all() total = 0 for x in products: total += … -
How to build a Voice based Email Web System for Blind
I want to build a Voice based Email Web System for Blind in Django but I face a problem. When I call a text to speech function for voice commands and open localhost Website loads after tts execution. I want that text to speech only works when website fully loaded. Also I want to know how to put data in Django form Fields by using voice (speech to Text) Please as soon as possible I need to know about how things done. Thanks -
Django - redis TLS encryption not working
actually I wanted to implement TLS encryption to connect my django application with redis but im failing with the following error (using without TLS work like a charm): app | raise ConnectionError("Error while reading from socket: %s" % app | redis.exceptions.ConnectionError: Error while reading from socket: (104, 'Connection reset by peer') my settingy.py: CACHES = { 'default': { 'BACKEND': 'django_prometheus.cache.backends.redis.RedisCache', 'LOCATION': [ 'rediss://' + ':' + env.str('REDIS_PWD') + '@' + env.str('REDIS_HOST') + ':' + env.str('REDIS_PORT') + '/' + env.str('REDIS_CACHE_DB') ], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'SOCKET_CONNECT_TIMEOUT': 30, # seconds 'SOCKET_TIMEOUT': 30, # seconds 'COMPRESSOR': 'django_redis.compressors.zlib.ZlibCompressor', 'CONNECTION_POOL_KWARGS': {'max_connections': env.int('REDIS_MAX_CONN'), 'retry_on_timeout': True, 'ssl_ca_certs': '/etc/ssl/CAcert.pem' }, 'REDIS_CLIENT_KWARGS': {'skip_full_coverage_check': True, 'ssl': True, 'ssl_cert_reqs': None } } } } This is how I start redis using docker: redis: image: redis:alpine command: > --requirepass ${REDIS_PWD} --protected-mode no --logfile "/var/log/redis-server.log" --loglevel "verbose" --tls-ca-cert-file /etc/ssl/CAcert.pem --tls-key-file /etc/ssl/redis.key --tls-cert-file /etc/ssl/redis.crt --tls-dh-params-file /etc/ssl/dhparams.pem --port 0 --tls-port 6379 --tls-auth-clients yes --tls-protocols "TLSv1.2 TLSv1.3" container_name: ${REDIS_HOST} hostname: ${REDIS_HOST} networks: - backend ports: - ${REDIS_PORT} labels: - traefik.enable=false volumes: - ./hard_secrets/ssl/redis:/etc/ssl - ./runtimedata/log/redis:/var/log The redis log is showing the following: 1:C 22 Jan 2021 23:15:23.486 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo 1:C 22 Jan 2021 23:15:23.486 # Redis version=6.0.9, bits=64, commit=00000000, modified=0, pid=1, just …