Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'list' object has no attribute 'startswith' - Django views
from django.shortcuts import render Create your views here. def twitter(request): return render(request, 'index.html') def page2(request): cars = ['A', 'B', 'C', 'D'] context = {'cars': cars, 'result': 99} return render(request, 'page2.html', context) AttributeError: 'list' object has no attribute 'startswith' I don't get the startswith attr for list contained in my app -
How to create and change ownership of a directory from within a Docker container
I have a Django app with an api endpoint for creating a directory for a user. When receiving the request, the app runs subprocess.check_output to create a directory for the user in an NFS mount and then run chown so that only that user has the proper permissions to add files to the directory. Now, I'm trying to migrate the app to run inside a Docker container but need to retain this functionality. What is the best way to do this? I've thought of having a volume to the NFS mount in the host machine but I'm not sure if that works, specially since the user wouldn't exist inside the Docker container and hence chown would fail. Something else I thought was having a shell script which can be called from the Docker container and run in the host machine but I don't know if that's possible -
How can I create django application with VueJS like Inertia in Laravel?
I want to create a simple application with django, but I want use vuejs like Inertia in laravel. ¿What is the correct way to implement it? I don't want separate front and back. I need a great idea to implement it or examples. -
error on django application in heroku when debug is set to False
Please I wanted to test my django application on heroku with the team before buying the host, but I get server error(500) when I set debug=False and try to access the login page or signup page, I have gone through the code but not finding any issue, but when I set the debug=True, the login and signup pages open fine. Also, when I upload an image, it displays for a while, when I revisit the page, the image will disappear, please help. this is my setting.py """ Django settings for EtufuorFarm project. Generated by 'django-admin startproject' using Django 4.1.6. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ import datetime import os from pathlib import Path import dj_database_url import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', 'django-insecure-qut(+bhgj@au6z4tl!_z8c(k%yes@)f(8x4lb%l6knh7n$d') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['etufuormarket.herokuapp.com'] # Application definition INSTALLED_APPS = [ #'admin_material.apps.AdminMaterialDashboardConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Tinymce doesn't generate pre-signed urls for uploaded images
I am developing a Django blog application where I utilize Tinymce as the text editor for the content of the posts. To store the uploaded images, I use AWS S3. The problem is that Tinymce does not generate pre-signed URLs for the uploaded images, leading to access denied errors when the expiration time is reached. This is the error I get: AccessDenied Request has expired 3600 2023-06-07T03:26:09Z 2023-06-07T15:46:49Z xxxxxxxxx xxxxxxxxx When an image is uploaded through Tinymce, it is stored as a link in the text area. However, Tinymce does not generate new pre-signed URLs for the images when a post is opened, resulting in the images retaining the same URL that was initially generated during the post's save operation. Since the pre-signed URLs for the Tinymce images do not change, when the expiration time set for the URLs is reached, the images become inaccessible, and I encounter an "access denied" error. I have other images in the blog that are served fine. The problem is just happening with those uploaded in Tinymce These are some relevant code snippets: uploadfile.js const image_upload_handler_callback = (blobInfo, success, failure, progress) => { const xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.open('POST', '/' + … -
Design pattern for Yelp-like app using microservices
I'm a newbie in microservices so forgive me if my question sounds a little naive. I'm designing a Yelp-like app for gyms. in this application, users can create a gym and its related data, and others can review or rate it. My question is how to design its services in microservice architecture? Is it a good design pattern to create these three services? Auth service that has a user table and manage user related data for login and registeration. Gym service for gym CRUD operation such as posting a gym, updating it, and so on. User service for relating gyms to their owners through event-driven architecture and message broker like Kafka. it also manage user profile data, such as resetting the password or changing the username, email, first name and last name. If this approach is reasonable, I want to know how does the relationship between user and auth service works. do I need to keep all the user data in the auth service and fetch or update it through published events, or should I duplicate the user data in a new user table in the user service database? -
Filter nested Django objects in serializer
In an application I am working on I would like to filter the objects returned by a serializer based on the user's is_staff status. If a user has is_staff = True I would like for all of the nested Book objects to be returned. If the user's is_staff status is False I would like for only Books with active = True. How can I achieve this using this viewset: class BookCategoryViewSet(viewsets.ReadOnlyModelViewSet): """ View available books by category """ queryset = BookCategory.objects.all() serializer_class = BookCategorySerializer and these serializers: class BookSerializer(serializers.ModelSerializer): """ Serialize Book for list endpoint """ class Meta: model = Book fields = ( 'id', 'name', 'description', 'category', 'category_name', 'thumbnail', 'active', ) class BookCategorySerializer(serializers.ModelSerializer): """ Serialize books by category """ books = BookSerializer(many=True, read_only=True, source='book_set') class Meta: model = BookCategory fields = ( 'name', 'active', 'books', ) NOTE: I am trying to filter the Books not the BookCategories based on the user status. -
Unable to connect to redis from celery
I'm using the django application where i want to run celery workers. But when i hit python -m celery -A cartpe worker, i get the following error consumer: Cannot connect to redis://redis:6379/0: Error 8 connecting to redis:6379. nodename nor servname provided, or not known.. This is my celery.py file import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cartpe.settings') app = Celery('cartpe') # Load the celery configuration from Django settings. app.config_from_object('django.conf:settings', namespace='CELERY') # Discover asynchronous tasks in Django app modules. app.autodiscover_tasks() __init__.py from .celery import app as celery_app __all__ = ('celery_app',) settings.py # Celery settings CELERY_BROKER_URL = 'redis://redis:6379/0' # initially had 'redis://localhost:6379/0' which didn't work either CELERY_RESULT_BACKEND = 'redis://redis:6379/0' I have redis running in docker. Is this the reason i'm unable to connect to redis ? Also i'm using MacOs. I saw a number of solutions related to this but none worked. What can i do here to resolve the issue ? -
Is it possible to return a Django.model instance with htmx?
I'm using django with django-htmx. I want to use hx-vals to return an instance that was given by the context to the django template. {% for auszubildender in auszubildende %} <div hx-post="/htmxFunctions/azubiAnzeigen" hx-trigger="click" hx-target="#content" hx-vals='{ "test": "test", "auszubildender": "{{auszubildender}}"}'> {% if auszubildender.first_name %} [...] {% endif %} </div> {% endfor %} When I'm accesing auszubildender with request.POST.get("auszubildender") it returns a str (the username as auszubildender is a django default Usermodel). Is there a way to post / get the instance or will a POST method always return just a string? In this case I will just use the PK to access the instance. -
Authentication for grafana behind a reverse niginx proxy
I am running a react app with a django backend. Users can log in to my app via django and are redirected to my react app. Now I want to show a grafana panel. I already set up a self-hosted grafana instance with a reverse proxy (for https). I can embedd the panel without a problem (iframe) when I use grafanas anonymous_authentication. But this is not an option for me. Also not an option for me is a login page on in app/iframe. I am reading alot that there is the option to manage the authentication via the reverse proxy. But since I am a nginx noob, I don't really know how I can implement this. Can someone guide me here? I think I have to somehow log in via the proxy to grafana My nginx setup thus far: server { server_name myserver.co; location / { proxy_set_header Host $http_host; proxy_pass http://localhost:3000/; } ##here is also some cert stuff } server { if ($host = myserver.co) { return 301 https://$host$request_uri; } listen 80; listen [::]:80; server_name myserver.co; return 404; } -
I'm getting "This field is required" from my Django Form when using Client().post to test even thought form.data shows values in those fields
I'm trying to test some form logic in my views.py and need to simply pass a form to that view in order to do that but I can't figure out why it isn't receiving a valid form when passed using a Client().post from my tests. When using the form from the browser normally it works fine. I'm using Django test Client submitting a form with a POST request and How should I write tests for Forms in Django? as guidance with no luck after looking at many different resources. The errors from form.errors shows name - This field is required address - This field is required However my form.data shows <QueryDict: {"'name': 'foo bar', 'address': '2344 foo st'}": ['']}> The working live form has the form.data as: <QueryDict: {'csrfmiddlewaretoken': ['htR...Rel', 'htR...Rel'], 'name': ['test'], 'address': ['test'],'submit': ['Submit_Form']}> I've played around with getting a "csrfmiddlewaretoken" but I don't feel like that the problem. I've also tried setting the .initial and played around with content type. Is the form.data not what is looked at? form.is_valid() is True before the post to the view.py. Thanks in advance for the help! My tests code is: @pytest.mark.django_db def test_add_bar_with_logged_in_user_form(setUpUser, django_user_model): from ..models.forms import BarForm from django.test … -
Django join through table even if don't match
I'm starting to use Django, but I'm just a beginner. I have a problem with Django Queries, and although I've done a lot of research online, I haven't found any answers that can help me. Models.py: class Articles(models.Model): ID = models.AutoField(primary_key=True) description = models.TextField() price = MoneyField(blank=True, null=True, decimal_places=2, max_digits=8, default_currency='EUR') class Meta: ordering = ('description',) def __str__(self): return self.description class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() Item_ID = models.ManyToManyField(Items, through="Detail", blank=True) class Detail(models.Model): ID = models.AutoField(primary_key=True) article_id = models.ForeignKey(articles, on_delete = models.CASCADE) Intervention_ID = models.ForeignKey(Interventions, on_delete = models.CASCADE) quantity = models.IntegerField(null=True, blank=True, default='1') I would like to be able to create a Query that takes all the records of the 'Interventions' model and all the records of the 'Details' table. The problem is that if an intervention is made, but without having used any article, the intervention itself is not displayed. How can I do? I tried with prefetch_related but it doesn't seem to work. Heartfelt thanks to everyone. -
Sonarqube displaying 0% of coverage and no unittest in django project using coverage.py
I'm working on creating unitest for a django project I installed sonarqube : docker run -d --name sonarqube -e SONAR_ES_BOOTSTRAP_CHECKS_DISABLE=true -p 9000:9000 sonarqube:latest through docker image and sonar-scanner using this command : docker run -v /home/hind/Desktop/map-manager:/usr/src --network="host" sonarsource/sonar-scanner-cli -Dsonar.host.url=http://localhost:9000/ -Dsonar.login=sqp_e7171bd635104a04d29c523243cf54000946ea7f and I before that I added coverage to my project , I created 23 unitest and all running well except for one that is failling I run tests with : coverage run manage.py run test maps and when I run the report of the sonarqube resultcoverage report and the report is displaying this : Name Stmts Miss Cover --------------------------------------------------- app/__init__.py 0 0 100% app/settings.py 58 10 83% app/urls.py 12 0 100% manage.py 13 6 54% maps/__init__.py 0 0 100% maps/admin.py 141 62 56% maps/migrations/__init__.py 0 0 100% maps/models.py 163 10 94% maps/templatetags/__init__.py 0 0 100% maps/tests.py 195 3 98% --------------------------------------------------- TOTAL 582 91 84% but in sonar-scanner I get 0.0% coverage and nothing in unitest enter image description here sonarsube result I dont know what's the problem so the coverage is not 0.0% -
How to allow multiple IP addresses and use that ip address from different network in django?
Therefore, I need to access my Django project from localhost to some other different network with a different different domain or IP address (my custom domain and ip address). Is there a method to achieve without using any live domain like AWS or GoDaddy? The Django host, ngrok, serveo, and thord parts I tried did not provide a custom domain name or IP. -
Django Machina - display post times in local timezone
I am using django-machina as a forum. I want post times in the forums to be displayed to users in their local times. I have TIME_ZONE = 'UTC' and USE_TZ = True in my settings.py file. I have also installed "pytz." The times are currently displayed in UTC time. I have attempted to use the following in a template: <small>{{ node.last_post.created | localtime }}</small> However this has no effect on the display times. I put this in the template as a test: {% get_current_timezone as TIME_ZONE %} {{ TIME_ZONE }} and it displays "UTC" How can I get the times to display in the user's local time zone? -
Error in AES Encryption/Decryption via python
We have integrated a API through which I am getting a encrypted data. Now in the docs they have given me a software link to decrypt the data. Here is the website they have recommend me to use to decrypt the received data: https://aesencryption.net/ It works fine and I am getting the decrypted data on this website On this website they have given their code they are using for decryption & that is in PHP. I have used chat GPT to convert that PHP code in python with little modification of my own. But it doesn't work with this code. I am mentioning everything that I have and have tried. import hashlib from Crypto.Cipher import AES import base64 class AESFunction: secret_key = None key = None decrypted_string = None encrypted_string = None @staticmethod def set_key(my_key): key = bytes.fromhex(my_key) sha = hashlib.sha256() sha.update(key) key = sha.digest()[:32] AESFunction.secret_key = AESFunction.key = key @staticmethod def get_decrypted_string(): return AESFunction.decrypted_string @staticmethod def set_decrypted_string(decrypted_string): AESFunction.decrypted_string = decrypted_string @staticmethod def get_encrypted_string(): return AESFunction.encrypted_string @staticmethod def set_encrypted_string(encrypted_string): AESFunction.encrypted_string = encrypted_string @staticmethod def encrypt(str_to_encrypt): cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC) encrypted_bytes = cipher.encrypt(AESFunction.pad(str_to_encrypt).encode('utf-8')) AESFunction.set_encrypted_string(base64.b64encode(encrypted_bytes).decode('utf-8')) @staticmethod def decrypt(str_to_decrypt): cipher = AES.new(AESFunction.secret_key, AES.MODE_CBC) decrypted_bytes = cipher.decrypt(base64.b64decode(str_to_decrypt)) AESFunction.set_decrypted_string(AESFunction.unpad(decrypted_bytes).decode('utf-8', errors='replace')) @staticmethod def pad(text): block_size = … -
CSRF_TRUSTED_ORIGINS works only with a string, not with a list as expected
Context I am running a Netbox instance, which uses Django. Inside of its parameters, I have to set CSRF_TRUSTED_ORIGINS to the origins I trust for Netbox to work properly. The Netbox instance I use runs inside a Docker container (netbox-docker). Issue I have found out that if I write these as a list, like expected in the documentation (see here), I get a 403 error with the following description: CSRF verification failed. Request aborted. Activating debug mode also tells me this: Origin checking failed - https://myurl does not match any trusted origins., which I do not understand because my variable looks like this: CSRF_TRUSTED_ORIGINS=['https://172.23.0.5', 'https://myurl']. Temporary workaround If I set the variable as a simple string, I do not get any error: CSRF_TRUSTED_ORIGINS="https://myurl" works flawlessly for myurl (of course, it still blocks all the other URLs). Issue (still) That worked for some time, but now I have to add a second domain name referencing my Netbox instance, so I would need to add "https://myurl2" to the trusted origins list. Since having a list does not work here, I do not really know how to proceed. What I have tried I have tried to change the way I assign its value … -
How to send mail to admin from individual mail I'd in Django?
I'm Working on Employee Management System Project, There is three type of user HR, Director and Employee. I want to send record mail to Director mail I'd from Employees individual email ID. How I can implement this feature, I'm working in Django. I'm trying to implement using Django send_mail() function but there is password providing issue, we can't provide email password for all employees. I want to know how i can implement. -
Form type request in Postman for API with nested serializers in Django Rest Framework
I need to pass the nested dictionary which is the mixture of text and file. I created the nested serializer to get the data from API request. What will be my request like in Postman? Request Structure: { "type":"Large", "category":[ { "category_segment":"A", "category_features":["name", "size", "color"], "action":["pack", "store", "dispatch"], "category_image": **''' Category A Image File Here'''** }, { "category_segment":"B", "category_features":["name", "size", "color"], "action":["pack", "store", "dispatch"], "category_image":**'''Category B Image File Here'''** } ] } Serializer class DataSerializer(serializers.Serializer): category_segment = serializers.CharField() category_features = serializers.ListField(child=serializers.CharField(default='Not Required'),default='Not Required') action = serializers.ListField(child=serializers.CharField()) image = serializers.FileField() class ExtractionSerializer(serializers.Serializer): type = serializers.CharField() category_image = serializers.ListField(child = DataSerializer()) -
Django - How to test an application with millions of users
I want to test a blog application with millions of users particularly where each posts have number of views that is visited by users. Although I tried to login with different browser for each users,its not efficient. How should I test users to login and try this application? Requirements Counts must be real time or near-real time. No daily or hourly aggregates. Each user must only be counted once. The displayed count must be within a few percentage points of the actual tally. The system must be able to run at production scale and process events within a few seconds of their occurrence. Although I tried to login with different browser for each users,its not efficient. -
Passing kwargs into FactoryBoy nested RelatedFactories for pytest
I see so many different ways of doing this that I'm getting a bit of choice paralysis. Problem description I have a top-level FactoryBoy factory, FruitBasketFactory. This defines a RelatedFactory to AppleFactory, a sort of "conduit" factory: AppleFactory defines 2 RelatedFactories: SeedFactory and SkinFactory. Some pseudo code: class FruitBasketFactory(factory.django.DjangoModelFactory): class Meta: model = FruitBasket apple = factory.RelatedFactory( AppleFactory, factory_related_name="fruit_basket" ) class AppleFactory(factory.django.DjangoModelFactory): class Meta: model = Apple fruit_basket = None seed = factory.RelatedFactory( SeedFactory, factory_related_name="apple" ) skin = factory.RelatedFactory( SkinFactory, factory_related_name="apple" ) class SeedFactory(factory.django.DjangoModelFactory): class Meta: model = Seed apple = None num_seeds = 10 seed_color = "black" class SkinFactory(factory.django.DjangoModelFactory): class Meta: model = Skin apple = None skin_color="red" My goal For my tests, I want to set a top-level flag e.g. fruit_basket_factory(apple_type_is_PinkLady=True), and 'pass down state' to all related, dependent factories. In this case, the changes required would be setting: fruit_basket.apple.seed.num_seeds = 5 fruit_basket.apple.seed.seed_color = "brown" fruit_basket.apple.skin.skin_color= "green" Is this possible? I'm imagining some sort of Class Params on each Factory that serve as 'message-passers'? In reality, my conduit factory has around 5-10 RelatedFactories. -
Forbidden (CSRF cookie not set.):- Nodejs 13 with Django
I am trying to send an HTTP POST request from my frontend in Node.js 13 to my Django backend, but I keep getting the error "Forbidden (CSRF cookie not set)." Currently, the application is configured to send an API request to my server to obtain the csrf_token when I open the website. Then, I attempted to send an API request to register with the csrf_token, but encountered the aforementioned error. const respond = await fetch( 'http://127.0.0.1:8000/register/register_user/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken, }, body: JSON.stringify({ name: name, email: email, password: password, passport: passport, trustNode: trustNode, }), cache: 'no-cache', } ); This is my Django settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website_backend', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:8000' ] -
Django model clean function validation error problem
I have a Django model with custom clean function as below: class License(models.Modes): # fields of the model def clean(self): if condition1: raise ValidationError('Please correct the error!') The problem is that, my admin user uploads some file as needed by FileField of License Model, but when I raise the ValidationError file fields are emptied and user is forced to upload the files again. Is it possible to raise the error, but keep the files? -
django primary key auto assigning available id from least value
In django project primary key are assigned automatically. In my model I have some model object with id (=5,6). id (= 1,2,3,4,) is deleted from the DB. Now when I create new object model,django assigning id with the value 7. But I want this to assign in a order like 1,2,3,4 and 7 and so. How can I implement this? I've tried to create a complete different id field with custom logic to assign the available id first,but I was expecting a django built-in function. -
'dict' object has no attribute 'headers': it is coming from clickjacking.py
I have a method that generates pdf cheque for a client. the code as follows @csrf_exempt def generate_pdf(request): body = ujson.loads(request.body) monitoring = Monitoring.objects.filter(tr_id=body['tr_id']).first() if not monitoring: return { "message": MESSAGE['NotDataTrID'] } data = { 'headers': ["Abdulloh",], 'user': monitoring.user, 'tr_id': monitoring.tr_id, 't_id': monitoring.t_id, 'type': monitoring.type, 'pay_type': monitoring.pay_type, 'sender_token': monitoring.sender_token, } pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf') it should generate a cheqeu in the end. But I am receiving an error from python env it is coming from clickjacking.py. Can anyne help. I am using python 3.9 and centos 7 for operation system