Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django edit.py ProcessFormView() question
class ProcessFormView(View): """Render a form on GET and processes it on POST.""" def get(self, request, *args, **kwargs): """Handle GET requests: instantiate a blank version of the form.""" return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ **form = self.get_form()** if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) # PUT is a valid HTTP verb for creating (with a known URL) or editing an # object, note that browsers only support POST for now. def put(self, *args, **kwargs): return self.post(*args, **kwargs) In that part, there is no part that is imported by inheriting self.get_form(), self.form_valid() so I am curious as to how to import it and just use it. Is that incomplete code? To use it normally, should I use "ProcessFormView(View, ModelFormMixin)" like this? The Django version I use is 4.1.5 I wonder why it suddenly appeared. The concept of inheritance clearly exists, but I have my doubts as to whether this is in violation of this. As an example, you can see that other codes inherit very well. `class BaseDeleteView(DeletionMixin, FormMixin, BaseDetailView): """ Base view for deleting an object. Using this base class … -
Raise error for when there is no header matching the specified row name from CSV
The issue is that when user clicks upload csv and picks a file and tries to submit the file. If the header of the file is not equal to "IP Address", then I get the debug menu from Django. The CSV file does not exist in any directory, so it is handled via upload, I was wondering what's best practice for raising an error, I have tried some methods below but still get the debug menu. This is the forms.py class that handles the CSV form. class CSVForm(forms.Form): csv_file = forms.FileField(required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ips_from_csv = [] def get_ips_from_csv(self): return self.ips_from_csv def clean_csv_file(self): csv_file = self.cleaned_data.get("csv_file") if not csv_file: return with csv_file.open() as file: reader = csv.DictReader(io.StringIO(file.read().decode("utf-8"))) for row in reader: form_data = self.cleaned_data.copy() form_data["address"] = NetworkUtil.extract_ip_address(row["IP Address"]) self.ips_from_csv.append(form_data["address"]) That is what currently works, below is the code that I have tried to implement, but I am no sure how to handle the error side of things. if form_data["address"] != row["IP Address"]: print("Invalid") and this with open(file, "r") as inf: csv_reader = csv.DictReader(inf) for header in csv_reader: if header != row["IP Address"]: print("Invalid") -
Python web development using django
My error is in tinymce admin.py have indentation error:unindent does not match any outer indentation level I tried in import From django.utils. encoding import smart_str.the error in the line formfield_overrides={ models.TextField:{"widget":TinyMCE()} ) -
why does coming this error when in visual studio terminal?
pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 pipenv django + CategoryInfo : ObjectNotFound: (pipenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException i want to install pipenv Django -
One to many relationships in Django ORM
I have built several database systems for managing parts databases in small electronics manufacturing setups. I am repeating the process using Django5 and MySQL. I'm a noob with Django but have used MySQL a lot in Java and Python. Consider the tables class Bom(models.Model): bom = models.AutoField(primary_key=True); bompart = models.ForeignKey(Part, on_delete=models.CASCADE) revision = models.CharField(max_length=1) class BomLine(models.Model): bom = models.ForeignKey(Bom, on_delete=models.CASCADE) part = models.ForeignKey(Part, on_delete=models.CASCADE) designator = models.CharField(max_length=10, primary_key=True) ordinal = models.IntegerField() qty = models.DecimalField(max_digits=11, decimal_places=4) class Meta: constraints = [ models.UniqueConstraint(fields=['bom', 'designator'], name='bomdesignator')] class Part(models.Model): groupid = models.ForeignKey(PartGroup, on_delete=models.CASCADE) partno = models.AutoField(primary_key=True) partdescription = models.CharField(max_length=100) (I've omitted the PartGroup table as it is unrelated to my question). The idea is that a bill-of-materials is defined in the Bom table. The system automatically assigns an integer id, and a part is nominated as the 'parent' of this BOM - ie the BOM is the materials list need to make the nominated part. Each BOM refers to BomLines. We can have many lines in a BOM for each component. Since there may be many of the same type of component in a BOM, a 'designator' is used to state exactly where in the assembly the part belongs. (The 'ordinal' field is only … -
Is it safe to pass a user object to a Django template?
I have a user model that stores all user data, for example username, password, favorite_color, etc. I pass the data to the template like this TemplateView def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) user_object = User.objects.get(email=self.get_object()) data['user_data'] = user_object return data and I display non-confidential data on the page <span class="favorite_color">{{ user_data.favorite_color }}</span> I'm wondering if it's safe to pass a User object to a page, but not display private data through a template (for example, {{user_data.password}}) Do I need to only send the specific data I want to use on the page? Or can I still send the whole user object? Let's just assume the developer doesn't make any mistakes. -
django TemplateDoesNotExist at password_reset_subject
I'm building a user authentication app in django, and following this tutorial: https://dev.to/earthcomfy/django-reset-password-3k0l I'm able to successfully get to the password_reset.html template, where I can enter an email address and submit. If I enter an email that is not associated with a user, the success_message from the ResetPasswordView is triggered, but if I enter a valid email address, associated with a user, I get the error. I did everything as per the tutorial, and I've verified that my email configs work by using EmailMessage module from the django shell to send emails. my ResetPasswordView: class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') I have all the templates in that class in the relevant places. The password_reset_subject is a .txt file as per the tutorial. Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /Users/.../user_management/users/templates/users/password_reset_subject (Source does not … -
Django The included URLconf '_mod_wsgi_...' does not appear to have any patterns in it
I am a Python novice and I am trying to run a Django hello world app on Windows. The upper error message shows up with the following code: import os import sys import site from django.core.wsgi import get_wsgi_application from django.conf import settings from django.urls import path from django.http import HttpResponse site.addsitedir("C:/Program files/python312/Lib/site-packages") sys.path.append('C:/Users/felhasznalo/Desktop/django') sys.path.append('C:/Users/felhasznalo/Desktop/django/todo') settings.ROOT_URLCONF=__name__ settings.ALLOWED_HOSTS = ['localhost', '127.0.0.1'] settings.SECRET_KEY = '1234' def hello(request): return HttpResponse("Hello World!") urlpatterns = [ path("", hello) ] application = get_wsgi_application() I checked a bunch of similar questions, but none of the answers appear to fix this. Any idea what to do or how to debug this? I have the urlpatterns variable present, the hello is a function, the "" is a valid path, still it does not seem to find the variable... :S :S :S I wonder why it uses global variables though instead of argument passing. Does not seem to be a well designed framework... -
django.contrib.auth.models.Group not shown in ios
In my django project (rechentrainer.app) I created two groups to manage my users: "lehrer" and "schüler". In all browsers and at all devices I can assign them to my users - but not in ios on my iPad or iPhone - the groups are not shown. In Safari on the Mac it works fine. I found no hint in the django manual and the guys in my german python/django forum have no idea. I even ask my provider. -
Django JSON file - Which file should "model": refer to?
I am trying to populate my model with the fields I have input in the json but I am unsure which file the "model": should refer to? I assume it should be where the model is located but I always get an error when I try to load the file - Problem installing fixture '/workspace/django-film-club/film/fixtures/films.json': film/fixtures/films.json; [ { "model": "film.movie", "pk": null, "fields": { "title": "Django Unchained", "slug": "django-unchained", "year": 2012, "genre": "WESTERN", "synopsis": "<p>With the help of a German bounty-hunter, a freed slave sets out to rescue his wife from a brutal plantation owner in Mississippi.<p>", "director": "Quentin Tarantino", "excerpt": "A freed slave sets out to rescue his wife from a brutal plantation owner in Mississippi.", "added_on": "2024-06-01T09:43:19.754Z" } }, ] film/models.py; class Movie(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) year = models.IntegerField(('year'), default=datetime.datetime.now().year) genre = models.CharField(max_length=15, choices=GENRE_CHOICES, default='horror') synopsis = models.TextField() director = models.CharField(max_length=200, unique=True) excerpt = models.TextField(blank=True) added_on = models.DateTimeField(auto_now_add=True) The only thing I can thnk is that that the model in the json file is incorrect, I have tried diffent names for the model: input but still doesnt seem to work. I expected, if sucessful to load the data into the site but I … -
I wish to perform a case-insensitive search in Django with a MySQL database
I'm trying to perform a case-insensitive search on a model in Django. I get a case-sensitive search instead. According to the Django docs, utf8_general_ci collation will result in a case-insensitive search. My current collation is utf8mb4_0900_ai_ci. I tried: SELECT dbasename ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 collate utf8_general_ci; but that gave me: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ALTER TABLE website_card CONVERT TO CHARACTER SET utf8mb4 collate utf8_general_c' at line 2 I don't understand what I'm doing wrong. Please advise. -
Slack Events endpoint not trigerring for large payload
I'm using Slack Bolt in my Django application to handle Slack events and shortcuts. I have set up an events endpoint in Slack, and it works perfectly fine when the payload size is small. However, I'm facing issues when the payload is large, such as when there are multiple media attached to the text where the user triggered the shortcut or when the text itself is extensive. In these cases, my backend does not seem to receive any trigger from Slack. Here are the specific details and steps I've taken so far: Normal Payloads: When the payload size is small (normal text or media), the events endpoint works without any issues. Large Payloads: When the payload size is large, my backend does not receive the trigger. I used oscato to monitor the requests, and I can confirm that Slack is indeed sending the trigger. This suggests that the issue lies within my backend. Events Endpoint Setup: Here is what my events endpoint looks like in my Django backend: slack_request_handler = SlackRequestHandler(app=slack_app) def slack_handler(request): return slack_request_handler.handle(request) Steps I have taken to debug this issue: Confirmed that Slack is sending the trigger for large payloads using oscato. Verified that the endpoint works … -
Content Security Policy when clients access via Windows Remote Desktop
Have django-csp working in report only mode on application deployed on aws using gunicorn/nginx. No reported issues in dev or prod except when clients log into their work computers to work remotely. Using a secured remote desktop session (I can recreate accessing production web using browser running in vm). I get nothing but errors and warnings about hosted page injection. Now my understanding is that CSP is meant to protect against unauthorized CSS but are there settings or headers that will allow site to operate in an approved remote window. Any guidance is appreciated. -
Django Rest Framework ManytoMany Feld Serializing
Models: class MaterialAttribute(models.Model): """ Represents a material attribute. Attributes: name (CharField): The name of the material attribute. """ class Meta: verbose_name = "Material Attribute" verbose_name_plural = "Material Attributes" db_table = "material_attribute" name = models.CharField(max_length=255) def __str__(self): return f"{self.name}" class MaterialType(models.Model): """ Represents a material type. Attributes: name (CharField): The name of the material type. attributes (ManyToManyField): The attributes of the material type. """ class Meta: verbose_name = "Material Type" verbose_name_plural = "Material Types" db_table = "material_type" name = models.CharField(max_length=255) attributes = models.ManyToManyField( MaterialAttribute, related_name="material_types" ) def __str__(self): return f"{self.name}" I want to write a MaterialTypeSerializer in that way, that for list/retrieave it returns the Json representation { "id": 1, "name": "Test", "attributes": [ { "id": 1, "name": "Format" }, { "id": 2, "name": "Farbe" } ] } of the Attrtibutes and for create/update { "name": "Test", "attributes": [ { 1 }, { 2 } ] } the primary key. class MaterialAttributeSerializer(serializers.ModelSerializer): """ Serializer for the MaterialAttribute model. This serializer includes the following fields: - id: The unique identifier of the material attribute. - name: The name of the material attribute. All fields are read-only. It is used to serialize minimal material attribute data. """ class Meta: model = MaterialAttribute fields … -
how can the logined user can only create and update their portfolio details only in django>>Can anyone explain?
Part 1 : User Profile Management Robust user profile management system facilitating the creation and customization of personal profiles, including biographical information, skill sets, and contact details. Part 2 : Portfolio Customization Intuitive interfaces enabling users to tailor their portfolios with personalized content, including project showcases, work experience, education, and certifications. Part 3 : Project Showcase A visually appealing and interactive presentation of past projects, complete with detailed descriptions, images, and relevant links to provide visitors with a comprehensive understanding of the showcased work -
My Django for-loop is not displaying the elements
I'm making a loop to display all the songs in my music streaming website homepage with a carousel but is not working (it doesn't display nothing but i have like 10 songs in my database). How can i fix it? This is my html code: <div id="All-songs" style="padding: 5px"> <h2>All Songs</h2> <div class="main-carousel" data-flickity='{"groupCells":5 , "contain": true, "pageDots": false, "draggable": false, "cellAlign": "left", "lazyLoad": true}'> {% for i in allsongs %} <div class="carousel-cell"> <section class="main_song"> <div class="song-card"> <div class="containera"> <img src="{{i.image}}" id="A_{{i.id}}" alt="song cover"> <div class="overlaya"></div> <div> <a class="play-btn" href="{{i.preview_url}}" id="{{i.id}}"><i> class="fas fa-play-circle"></i></a> {% if user.is_authenticated %} <div class="add-playlist-btn"> <a id="W_{{i.song_id}}" title="Add to Playlist" onclick="showDiv(this)"></a> </div> {% endif %} </div> </div> </div> <div> <p class="songName" id="B_{{i.id}}">{{i.name}}</p> </div> <p class="artistName">{{i.singer1}}</p> </section> </div> {% endfor %} </div> </div> this is views.py: def allSongs(request): myPlaylists = [] user = request.user if user.is_authenticated: # Extracting Playlists of the Authenticated User myPlaylists = list(Playlist.objects.filter(user=user)) try: allsongs = list(Song.objects.all()) random.shuffle(allsongs) return render(request, 'allSongs.html', {'allsongs': allsongs, 'myPlaylists': myPlaylists}) except: return redirect("/") and this is models.py: class Song(models.Model): song_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) artist = models.CharField(max_length=50) album = models.CharField(max_length=50, blank=True) genre = models.CharField(max_length=20, blank=True, default='Album') song = models.FileField(upload_to="media/songs/", validators=[FileExtensionValidator(allowed_extensions=['mp3', 'wav'])], default="name") image = models.ImageField(upload_to="media/songimage/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], … -
I recover the database on xampp mysql but store procedures were lost
I have an issue with XAMPP MySQL unable to start MySQL and access databases. I start MySQL and recover the database, but my stores procedures did not exist. where do they go? how do get them back. Thank you. I expect steps on how to fix this problem, queries or commands which shows the steps to get sored procedures back. -
How to do session-based authentication
For the backend of a project, we are combining FastAPI and Django. Why FastAPI? We need to use WebSockets and FastAPI supports that natively We like the Pydantic validation & auto-documentation it include Why Django? We want to make use of the builtin authentication & authorization (permissions) features We like to be able to use its ORM Why not Django-ninja? It does not support WebSockets Why not Django with Django Rest Framework for the API & with Channels for WebSockets? We prefer FastAPIs API features over DRF We like that FastAPI supports WebSockets natively We would like to authenticate & authorize the FastAPI endpoints based on the auth features that Django has (builtin User sessions & permissions). I'm struggling to find a good way of securing the FastAPI endpoints with the sessions from Django. In the code below you can see the current setup: main.py: FastAPI is set up here with (1) a router containing the FastAPI endpoints and (2) the Django application mounted router.py: Contains the FastAPI endpoints, I would like to make use of Django's builtin user sessions for authentication & authorization of the FastAPI endpoints. ## main.py (FastAPI) import os from django.conf import settings from django.core.asgi import … -
Django LoginRequiredMixin not redirecting to login page
I have a django e-commerce website and when I am trying to add a product without logging in, I am not being redirected to the login page. When I try to add a product without being logged in, on my terminal it says: [16/Jun/2024 07:18:26] "POST /cart/ HTTP/1.1" 302 0 [16/Jun/2024 07:18:26] "GET /login/?next=/cart/ HTTP/1.1" 200 134934 But I stay on the same page. Why is this not redirecting me to the login page? Thanks in advance! My views.py: def user_login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') CustomUser = authenticate(request, username=username, password=password) if CustomUser is not None: login(request, CustomUser) messages.success(request, 'Login successful.') return redirect('home') else: messages.error(request, 'Invalid username or password.') return render(request, 'users/user_login.html') class CartView(LoginRequiredMixin, View): def get(self, request): cart_items = Cart.objects.filter(user=request.user) total_price = sum(item.product.price * item.quantity for item in cart_items) return render(request, 'business/cart.html', {'cart_items': cart_items, 'total_price': total_price}) @method_decorator(login_required) def post(self, request): try: data = json.loads(request.body) product_id = data.get('product_id') selected_variations = data.get('selected_variations', []) quantity = data.get('quantity', 1) # Get the quantity from the request logger.debug(f'Received product_id: {product_id} with variations: {selected_variations} with quantity {quantity}') except json.JSONDecodeError: logger.error("Invalid JSON data in the request body") return JsonResponse({'error': 'Invalid JSON data'}, status=400) if not product_id: logger.error("No product_id provided in the … -
How to get a value from radio buttons in Django form?
I have a HTML form. I need to get a value from radio button to pass it ti the model instance, but I'm getting a request without chosen radio button value, what's the problem? product.html <form action="{% url 'add_comment' %}" method="POST" class="addCommentForm" id="commentProductForm"> {% csrf_token %} <input type="text" name="comment_text" class="search-input" id="comment_text" placeholder="Введите отзыв..."> <div class="rating-area"> <label for="star-5" title="Оценка «5»"></label> <input type="radio" id="star-5" name="rating" value="5"> <label for="star-4" title="Оценка «4»"></label> <input type="radio" id="star-4" name="rating" value="4"> <label for="star-3" title="Оценка «3»"></label> <input type="radio" id="star-3" name="rating" value="3"> <label for="star-2" title="Оценка «2»"></label> <input type="radio" id="star-2" name="rating" value="2"> <label for="star-1" title="Оценка «1»"></label> <input type="radio" id="star-1" name="rating" value="1"> </div> <input type="hidden" name="product_id" value="{{ product.id }}"> <input type="submit" value="ОТПРАВИТЬ" class="search-btn"> </form> views.py def add_comment(request): if request.method == 'POST': ''' A request like b'comment_text=r&product_id=14395& csrfmiddlewaretoken=2inK4JGd1nqjS79p5Z6x78IupBqMOcNGGMuFJKW8zYIN2pzMlij4hyumV7G5k0H1' But without choosen radio button ''' print(f'\n{request.body}\n') text = request.POST.get('comment_text') product_id = request.POST.get('product_id') stars = request.POST.get('rating') # Here it shows None print(f'\n\nType: {type(stars)}\nValue: {stars}\n\n') if text == '': return JsonResponse({'success': False, 'message': 'Invalid data'}) profile = Profile.objects.get(user=request.user) product = Product.objects.get(id=product_id) Comment.objects.create(text=text, author=profile, product=product) return JsonResponse({'success': True, 'text': text, 'author': profile.first_name}) return JsonResponse({'success': False}) -
How do I update my code to have login and signup on the same page in django?
I want to have the login and sign up form on the same page, I also want to signup and login depending on which button was clicked. Here is my registration page enter image description here enter image description here and here is my views.py def register_view(request): if request.method == "POST": form = UserRegisterForm(request.POST or None) if form.is_valid(): new_user = form.save() username = form.cleaned_data.get("username") messages.success(request, f"Hey {username}, Your account was created successfuly") new_user = authenticate(username=form.cleaned_data['email'], password = form.cleaned_data['password1']) login(request, new_user) return redirect("core:index") else: print("User cannot be registered") form = UserRegisterForm() context = { 'form': form, } return render(request, "userauths/sign-up.html", context) def login_view(request): if request.user.is_authenticated: return redirect("core:index") if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.object.get(email=email) except: messages.warning(request, f"User with {email} does not exist") user = authenticate(request, email=email, password=password) if user is not None: login(request, user) messages.succes(request, "You are logged in") return redirect("core:index") else: messages.warning(request, "User does not exist. Create an account!!") context = { } return render(request, "userauths/sign-in.html", context) register.html <div class="login-form"> <form class="sign-in-htm" method="post" method="POST"> {% csrf_token%} <div class="group"> <label for="user" class="label">Email</label> <input id="user" type="text" class="input" required name="email"> </div> <div class="group"> <label for="pass" class="label">Password</label> <input id="pass" type="password" class="input" name="password" required data-type="password"> </div> <div class="group"> … -
No module named 'diabetes_proj'
I struck with problem when i was trying to deploy my Django project on Heroku infrastructure. I have this heroku logs --tails: 2024-06-15T18:37:26.503332+00:00 app[web.1]: return util.import_app(self.app_uri) 2024-06-15T18:37:26.503332+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-15T18:37:26.503333+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/util.py", line 371, in import_app 2024-06-15T18:37:26.503333+00:00 app[web.1]: mod = importlib.import_module(module) 2024-06-15T18:37:26.503333+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-15T18:37:26.503333+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/importlib/_init_.py", line 90, in import_module 2024-06-15T18:37:26.503333+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2024-06-15T18:37:26.503334+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1387, in _gcd_import 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1360, in _find_and_load 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1310, in _find_and_load_unlocked 2024-06-15T18:37:26.503334+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed 2024-06-15T18:37:26.503335+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1387, in _gcd_import 2024-06-15T18:37:26.503335+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1360, in _find_and_load 2024-06-15T18:37:26.503335+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked 2024-06-15T18:37:26.503335+00:00 app[web.1]: ModuleNotFoundError: No module named 'diabetes_proj' 2024-06-15T18:37:26.503390+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [9] [INFO] Worker exiting (pid: 9) 2024-06-15T18:37:26.523181+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [2] [ERROR] Worker (pid:9) exited with code 3 2024-06-15T18:37:26.523524+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [2] [ERROR] Shutting down: Master 2024-06-15T18:37:26.523543+00:00 app[web.1]: [2024-06-15 18:37:26 +0000] [2] [ERROR] Reason: Worker failed to boot. 2024-06-15T18:37:26.603484+00:00 heroku[web.1]: Process exited with status 3 2024-06-15T18:37:26.629365+00:00 heroku[web.1]: State changed from starting to crashed Heroku can't find my wsgi.py file. Here … -
504 Timeouts after setting django CSRF_TRUSTED_ORIGINS
I have a django 5.0 site deployed to elastic beanstalk with a domain and https through cloud front. When i make POST requests without the CSRF_TRUSTED_ORIGINS setting set, i get 403 errors. When i set the CSRF_TRUSTED_ORIGINS setting, i get 504 timeouts. I have tried SSH'ing into the box and running the POST directly against the django site-- it does the timeout there too. So it's definitely not AWS. Something with django. I've also tried downgrading to django 4-- didn't work either. Everything works perfectly locally. Any ideas? -
Replace Redis in a Django with Valkey
TLDR: Has anyone had experience replacing Redis with Valkey in their Docker compose for Django? I have a running Django instance that also uses Redis. Here I would like to replace Redis with Valkey. Currently I do not use Redis more than it is used by the standard processes of Django, but I became aware of it through the processes in Redis and their change of license. My question is whether I need to pay attention to anything special when switching and whether there are any known weaknesses or problems. Also in relation to a Docker Compose setting. -
Deploying Django project with Nginx, uWSGI and docker
I am trying to deploy and run a django application by using uWSGI, Nginx and docker on DigitalOcean. The Nginx and uWSGI works fine (I think) but I do not know why the uWSGI do not recieve any requests from Nginx. Here is my nginx configuration # upstream for uWSGI upstream uwsgi_app { server unix:/tmp/uwsgi/my_project.sock; } # upstream for Daphne upstream daphne { server unix:/tmp/uwsgi/my_project_daphne.sock; } server { listen 80; server_name www.domaine.com domaine.com; return 301 https://$host$request_uri; } server { listen 443 ssl; ssl_certificate /code/django_project/ssl/certs/cert.pem; ssl_certificate_key /code/django_project/ssl/certs/key.pem server_name www.domaine.com domaine.com; error_log stderr warn; access_log /dev/stdout main; location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgi_app; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://daphne; } location /static/ { alias /code/django_project/staticfiles/; } location /media/ { alias /code/django_project/mediafiles/; } } my uWSGI file [uwsgi] socket = /tmp/uwsgi/my_project.sock chdir = /code/django_project/ module = django_project.wsgi:application master = true processes = 2 chmod-socket = 666 uid = www-data gid = www-data harakiri = 60 vacuum = true buffer-size = 32768 logger = file:/tmp/uwsgi.log log-maxsize = 200000 **My Dockerfile ** FROM python:3.11.5 ### 3. Set environment variables ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN mkdir /code COPY . /code/ WORKDIR /code RUN …