Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data from Django form doesn't get saved to MySQL table
I am trying to save data, collected via a Django form, to the DB. The page is designed to first ask user for an input, based on which a list is generated. I am trying to save values corresponding to these generated items. But this data, while I see it in the POST request, just doesn't get saved. I am assuming the error is in my Save logic, but I just cannot find it out. I have the views defined to save this, and also the relevant URLs. The Django logs show no error, and there are none when I look into the DB error log. Here's how my code looks like: Model class MonthlySheet(models.Model): month = models.IntegerField() year = models.IntegerField() org_name = models.ForeignKey(Establishment, on_delete=models.DO_NOTHING) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, default=None) wages = models.IntegerField() gross = models.IntegerField() total_work_days = models.IntegerField() present_days = models.IntegerField() calc_twelve = models.DecimalField(max_digits=10, decimal_places=2) calc_eight_three_three = models.DecimalField(max_digits=10, decimal_places=2) calc_diff = models.DecimalField(max_digits=10, decimal_places=2) calc_point_seven_five = models.DecimalField(max_digits=10, decimal_places=2) def get_absolute_url(self): return reverse('monthly_sheet_detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): self.pk = f"{self.month}.{self.year}" super().save(*args, **kwargs) View: class AddMonthlySheetView(FormView): template_name = 'add_monthlysheet.html' form_class = CustomMonthlySheetForm model = MonthlySheet def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) last_month, year, total_work_days = set_previous_month() context['last_month'] = last_month … -
HTTP 404 error for css and javascript files in Django and Gunicorn
The actual error is Refused to apply style from 'http://127.0.0.1:8000/static/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://127.0.0.1:8000/static/js/home.js net::ERR_ABORTED 404 (Not Found) This error started happening when I started using Gunicorn as app server. The first error for css is a misdirection. The file was not found to begin with. Chrome developer tools shows Request URL:http://127.0.0.1:8000/static/css/home.css Request Method:GET Status Code:404 Not Found Referrer Policy:same-origin Connection:close Content-Length:8559 Content-Type:text/html Date:Wed, 07 Jun 2023 19:32:29 GMT Referrer-Policy:same-origin Server:gunicorn status code. I see the same status code for all the css and javascript files. Here are my relevant settings settings.py INSTALLED_APPS = [ . . 'django.contrib.staticfiles', 'bootstrap4', . . ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "kubera/static"), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") import mimetypes mimetypes.add_type("text/css", ".css", True) manage.py collectstatic command copied the files correctly ~/workspace/djangoapp/src$ python3 manage.py collectstatic 161 static files copied to '/home/<myhomedir>/workspace/djangoapp/src/static'. index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% bootstrap_messages %} <link href="{% static 'css/home.css' %}" type="text/css" rel="stylesheet"> <title>{% block title %}Parier Config Central {% endblock %}</title> </head> … -
How to find out where Django is querying from?
I am relatively new to Django and web development in general. I am working on a project with my company (small company, three developers here currently who all have little to no experience) which has very little documentation, and the person who used to work on it is gone. I am getting errors when building the project, and part of the problem I think is that I may have incorrect data for building the project. My specific question is, when you call something like Model.objects.get(), how can you tell where the program is "getting" this information from? My project has a ton of moving parts - an sqlite db, a csv spreadsheet, a whole directory of audio recording sessions, and is making use of all of them. I am not sure whether this get() is looking at any of these, or possibly an API that no one currently in my company even knows exists. Is there a standard file in most Django projects where I could see what Model.objects.get() looks at when fetching the data? -
How to cache beautified / prettified outputted HTML rendered by Django?
I've implemented a Middleware after researching how to beautify / prettify (format nicely), the outputted HTML rendered in the browser for my Django project. I came across this method here. settings.py # local Memcached CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... 'django.middleware.gzip.GZipMiddleware', 'myproject.middleware.HTMLBeautifyMiddleware', # needs to come after gzip ] myproject/middleware.py from bs4 import BeautifulSoup class HTMLBeautifyMiddleware(object): TAGS = ["p", "script", "span", "i", "h1", "h2", "h3", "h4", "h5", "h6"] def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if response.status_code == 200: if response["content-type"].startswith("text/html"): html = BeautifulSoup(response.content, "lxml", preserve_whitespace_tags=self.TAGS) response.content = html.prettify() return response In the discussion on the blog, a comment mentions: I’d advise to cache the output before using this plugin on a production site. My questions are: How would one go about caching the outputted HTML? Does Django or the browser handle caching the outputted HTML for me, or do I need to do something explicitly to make it happen? If I used AWS Cloudfront, would that be a solution? -
Unable to send email using celery in DRF
I'm unable to send email via smtp using celery task and DRF. I have the following constants in settings.py # Celery settings CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # Email settings EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = MY_EMAIL EMAIL_HOST_PASSWORD = MY_PASSWORD EMAIL_USE_TLS = True EMAIL_USE_SSL = False tasks.py from django.core.mail import send_mail from celery import shared_task @shared_task def send_verification_email(user_email): send_mail( subject="test email", message="testing", from_email=settings.EMAIL_HOST_USER, recipient_list=[user_email], fail_silently=False ) views.py class RegisterUserAPIView(generics.GenericAPIView): ... user_email = ... send_verification_email.delay(user_email = user_email) ... The error I'm getting is raised unexpected: SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)') Also, if i'm using console instead of smtp in below EMAIL_BACKEND, i'm able to send emails to the console without any problem.. EMAIL_BACKEND ='django.core.mail.backends.console.EmailBackend' I have EMAIL_USE_SSL = False but still asking for SSL certificate ? Not understanding how to fix this issue. -
pyQt5 ui connected a Django services
I want to create a program for organizations. that has a simple interface and is linked to the Django project for the large parent organization, Where you receive the order from one of the branches by to the interface ui ,, Django sends the results,, can I use puQt5 for ui interface and Django for server? Can I make a ui interface with pyQt5 for multy entreprises Connected to the django project with a mother entreprise? -
How can I create a user login/registration model using Django Rest Framework without getting a response code 403 when trying to create user?
So I am working on a project using Django and Django rest framework. I'm trying to create an api for my website which allows users to register/log in/log out. I'm following [this tutorial] (https://iheanyi.com/journal/user-registration-authentication-with-django-django-rest-framework-react-and-redux) for the initial set up. My issue is that when I try to run my test code to create a user, I get a response code 403 which I guess means I'm trying to do something I don't have permission to do? How can I get rid of this issue so I can create users? Here is my tests.py: from django.test import TestCase from django.urls import reverse from rest_framework.test import APITestCase from django.contrib.auth.models import User from rest_framework import status class TestUserApi(APITestCase): def setUp(self): self.test_user = User.objects.create_user('testuser', 'test@example.com', 'testpassword') self.create_url = reverse('user-create') def test_create_user(self): data = { 'username': 'foobar', 'email': 'foobar@example.com', 'password': 'somepassword' } response = self.client.post(self.create_url , data, format='json') # We want to make sure we have two users in the database.. self.assertEqual(User.objects.count(), 2) # And that we're returning a 201 created code. self.assertEqual(response.status_code, status.HTTP_201_CREATED) # Additionally, we want to return the username and email upon successful creation. self.assertEqual(response.data['username'], data['username']) self.assertEqual(response.data['email'], data['email']) self.assertFalse('password' in response.data) def test_create_user_with_short_password(self): data = { 'username': 'foobar', 'email': 'foobarbaz@example.com', 'password': 'foo' … -
How to access Product name and all details from sub Category using Django?
I want to get product name and all its details from sub category, I tried a lot to find how to do it but it didn't work When clicking on the sub category the related products should appear ,If anyone knows the query please tell me I have made four models First Main category Second category Third SubCategory Category contains the foregion key of the main category Also In sub category the foregion key of category is given And in the product model, the foreign key of the above three models is given I try this query Product.objects.all().select_related('main_category').select_related('category').select_related('sub_category') Please tell me and its html part too -
How to order the results by two columns using admin.display decorator
Please consider the following example: # models.py class Case(models.Model): number = models.SmallIntegerField(null=False, blank=False) year = models.SmallIntegerField(null=False, blank=False) ... #admin.py @admin.register(Case) class CaseAdmin(admin.ModelAdmin): list_display = ['case_number', ...] ordering = ['-year', '-number'] @admin.display(ordering=['-year', '-number']) def case_number(self, case): return f'{case.number} / {case.year}' Now how can I specify the order to be by '-year' and '-number' using the admin.display() decorator? If it can not be done with the admin.display() decorator, is there another way to achieve that? Thanks -
`django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured` when I try to start the daphne
I have a django project. When I start runserver - everything is fine. But if I try to start the daphne asynchronous server (daphne -p 8001 config.asgi:application), I get an error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Settings in wsgi and asgi are the same os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') Maybe someone came across and can me help? Here ais full traceback File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dima/PycharmProjects/TyuMeb/Back_reload/venv/lib/python3.11/site-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/dima/PycharmProjects/TyuMeb/Back_reload/config/asgi.py", line 16, in <module> from chat import routing File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/routing.py", line 3, in <module> from . import consumers File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/consumers.py", line 9, in <module> from chat.models import Conversation, Message File "/home/dima/PycharmProjects/TyuMeb/Back_reload/chat/models.py", line 3, in … -
Static url is not working whenever I am trying to use slug to show a blog details
My other pages static url is working great but when ever I am trying to show a blog details, my static url is changing its showing http://127.0.0.1:8000/blog/this-is-testing-number-1/media/assets/css/bootstrap.min.css instead of http://127.0.0.1:8000/media/assets/css/bootstrap.min.css my blog app views.py from django.shortcuts import render from .models import Blog # Create your views here. def details(request, slug): blog = Blog.objects.get(slug=slug) context = { 'blog':blog } return render(request, 'blog/blog_details.html', context) my blog app urls.py from django.urls import path, include from froala_editor import views from .views import * urlpatterns = [ path('froala_editor/',include('froala_editor.urls')), path('<slug>/', details, name='details') ] my blog details.html <!-- CSS ================================================== --> <link rel="stylesheet" href="media/assets/css/bootstrap.min.css" /> <link rel="stylesheet" href="media/assets/css/magnific-popup.css" /> <link rel="stylesheet" href="media/assets/css/owl.carousel.min.css" /> <link rel="stylesheet" href="media/assets/css/simple-scrollbar.css" /> <link rel="stylesheet" href="media/assets/css/fontawesome.all.min.css" /> <link rel="stylesheet" href="media/assets/css/style.css" /> <script src="media/assets/js/modernizr.min.js"></script> </head> my static settings STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIR = { os.path.join(BASE_DIR , "public/static") } MEDIA_ROOT = os.path.join(BASE_DIR, 'public/static') MEDIA_URL = '/media/ my main urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('blog/', include('blog.urls')), path('account/', include('account.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() how to fix this. I … -
issue sending uploaded image file from reactJS frontend to django python backend (file sending as undefined)
I am trying to send various data types from user input on the reactJS frontend to the Django python backend and getting an error where the text string sends but the image file does not. here is where I am sending the image and caption handleSubmit = async () => { try { const formData = new FormData(); console.log('Image: ', this.props.fileInput); console.log('Image type: ', typeof this.props.fileInput); console.log('Image is a File: ', this.props.fileInput instanceof File); formData.append('file', this.props.fileInput); // formData.append('file', this.props.file); formData.append('caption', this.state.caption); for (let pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } const response = await axios.post(API_URL, formData, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response.status === 200) { console.log('Image uploaded successfully'); } } catch (error) { console.error(error); } } on the caption component and for the image component I did updateImage = async (imageId, caption) => { try { const formData = new FormData(); console.log('File:', this.state.file); console.log('Caption:', caption); formData.append('file', this.state.file); formData.append('caption', caption); for (let pair of formData.entries()) { console.log(pair[0] + ', ' + pair[1]); } const response = await axios.post(API_URL, formData, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response.status === 200) { console.log('Image processed successfully'); const currentState = this.state; const newState = {...currentState}; newState.elements[imageId].URL = … -
Django formatting DecimalField to money
In my Django project I'm saving a money amount in a decimalField. The problem is the format of the number when I print it. I need it in the german money format 10.000,00 € so first a point as seperator and a comma for the cents. In Django I've only managed it to seperate everything with commas like 10,000,00 Has anyone an idea how I can implement it as I want? -
Ajax call to load dropdown with value associated with selected customer profile
Im getting a project that is associated with the selected customer. Whenever I try and submit the form im getting <ul class="errorlist"><li>project<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>. For the life of me I can't figure why because its giving me the correct project. var querysetURL = "{% url 'administration:get_queryset' %}" $(document).ready(function () { $('#customer-profile').change(function (e) { e.preventDefault(); var customerProfile = $(this).find(":selected").val(); $.ajax({ url: querysetURL, method: 'GET', data: { filter_data: customerProfile }, success: function (data) { console.log(data); var projectDropdown = $('#id_project'); projectDropdown.empty(); var option = $('<option>').text(data); projectDropdown.append(option); }, error: function (xhr, status, error) { console.log("error"); console.log(error); console.log(status) } }); }); <div class="col-md-6" id="customer-profile"> {{ form.customer_profile|as_crispy_field }} </div> <!-- Display the project --> {{ form.project|as_crispy_field }} def get_queryset(request): filter_data = request.GET.get("filter_data") if filter_data: print("filtering..") profile = Profile.objects.get(id=filter_data) queryset = [profile.project] # queryset = Project.objects.filter(profile=profile) else: queryset = Project.objects.none() return HttpResponse(queryset) # TICKET CREATION VIEW @login_required def create_ticket(request): form = CreateTicketForm(data=request.POST or None, files=request.FILES or None) # queryset = get_queryset(request) if request.method == 'POST': if form.is_valid(): form_obj = form.save(commit=False) form_obj.created_by = request.user # project_id = request.POST.get('project') # print(project_id) # messages.info(request, project_id) # print(request.POST) # if project_id: # try: # project = Project.objects.get(id=project_id) # form_obj.project = … -
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 …