Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail PageChooserBlock custom ordering
I'm using PageChooserBlock to display list of objects class ActualSection(models.Model): content = StreamField( [ ("article", PageChooserBlock(page_type="articles.Article")), ], min_num=1, ) Is there any way to put some custom ordering on it? Because now it's seems like having some random order -
how to make a custom error for empty input in a field (i.e. name = serializers.CharField(required=True))?
name = serializers.CharField(required=True) def validate(self,data): if not name: //Return error I want to validate name or check if it's empty in def validate_name(self,value): I tried to trigger def validate and def validate_name and I expected a return from there but instead I am getting error from default rest framework -
How to get header value to the particular class?
def prep_head(self, requestParams, requestType,): return { 'content-type': "application/json", 'id': "xyz" } How to add the id header dynamically? I want to power this one on the prod link. Anhybody please help!!!!!!!!!!!! -
Django pagination of filtered post list
I've been working on a project of a blog where all posts are grouped by rubrics. The posts can be filtered by rubric in the frontend but I've got some problems whith implementing pagination. Paginator works fine and paginates filtered list, when I choose a rubric on my site it shows the number of pages and shows link to the next. But the url it forms ignores rubrication and instead of sending me to something like localhost/blog/?rubric=some_rubric&page=2 it shows localhost/blog/?page=2 The pagination works fine if I input adress by hand. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset()\ .filter(status=Post.Status.PUBLISHED) class Rubric(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() class Meta: verbose_name_plural = 'Rubrics' ordering = ('name',) indexes = [models.Index(fields=['name']),] def __str__(self): return self.name class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') cover_img = models.ImageField(upload_to='post_covers/', blank=True, null=True) rubric = models.ForeignKey(Rubric, on_delete=models.CASCADE, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') excerpt = models.TextField(max_length=500) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) objects = models.Manager() # The … -
I am getting error in console "You need to enable JavaScript to run this app."
I am working on a site that has a back-end with django and a front-end with react js, it was running well locally, but when I run the command on the cloud server, I get the error "You need to enable JavaScript to run this app". JavaScript is enabled in the browser, I also tried different browsers. But I get the same error in all browsers. Please someone help me to overcome this error. -
Gptcache and streaming are incompatible
Now, I have made a chatbot which can stream and answer the question from user. However that chatbot can't stream showing no error in terminal after I implemented init_cache() and changed llm. Here are some parts of my code: class CustomStreamingCallbackHandler(BaseCallbackHandler): """Callback Handler that Stream LLM response.""" def __init__(self, queue): self.queue = queue def on_llm_new_token(self, token: str, **kwargs: Any) -> None: """Run on new LLM token. Only available when streaming is enabled.""" self.queue.put(token) def generate_stream(q: Queue, job_done): while (...): try: stream = q.get(True, timeout=1) print(stream) yield stream except: continue def openai_response_generator(queue, retriever, prompt, query, chat_history, job_done): llm = LangChainChat( chat=ChatOpenAI( model_name="gpt-3.5-turbo-16k", streaming=True, temperature=0, callbacks=([CustomStreamingCallbackHandler(queue)]), )) chain = ConversationalRetrievalChain.from_llm( llm=llm, retriever=retriever, condense_question_prompt=prompt, return_source_documents=True, ) res = chain({'question': query, 'chat_history': chat_history}) print(res["answer"]) queue.put(job_done) def get_content_func(data, **_): return data.get("messages")[-1].content def init_cache(): onnx = Onnx() cache_base = CacheBase('sqlite') vector_base = VectorBase('faiss',dimension=onnx.dimension, collection_name='for_cache') data_manager = get_data_manager(cache_base, vector_base) cache.init( pre_embedding_func=get_content_func, embedding_func=onnx.to_embeddings, data_manager=data_manager, similarity_evaluation=SearchDistanceEvaluation(max_distance=1), ) cache.set_openai_key() # save data to cache from getting one answer cache.config.auto_flush = 1 init_cache() task = threading.Thread( target=openai_response_generator, args=(queue, retriever, prompt, query, chat_history, job_done) ) task.start() Before I changed llm, it was: llm = chatOpenAI( model_name="gpt-3.5-turbo-16k", streaming=True, temperature=0, callbacks=([CustomStreamingCallbackHandler(queue)]), ) Could you help me with that? I have already tried to change … -
DJango how to set up api and testing in Insomnia?
What should I add in the urls or views? I want to create an api and test in Insomnia, my app name called jqeshop and i create a table call product, i try to get it and display, after that i want to pass it to frontend, it just a practice for me, i need some one help enter image description here enter image description here enter image description here enter image description here This is the error message -
In Django AuthenticationForm, how to check only email and password is_valid
I tried to do this to remove username validation def clean_username(self): return "valid_username" But the is_valid() method is showing false. Even when i give the correct username and password I also tried this def clean_username(self): return self.cleaned_data.get('username') views.py def login(request): if request.method == 'POST': form = LoginUser(request=request.POST, data=request.POST) if form.is_valid(): print(True) print(form.cleaned_data['username']) print(form.cleaned_data['password']) print(form.is_valid()) else: form = LoginUser() context ={ 'form': form, } return render(request, 'login.html', context) forms.py class LoginUser(AuthenticationForm): username = forms.CharField(max_length=20, required=True, widget=forms.TextInput(attrs={'class': form_class, 'placeholder': 'username', })) password = forms.CharField(min_length=8, required=True, widget=forms.PasswordInput(attrs={'class': form_class, 'placeholder': 'password', })) def clean_username(self): return "valid_username" I think I need to change the is_valid method -
How to use django_autocomplete_light in django admin page?
I have a 2 model in django models class Country(models.Model): country_name = models.CharField(max_length=30, null=False) country_phone_code = models.CharField(max_length=50, primary_key=True, null=False) country_image = models.CharField(max_length=255, blank=True) is_shipping_available = models.BooleanField(null=False) class State(models.Model): id = models.AutoField(primary_key=True) state_name = models.CharField(max_length=30, null=False) country = models.ForeignKey( Country, on_delete=models.CASCADE, related_name="states" ) is_shipping_available = models.BooleanField(null=False) what i was trying to do register the states model in Modeladmin and have an auto field to select from country model since it is related using the foreign key relation ship and i found out that i can do it using the django_autocomplete_light ? help -
Running Django and PHP on same Ubuntu server
I have a dedicated Ubuntu 22.0 server on which I am running PHP apps using Cyberpanel. I want to use Django on the same server. I have 2 sites inside cyberpanel using wordpress. I want my third site to point to the Django app, not the PHP. What should be the approach to configure it? -
DoesNotExist at /buy_now_payment_done/ Payment matching query does not exist
i have implemented an E-commerce website with razorpay payment integration and when i am got to checkout page with cart items, all logic work properly but when i am click on Buy Now button and then redirect it to "buynow_checkout.html" after that i am making a payment and payment is also successfull but after that i am getting an error : DoesNotExist at /buy_now_payment_done/ Payment matching query does not exist. how to resolve this? here is my code: Buy Now button <a href="{% url 'buy_now' %}?prod_id={{ product.id }}" id="" class="btn btn-danger shadow px-5 py-2 ms-4">Buy Now</a> urls.py path('buy_now/', login_required(views.BuyNow.as_view()), name='buy_now'), path("buy_now_payment_done/", views.buynow_payment_done, name='buynow_payment_done'), path('checkout/', login_required(views.checkout.as_view()), name='checkout'), path("payment_done/", views.payment_done, name='payment_done'), view.py import uuid from django.shortcuts import render,redirect,get_object_or_404 from django.views import View from django.contrib import messages from django.http import HttpResponseRedirect, JsonResponse, HttpResponse from django.conf import settings from django.core.mail import send_mail from django.contrib.auth import authenticate,login,logout from django.urls import reverse from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.db.models import Q from .forms import * from .models import * import razorpay class checkout(View): def get(self,request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity * p.product.discounted_price famount = famount+value totalamount = famount + … -
How to stop my footer design to effect the whole page?
I made this footer but when I include it in my base.html it changes the styling of the other parts I think due to its CSS and it makes some icons look strange what should I do?? if I need to post another part of code please let me know Thanks in advance my index.html (footer) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="vieport" content="width=device-width,initial-scale=1.0"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha512-DTOQO9RWCH3ppGqcWaEA1BIZOC6xxalwEsw9c2QQeAIftl+Vegovlnee1c9QX4TctnWMn13TZye+giMm8e2LwA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <title>Document</title> </head> <body> <footer> <div class="footerContainer" > <div class="socialIcons"> <a href=""><i class="fa-brands fa-facebook"></i></a> <a href=""><i class="fa-brands fa-instagram"></i></a> <a href=""><i class="fa-brands fa-telegram"></i></a> <a href="https://github.com/Jasmine-dy"><i class="fa-brands fa-github"></i></a> <a href=""><i class="fa-brands fa-youtube"></i></a> </div> <div class="footerNav"> <ul> <li><a href="">Home</a></li> <li><a href="">Genres</a></li> <li><a href="">Contact Me</a></li> <li><a href="">Your Account</a></li> </ul> </div> </div> <div class="footerBottom"> <p style="margin-top: 10px" >Copyright &copy;2023; Designed by <span class="designer">Jasmine</span> </p> <a href="https://www.freepik.com/free-vector/abstract-background-with-rainbow-coloured-hologram-background_19613969.htm#query=pastel%20holographic%20background&position=2&from_view=keyword&track=ais&uuid=eccfffcb-4044-4b17-8749-40b272baa47e">Image by kjpargeter</a> on <span class="designer"> Freepik</span> <h2></h2> <a target="_blank" href="https://icons8.com/icon/79363/reading-unicorn">Reading Unicorn</a> icon by <a target="_blank" href="https://icons8.com">Icons8</a> </div> </footer> </body> <style> footer{ padding: 0; margin: 0; box-sizing: border-box; } footer{ background-color: transparent; } .footerContainer{ width: 100%; padding: 70px 30px 20px; } .socialIcons{ display: flex; justify-content: center; } .socialIcons a{ text-decoration: none; padding: 10px; background-color: white; margin: 10px; border-radius: 50%; display: flex; } .socialIcons a i{ … -
Cross-domain issues between Vue and Django
I encountered a problem when using CROS to solve cross-domain issues between Vue and Django. In the Django part, I have completed the corresponding settings and can already request Django from the Vue interface at http://localhost:5173. But when I use http://127.0.0.1:5173 to access Vue, a CORS error occurs when requesting Django.As follows: The localhost domain name can be cross-domain normally A cross-domain error occurred in the 127.0.0.1 domain name My Django side has been configured with corsheaders and CORS_ORIGIN_WHITELIST Django settings -
Django: messages.error doesn't work with redirect('/')
I'm so confused in templates main page I have: {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %} <div class="alert alert-danger" role="alert">{{ message }}</div> {% endif %} {% endfor %} but the message is not printed. in views.py I have def my_form(request): if not str(request.POST['name']): messages.error(request,'error message.') return redirect('/') and in myapp urls.py path('', views.index, name='index'), re_path(r'^MyForm/$', views.my_form, name='my_form') and in the general urls.py re_path(r'^', include('myapp.urls'), name='home') what could be the issue, the log file shows nothing -
Hello, how do I correct this django error because I've already done everything?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/concesionario/lista_vehiculos/ Using the URLconf defined in concesionario_proyecto.urls, Django tried these URL patterns, in this order: Lista_vehiculos.html The current path, concesionario/lista_vehiculos/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This error is from Django I tried all the methods and it doesn't work and I hope to create a project using the Django Framework, of an application for a dealer of new vehicles, the project must contain a use and/or configuration of: Django installation. Creation of the Django project. Creation of the application for the dealership. Creation of the required data models Create the required views. Create the base template to apply to two dependent HTML documents. Execution and correct functional demonstration of the created system -
Django usercreation form not creating user after authentication
I am currently learning Django and working on a project to help me learn, I created my custom usercreation form and everything seems to work except when i fill in the form it does not create a new user, when i open the sign up page it seems to see it as a request to create a new user and doesnt create one since the form hast been filled and it isnt valid and even when i do fill it still doesnt seem to think its valid and renders the sign up form again. i put two print statements in the sign up function in views.py one in the if statement and one outside just to know if a user was actually created from the console and every single time it says user not created meaning the form is never valid views.py: def signup(request): form = RegisterForm(request.POST) if request.method == 'POST': if form.is_valid(): print("User is valid") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') form.save() new_user = authenticate(username=username, password=password) if new_user is not None: authlogin(request, new_user) redirect('home/') print("User created") form = RegisterForm() print("User not created") return render(request, 'registration/signup.html', {'form': form}) forms.py: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'id':'RegisterUsername', 'type':"text", … -
Django and Polars strange slow response behavior
I am using Django rest framework with polars for creating reports. When having big response data, about 3,500 records, a response takes about a minute. At first, I thought the polar process was slow, but then I timestamped the beginning and end, and found out the whole process is about 1 sec. class TaskViewSet(SearchViewSet): """Task view set""" queryset = Task.objects.all() serializer_class = TaskSerializer search_vector = SearchVector("id", "name") permission_classes = [D7896DjangoModelPermissions] filter_backends = [ filters.DjangoFilterBackend, ] filter_class = TaskFilter pagination_class = None def list(self, request, *args, **kwargs): start_time = datetime.now() branch = request.GET.get("branch", None) orders = request.query_params.getlist("order", []) events = request.query_params.getlist("event", []) production_orders = request.query_params.getlist("production_order", []) start_date = request.GET.get("date__gte", None) start_date = ( datetime.strptime(start_date, "%Y-%m-%d").date() if start_date else start_date ) end_date = request.GET.get("date__lte", None) end_date = ( datetime.strptime(end_date, "%Y-%m-%d").date() if end_date else end_date ) # Validate branch is present if not branch: raise ValidationError("The 'branch' field is missing.") _, tasks = WorkOrderManager.get_work_orders( branch, start_date, end_date, orders, events, production_orders ) if not tasks.is_empty(): tasks = tasks.filter(pl.col("unused_components_task") == False).drop( ["unused_components_task"] ) tasks = tasks.with_columns( tasks['date'].dt.strftime('%Y-%m-%d'), tasks['supply_date'].dt.strftime('%Y-%m-%d') ) data = tasks.to_dicts() json_data = json.dumps(data) end_time = datetime.now() total_time = end_time - start_time print(total_time) return Response(json_data, content_type='application/json') Total Time printing in the terminal: printing in … -
How can I process Image in Django
In my Django Application, I am using imagekit to process images in my model but any time I try uploading image error says: module 'PIL.Image' has no attribute 'ANTIALIAS'. Initially, I never had issues with it but recently any time I try to save my form, I get that error. I have upgraded Pillow and used ImageFilter.MedianFilter() instead of ANTIALIAS but error persist. Someone should help with the best way of doing this. I am using Django Django==4.0. See my Model code: from django.db import models from PIL import Image from phonenumber_field.modelfields import PhoneNumberField from imagekit.processors import ResizeToFill, Transpose from imagekit.models import ProcessedImageField from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible @deconstructible class FileExtensionValidator: def __init__(self, extensions): self.extensions = extensions def __call__(self, value): extension = value.name.split('.')[-1].lower() if extension not in self.extensions: valid_extensions = ', '.join(self.extensions) raise ValidationError(f"Invalid file extension. Only {valid_extensions} files are allowed.") Allowed Image extensions image_extensions = ['jpeg', 'jpg', 'gif', 'png'] class ResizeToFillWithoutAntialias(ResizeToFill): def process(self, img): img = super().process(img) return img.resize(self.size, Image.LANCZOS) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=True, null=True) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) date_birth = models.DateField(blank=False, null=True) phone_number = models.CharField(max_length=11, blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) marital_status = … -
ModuleNotFoundError: No module named '<django_project_name>' Heroku deployment
I have seen tens of queries on same topic in past 2 days on web but unfortunately nothing has helped in my case. I am trying to deploy on Heroku from windows 10. Python manage.py runserver works the job fine on local PC and projects runs. Here is my project structure austbooks ├── accounting │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ ├── models.py │ ├── static │ │ └── accounting │ │ ├── css │ │ └── js │ ├── templates │ │ ├── account │ │ └── accounting │ ├── tests.py │ ├── views.py │ ├── __init__.py │ └── __pycache__ ├── austbooks │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ ├── wsgi.py │ ├── __init__.py │ └── __pycache__ ├── manage.py ├── Procfile ├── requirements.txt ├── runtime.txt └── staticfiles ├── Accounting │ ├── css │ └── js ├── admin │ ├── css │ ├── img │ └── js ├── debug_toolbar │ ├── css │ └── js └── staticfiles.json I was getting the following error on deployment to heroku -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.12/site-packages/django/core/management/__init__.py", line 255, in fetch_command app_name = commands[subcommand] ~~~~~~~~^^^^^^^^^^^^ KeyError: 'collectstatic' During … -
Django Added ForeignKey object in Custom User Model, when creating users im getting value error
Django Added ForeignKey object in Custom User Model, when creating users im getting value error this is user model(AppUser) having foreignkey in it, the error is as folllowed, ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. tried with just instance also user = User.objects.create_user(email='admin@fmlk.com',branch=Branches.objects.get(name="Temp_Branch")) class AppUser(AbstractUser): username = None secId = models.CharField(max_length=255,default=sec.token_urlsafe(16)) email = models.EmailField(unique = True, null=False) password = models.CharField(max_length=255) branch = models.ForeignKey(Branches,on_delete=models.SET(tempBranch),null=False) is_verified = models.BooleanField(default = False) USERNAME_FIELD = "email" ` REQUIRED_FIELDS = ['branch'] objects = UserManager() class UserManager(BaseUserManager): def create_user(self, email, branch, password = None,**extra_fields): if not email: raise ValueError("Email is required") if not branch: raise ValueError("Need Branch") email = self.normalize_email(email.lower()) user = self.model(email = email, branch= branch, **extra_fields) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, email,branch, password = None, **extra_fields): extra_fields.setdefault("is_staff",True) extra_fields.setdefault("is_superuser",True) extra_fields.setdefault("is_active",True) return self.create_user(email,branch,password, **extra_fields) >>> user = User.objects.create_user(email='admin@fmlk.com',branch=Branches.objects.get(name="Temp_Branch").id) Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/Varun/Spaces/spaces/core/manager.py", line 9, in create_user email = self.normalize_email(email.lower()) File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/base.py", line 543, in __init__ _setattr(self, field.name, rel_obj) File "/Users/Varun/Spaces/env/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 283, in __set__ raise ValueError( ValueError: Cannot assign "1": "AppUser.branch" must be a "Branches" instance. -
nginx unit + django + docker - wsgi.py cannot import module
Currently containerizing a legacy Django project, and running into an odd error. When pushing the config file to the running server, it fails to apply, and on inspecting the log, I get the following: 2023/12/06 21:36:02 [info] 39#39 discovery started 2023/12/06 21:36:02 [notice] 39#39 module: python 3.11.2 "/usr/lib/unit/modules/python3.11.unit.so" 2023/12/06 21:36:02 [info] 1#1 controller started 2023/12/06 21:36:02 [notice] 1#1 process 39 exited with code 0 2023/12/06 21:36:02 [info] 41#41 router started 2023/12/06 21:36:02 [info] 41#41 OpenSSL 3.0.11 19 Sep 2023, 300000b0 2023/12/06 21:40:22 [info] 49#49 "myapp" prototype started 2023/12/06 21:40:22 [info] 50#50 "myapp" application started 2023/12/06 21:40:22 [alert] 50#50 Python failed to import module "myapp.wsgi" Traceback (most recent call last): File "/app/myapp/wsgi.py", line 5, in <module> from django.core.wsgi import get_wsgi_application # noqa: E402 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ModuleNotFoundError: No module named 'django' 2023/12/06 21:40:22 [notice] 49#49 app process 50 exited with code 1 2023/12/06 21:40:22 [warn] 41#41 failed to start application "myapp" 2023/12/06 21:40:22 [alert] 41#41 failed to apply new conf 2023/12/06 21:40:22 [notice] 1#1 process 49 exited with code 0 My config file is as follows: { "applications": { "myapp": { "type": "python 3.11", "module": "myapp.wsgi", "processes": 150, "environment": { "DJANGO_SETTINGS_MODULE": "myapp.settings.production", } } }, "listeners": { "0.0.0.0:8000": { "pass": "applications/myapp" } } … -
Django php bridge
I have configured my app like this: client -> server(Apache -> php -> [django]) Some requests are handled by the php, and some are "forwarded" to django. I can successfully access the django app via this php proxy. But when I try to upload a file to the server (here django should handle that request), is there any way to directly forward the file content to the django app or I need to temporarily save it in the php server and make a request to the django app for the rest? -
Bootstrap Modal - Deleting a Review using Django
I'm using a simple Boostrap modal and it works fine. I have a delete URL which will delete the review based on the id. My issue is, I don't know how to pass the review.id from the button, through to the modal confirm delete button. If I don't use a modal and just do a simple delete button, it works fine using: How do I pass that review.id through to the final button? {% url 'delete_review' review.id %} HTML: {% if request.user.is_authenticated and user.username == review.name or user.is_superuser %} <div> <a class="btn btn-black rounded-0 text-uppercase mt-2" href="{% url 'edit_review' review.id %}" role="button">Edit</a> | <!-- Button trigger modal --> <a class="btn-delete btn rounded-0 text-uppercase btn-outline-danger mt-2" data-toggle="modal" data-target="#exampleModal" role="button">Delete</a> </div> {% endif %} <hr> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Review</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to <strong class="text-danger">DELETE</strong> your Review? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" href="{% url 'delete_review' review.id %}">Delete Review</button> </div> </div> </div> </div> -
Django-pipeline collect my statics in dev
I use Django-pipeline on my project. Here are the configurations: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = os.path.join(BASE_DIR, 'zstatics') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'pipeline.storage.PipelineManifestStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', ) PIPELINE = { 'PIPELINE_COLLECTOR_ENABLED': False, 'PIPELINE_ENABLED': False, 'CSS_COMPRESSOR': None, 'JS_COMPRESSOR': None, 'JAVASCRIPT': { 'unauthenticated_main': { 'source_filenames': ( 'website/js/theme.bundle.min.js', 'js/htmx.min.js', 'website/vendors/js/prism.min.js', 'js/copyleft.min.js', 'js/unauthenticated_custom.min.js', 'js/oqb.min.js', ), 'output_filename': 'compressed/unauthmain.min.js', } } } It works quite well but in developpement mode with DEBUG=False it collects my files anyway, and minify them in doucble and I got new files in zstatics, the files declared in the dictionnary. for example I got a 'js/htmx.min.js' file and a 'js/htmx.min..min.js' file which is quite weird. Any idea where I failed in the configuration? -
Connecting to Amazon SQS key (SSE-SQS) Encrypted SQS Queue via Django Celery [sqs]
I am unable to get my Celery working running while connecting to an SQS Encrypted Queue This is my settings.py for my django project SQS_AWS_ACCESS_KEY_ID = 'xxxx' SQS_AWS_SECRET_ACCESS_KEY = 'xxxx' SQS_AWS_QUEUE_NAME = 'sqs.eu-west-2.amazonaws.com/xxxx/xxx-celery-broker' broker_url = f"sqs://{SQS_AWS_ACCESS_KEY_ID}:{SQS_AWS_SECRET_ACCESS_KEY}@{SQS_AWS_QUEUE_NAME}" CELERY_BROKER_URL = broker_url CELERY_RESULT_BACKEND = None CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True When i run my worker i get this error, i assume as my Queue Name is not https:// botocore.exceptions.ClientError: An error occurred (InvalidSecurity) when calling the GetQueueAttributes operation: All requests to this queue must use HTTPS and SigV4. when i change it to SQS_AWS_QUEUE_NAME = 'https://sqs.eu-west-2.amazonaws.com/xxxx/xxx-celery-broker' I get this error Cannot connect to sqs://xxx:**@https//sqs.eu-west-2.amazonaws.com/xxx/xxx-celery-broker: Could not connect to the endpoint URL: "http://https/". The Config seems to add a random http onto the url which is why i assume its failing When i connect to a non encrypted queue it works fine as seen as This is my celery.py config os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") # Create a Celery instance and configure it to use SQS app = Celery("proj") # Load task modules from all registered Django app configs. app.config_from_object("django.conf:settings", namespace="CELERY") # Auto-discover tasks in all installed apps app.autodiscover_tasks(settings.INSTALLED_APPS) app.conf.task_default_queue = 'xxx-celery-broker' I'm at my wits end trying to fix this im assuming there is a small config change …