Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
''TypeError at /user expected string or bytes-like object'' on submitting the for in django?
When I submitting the form in django it is giving error ''TypeError at /user expected string or bytes-like object''. This is my staff models class staff(models.Model): id = models.AutoField name = models.CharField(max_length=250) role = models.CharField(max_length=250) salary = models.CharField(max_length=250) address = models.CharField(max_length=250) number = models.CharField(max_length=250) date = models.DateField() This is my user views. def user(request): if request.method == "POST" : name = request.POST['name'] role = request.POST['role'] salary = request.POST['salary'] address = request.POST['address'] number = request.POST['number'] date = DateTimeField() ins = staff(name=name, role=role, salary=salary, address=address, date=date, number=number) ins.save() staffs = staff.objects.all() return render(request, "salary/user.html", {'staff': staffs}) and this is form of template user.html <form class="forms-sample" action="/user" method="post"> {% csrf_token %} <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Name:</label> <div class="col-sm-9"> <input type="text" name="name" id="name" class="form-control" id="exampleInputUsername2" placeholder="Username"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Role:</label> <div class="col-sm-9"> <input type="text" name="role" id="role" class="form-control" id="exampleInputUsername2" placeholder="Role"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Salary:</label> <div class="col-sm-9"> <input type="text" name="salary" id="salary" class="form-control" id="exampleInputUsername2" placeholder="Salary"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Address:</label> <div class="col-sm-9"> <input type="text" name="address" id="address" class="form-control" id="exampleInputUsername2" placeholder="Address"> </div> </div> <div class="form-group row"> <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Mobile no.:</label> <div class="col-sm-9"> <input type="text" name="number" id="number" class="form-control" id="exampleInputUsername2" placeholder="Mobile no."> </div> </div> … -
How to structure django + react project for deployment?
I'm building a django + django-rest-framework project with react as frontend. I've look around for the best way to structure and deploy it and it seems there are several aproaches. One is to build the react frontend as static files and have django serve them, another one is to have 2 diffeernt servers and let both projects comunicate over http. Which is the better option? What are the pros and cons of each aproach? It seems the latter one would be more expensive since we have to pay for both servers. Notes: The project is realatively small but can end up evolving into a larger one. We are using a MySQL database We want the option to use the django admin webpage -
Django ajax return a html page
i am trying to decrypt encrypted text and return the plain text through ajax call, instead of getting the message response i get an html page back as response. i have tried returning the response as json but still getting the same html response. ''' function loadMessage() { fetch("{% url 'chat:history' chatgroup.id %}") .then( response => response.json() ) .then( data => { for (let msg of data) { var message=msg.message; $.ajax({ type: 'GET', url: '', data: { message: message}, success: function(response){ broadcastMessage(response.message, msg.username, msg.date_created) } }) } }) } ''' view.py ''' def get(request): message = request.GET.get('message') key = b'\xa8|Bc\xf8\xba\xac\xca\xdc/5U0\xe3\xd6f' cipher = AES.new(key, AES.MODE_CTR) nounce = b64encode(cipher.nonce).decode('utf-8') if request.is_ajax(): nounce_ = self.nounce msg_ = self.message key = self.key nounce = b64decode(nounce_) ct = b64decode(msg_) cipher = AES.new(key, AES.MODE_CTR, nounce=nounce) msg_ = cipher.decrypt(ct) mwssage = msg_.decode() return JsonResponse({'message': message}) return render(request, 'chat/room.html') ''' -
How to display two separate lists of two different models declared in ListView in one HTML template in Django?
I have coded a ListView for search engine. I wanted to extract data from fields of two different models. First, I declared separate lists for each model. Then I combined them into one list as shown below. view.py class SearchView(ListView): template_name = 'articles/search_view.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Article.objects.filter(Q(title__icontains=query) | Q(description__icontains=query)| Q(body__icontains=query) | Q(stocks_etfs_or_bonds__ticker__icontains=query) | Q(stocks_etfs_or_bonds__description__icontains=query) | Q(stocks_etfs_or_bonds__name__icontains=query) | Q(tags__name__icontains=query)) securities_list = StockETFBond.objects.filter(Q(name__icontains=query)) search_result = list(chain(object_list, securities_list)) return search_result In this case, the template will display one list of two models. search_view.html template now {% for object in object_list %} {{ object }} {% endfor %} But I would like to be able to display two separate lists of two different models in the template as shown below. search_view.html {% for object in object_list %} {{ object }} {% endfor %} {% for object in securities_list %} {{ object }} {% endfor %} How can I do it? -
How to accommodate simple serializer into Model Serializer Or combine 2 separate apps (Model Serializer) in Django rest API View
I am using Django and Django rest framework (latest version) for my Department - Employee rest API. Created 2 apps in my project DepartmentApp - which has Model : Department (Id, Department name , Location) , Department --> ModelSerializer and finally DepartmentApi using Class API (views.py) EmployeeApp - which has Model : Employee (Id, Employee name , Job title, Salary , Department ID) , Employee --> ModelSerializer and finally EmployeeApi using Class API (views.py) Now under EmployeeApp --> views.py , I am calling DepartmentApi under def get method .The purpose it to get department name and location for a give employee object.departmentID and use those attributes as part of employeeSerializer response.. I am not sure how to achieve this. below code snippet from views.py from EmpployeeApp def get(self, request, EmployeeId = None): if EmployeeId: employee=Employees.objects.get(EmployeeId=EmployeeId) print (employee.Department) # This prints DepartmentID from employee Model e_response = requests.get('http://127.0.0.1:8000/department/1') # calling DepartmentAPI deptData = e_response.json() print (f"{deptData['DepartmentName']} and {deptData['Location']}") employees_serializer = EmployeeDeptSerializer(employee) return Response(employees_serializer.data) Above code will only contain Employee object . But my ask is to add Department name and Location in my Response while calling EmployeeApi(for a given Employee ID or for all objects). Please help me out as I … -
ModuleNotFoundError at /auth/users/me/ No module named 'accounts'
I am using djoser and django-rest-framework JWT for user authentication . According to doc.for djaoser . I have /user/ end point for creating a user and /user/me/ for getting details. The first endponts works fine but in the second /user/me/ , it give me the error ModuleNotFoundError at /auth/users/me/ No module named 'accounts' I don't know where the problem lies. I am testing it on postman. here is my settings.py: """ Django settings for backend project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from django.conf import settings from datetime import timedelta from pathlib import Path # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-jyhhr)v0kyrb+^ifdlio=p3mo&l=$(^an7xb&fow--z^rxd7^r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'djoser', 'base.apps.BaseConfig', 'corsheaders', 'social_django' ] MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
I was created method in Django media Folder to add watermark to images , but when i import the method to views .py it shows
in myApp->views.py from ..media.main import addwatermark ImportError: attempted relative import beyond top-level package -
Django Rest Framework Custom error format
Hi I have the following dict to be serialised { "field_name":"myrole", "description":"it has access", "status":"active", "role":"admin", "modules":[ { "module_id":"newid", "create":true, "read":true, "update":true, "delete":true } ] } Serializer I'm having now is class ModulerSerializer(serializers.Serializer): module_id = serializers.BooleanField(required=True, allow_null=True) delete = serializers.BooleanField(required=True) read = serializers.IntegerField(required=True) create = serializers.BooleanField(required=True) update = serializers.BooleanField(required=True) class RoleValidateSerializer(serializers.Serializer): field_name = serializers.BooleanField(required=True) description = serializers.CharField(required=True, max_length=128) role = serializers.CharField(required=True, max_length=128) status = serializers.CharField(required=True, max_length=128) modules = serializers.ListField(child=ModulerSerializer()) it is producing the error message like below {'field_name': [ErrorDetail(string='Must be a valid boolean.', code='invalid')], 'modules': { 0: {'module_id': [ErrorDetail(string='Must be a valid boolean.', code='invalid')], 'read': [ErrorDetail(string='A valid integer is required.', code='invalid')]}}} What I'm expecting is to append all error message values in to a single array like below or extracting error message from all nested child object [field_name Must be a valid boolean,module_id Must be a valid boolean, read A valid integer is required. ] -
Django doesn't show ValidationError in my web-site
guys, I am beginner at Django. I watch lessons on youtube and get different results. I use Django==2.0.7 and Python==3.6.5. I try to get error on my page, if I write not correct name of title, but I don't get it. Look at func - **def clean_title(self, *args, kwargs), I hope, you understand, what I mean. There I have "raise forms.ValidationError("Error")", but it doesn't work anymore. forms.py from django import forms from .models import Product class ProductForm(forms.ModelForm): title = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder": "title"})) Description = forms.CharField( required=False, widget=forms.Textarea( attrs={ "placeholder": "Your description", "class": "new-class-name two", "id": "new-class-name two", "rows": 20, 'cols':120 } ) ) Price = forms.DecimalField(initial=199.99) class Meta: model = Product fields = [ 'title', 'Description', 'Price' ] def clean_title(self, *args, **kwargs): title = self.cleaned_data.get('title') if "Ruslan" in title: return title else: raise forms.ValidationError("Error") In forms.py I created class ProductForm and declared the fields. In my page I see it. Also I defined clean_title. I wanted to get error if I filled in wrong name of title. views.py from django.shortcuts import render from .models import Product from .forms import ProductForm as CreateForm, PureDjangoForm def create_form(request): form = CreateForm(request.POST or None) if form.is_valid(): form.save() form = CreateForm() context = { 'form': … -
Django S3bucket uploaded images visible only when i upload but after certain time it is not visible
When i upload an image with django admin, i can see the image for a few minutes, but after few minutes, i cant see the image anymore, it show me error But i can that image another way and when i remove the url parameter of image, the the image always visable. Like when image urls look like this https://example.s3.amazonaws.com/media/images/2021/08/27/0A96395C-EB5B-4DC4-B0F7-43C322A4E6CC.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA4KGTUZ6KPWNI3KGE%2F20210828%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210828T164251Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=805bee29302409a99d27fe26c237b664f5b92a5cd9d4341cc1c990d5ba64 It works only for few minutes, then it fires me error <Message>Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'us-east-2'</Message> and when i remove the parameter and make it look like this. https://example.s3.amazonaws.com/media/images/2021/08/27/0A96395C-EB5B-4DC4-B0F7-43C322A4E6CC.jpg It works very well, what is the reaons? This is my django settings AWS_S3_CUSTOM_DOMAIN = ' AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_DEFAULT_ACL = os.getenv("AWS_DEFAULT_ACL", "public-read") AWS_AUTO_CREATE_BUCKET = os.getenv("AWS_AUTO_CREATE_BUCKET", True) AWS_S3_SIGNATURE_VERSION = 's3v4' Can anyone tell me what is the issue? -
Sending a List with Dictionary type data
I am working on a quiz app. I have Quiz, Question, Answer models. I save the Quizzes made in the 'TakingQuiz' model, and the answers are in the 'TakingQuizAnswer' model. While talking to my friend, he mentioned that what I have to do is as follows: "When we send an Update request to the TakingQuiz API from Frontend, you need to send responses like answers : [{answer1object}, {answer2object}] and register them on the Backend." How can I get and save data like this in the Serializer of the TakingQuiz model? I have no idea how to send data as a list in the request. Related models class Quiz(AbstractQuizBaseModel): ENABLED_CHOICES = ( (True, _("Active")), (False, _("Not Active")), ) book = models.ForeignKey("book.Book", on_delete= models.CASCADE, related_name="book_quiz") title = models.CharField(max_length=150) enabled = models.BooleanField(choices=ENABLED_CHOICES, default=False) class Question(AbstractQuizBaseModel): quiz = models.ForeignKey("quiz.Quiz", on_delete=models.DO_NOTHING, related_name="question_quiz") question = models.CharField(max_length=500) topic = models.CharField(max_length=500) class Answer(AbstractQuizBaseModel): IS_CORRECT_CHOICES = ( (True, _("Correct")), (False, _("Wrong")) ) question = models.ForeignKey("quiz.Question", on_delete=models.CASCADE, related_name = "question_answer") answer = models.CharField(max_length=500) is_correct = models.BooleanField(choices=IS_CORRECT_CHOICES, default=False) class TakingQuiz(AbstractQuizBaseModel): quiz = models.ForeignKey("quiz.Quiz", on_delete=models.DO_NOTHING, related_name="quiz_taking_quiz") child = models.ForeignKey("account.ChildProfile", on_delete=models.CASCADE, related_name = "child_taking_quiz") title = models.CharField(max_length=150, editable=False, default="-") total_point = models.PositiveIntegerField(default=0, editable=False) class TakingQuizAnswer(AbstractQuizBaseModel): taking_quiz = models.ForeignKey("quiz.TakingQuiz", on_delete=models.CASCADE, related_name="taking_quizes") question = models.ForeignKey("quiz.Question", … -
Can I host Django Web Application which uses Wand API in its code?
I have made small project which uses Wand API in its code for some parts of project. Wand uses Imagemagick , those it needs to be installed in Computer. I have already installed it . Now, I want to Host my Web Application. is it possible to host this type of Web Application ?if Yes, then how ? If you Answer this it will help me a lot . Thankyou. -
why my django-simple captcha form is not showin up django
I am tryin to use captcha form to authenticate a real person but my form is not showing in template this is my views.py def codhandler(request): if request.method == "POST": form = CaptchaForm(request.POST) if form.is_valid(): form.save() return redirect('orders:successcod') else: form = CaptchaForm() return render(request, 'cashondeliversummary.html', {'form': form}) my html <form action="{% url 'orders:codhandler' %}" method='POST'> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-outline-primary" style="border:2px solid #025;">Place Order</button> <button class='js-captcha-refresh'></button> </form> i did install django-simple-captcha in my virtualenv my forms from django import forms from captcha.fields import CaptchaField class CaptchaForm(forms.Form): captcha = CaptchaField() any idea what i am doing wrong here -
django static files when hosting in heroku
I have excel files in my static folder that I read from to get some data but the files arent there when I deploy my project these are my settings for configuring static files STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ BASE_DIR / 'static' ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' this is how I call them in my views from django.conf import settings from django.templatetags.static import static from django.contrib.staticfiles.storage import staticfiles_storage from django.contrib.staticfiles.finders import find def get_static(path): if settings.DEBUG: return find(path) else: return static(path) def sport_news(request): path = 'excel\sport_update.xlsx' excel_data = excel(get_static(path)) return render(request, 'news/news.html', {"excel_data":excel_data, 'type':'Sport News'}) -
Upgrading django from 3.0.4 to 3.2.6 results in missing content_type objects while testing
I'm trying to migrate a project from Django 3.0.4 to 3.2.6. I'm running into the following issue while running my testsuite django.db.utils.IntegrityError: insert or update on table "auth_permission" violates foreign key constraint "auth_permission_content_type_id_2f476e4b_fk_django_co" DETAIL: Key (content_type_id)=(1) is not present in table "django_content_type". self = <QuerySet []>, defaults = {'name': 'Can export log entry (adminactions)'} kwargs = {'codename': 'adminactions_export_logentry', 'content_type': <ContentType: admin | log entry>} params = {'codename': 'adminactions_export_logentry', 'content_type': <ContentType: admin | log entry>, 'name': 'Can export log entry (adminactions)'} def get_or_create(self, defaults=None, **kwargs): """ Look up an object with the given kwargs, creating one if necessary. Return a tuple of (object, created), where created is a boolean specifying whether an object was created. """ # The get() needs to be targeted at the write database in order # to avoid potential transaction consistency problems. self._for_write = True try: > return self.get(**kwargs), False /usr/local/lib/python3.9/site-packages/django/db/models/query.py:581: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <QuerySet []>, args = () kwargs = {'codename': 'adminactions_export_logentry', 'content_type': <ContentType: admin | log … -
debug setting is ignored when I move my django project to docker compose
we have a Django application. Right now we run it using Ubuntu 18.04 on Vagrant. Everything works fine. Now we have decided to move to docker compose. We have set everything and all is great and running. The only problem is that we have a very weird bug with the debug value. So, we have DEBUG=True in our settings file. We pass that value to the configuration template to use come includes in html. To do that, we have the following settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. os.path.join(PROJECT_DIR, 'templates'), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ # List of callables that know how to import templates from various sources. 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.request', 'leads.context_processors.leads', ] } }, ] As you can see, we declare the option debug with the value of DEBUG. I have set a breakpoint on both environments there, I can see DEBUG=True. Now comes the fun part, if I set a breakpoint on a django template, for instance, this one: {% if not debug %} <link rel="stylesheet" href="somlink" /> {% … -
Django. CSRF token missing or incorrect
I have just recently started learning Django. I have a problem with the password change page 403 Reason given for failure: CSRF token missing or incorrect. My users/urls.py urlpatterns = [ path( 'logout/', LogoutView.as_view(template_name='users/logged_out.html'), name='logout' ), path( 'login/', LoginView.as_view(template_name='users/login.html'), name='login' ), path( 'password_change/', PasswordChangeView.as_view(template_name='users/password_change_form.html'), name='password_change_form' ), path( 'password_change/done/', PasswordChangeDoneView.as_view(template_name='users/password_change_done.html'), name='password_change_done' ), ..., ] And My Form in Template starts <form method="post" {% if action_url %} action="{% url action_url %}" {% endif %} > {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken" value=""> With this form, I get the error 403 and "CSRF token missing or incorrect." Without this string everythink works <input type="hidden" name="csrfmiddlewaretoken" value=""> everythink works. 1)Could you please explain me why? And what is it? What is the best way to use csrf? 2) I also used to write like <form method="post" action="{% url 'users:password_change_form' %}"> But founded this example using action_url. What is action_url? What way is better? -
How do you do logic on Post request sent from react in django?
When making a website (django and react) with its own currency. How can one use the data from the post method from react to do some logic on it and then return back the user info? Example: User has 20 coins, tries to buy something for 15 coins If user has more than 15 coins: User coins = User coins - 15 Return user info Else: Return "user does not have sufficient funds" -
after add postgresql get programming error in django
I'm creating a blog app with django and also it works fine with django default database called dbsqllite so. I decided to add postgresql database for my blog application after adding postgresql database it gives me a error like this django.db.utils.ProgrammingError: relation "blog_category" does not exist LINE 1: ...log_category"."name", "blog_category"."name" FROM "blog_cate.. . by the way I have already tired so many things like python manage.py makemigrations python manage.py migrate python manage.py migrate --run-syncdb python manage.py migrate --fake python manage.py migrate {app name} zero but any of this can't solve. I coudn't find any answer for this anyway here is model if you need for any reference. models.py of category model from django.db import models from django.contrib.auth.models import User from django_summernote.fields import SummernoteTextField from django.urls import reverse from django.template.defaultfilters import slugify STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) category = models.CharField(max_length=50, default='uncatagories') class Meta: ordering = ['-created_on'] # this is used to order blog posts using time def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) … -
Django adds an extra "/" in the url?
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/1// Using the URLconf defined in products.urls, Django tried these URL patterns, in this order: [name='home'] contact/ admin/ products/ [name='product-list'] products/ products/ <int:id>/ [name='product-detail'] products/ <int:id>/delete/ [name='product-delete'] products/ about/ The current path, products/1//, didn’t match any of these Why does it require an extra slash after the id? The more I deal with it, the more slashes it wants. I have urls.py like this: from django.urls import path from .views import ( product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view, product_delete_view, product_list_view) app_name = 'product' urlpatterns = [ path('', product_list_view, name='product-list'), path('', product_create_view), path('<int:id>/', dynamic_lookup_view, name='product-detail'), path('<int:id>/delete/', product_delete_view, name='product-delete'), path('', product_detail_view), ] Also another urls.py with something like this: urlpatterns = [ path('', home_view, name='home'), path('contact/', contact_view), path('admin/', admin.site.urls), path('products/', include('product.urls')), path('about/', about_view), ] Here's the function: def dynamic_lookup_view(request, id): #obj = Product.objects.get(id=id) #obj = get_object_or_404(Product, id=id) try: obj = Product.objects.get(id=id) except Product.DoesNotExist: raise Http404 context = { 'object': obj } return render(request, "products/product_detail.html", context) So it raises the exception because it was looking for the additional "/", but where did it come from? -
S3 Bucket Configuration Problem, <Code>AccessDenied</Code>
I'm Unable to set up S3 Bucket Correctly. I followed the following steps to configure. Installed boto3 django-storages Created S3 Bucket with IAM User, And Block all public access is off Settings.py has the following related code. INSTALLED_APPS = [ #... 'storages', ] AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR / 'static'), os.path.join(BASE_DIR / 'build/static') ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) MEDIA_URL = 'https://%s/%s/images/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Now the problem is When I go to the URL of the Uploaded file which is MEDIA_URL = 'https://%s/%s/images/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) I'm getting this error on accessing the Image file https://remote-hospital-v4.s3.us-east-2.amazonaws.com/static/images/IMG_18.jpg And also files are still getting stored locally and are not getting uploaded to S3 Bucket Help required to fix this, Or where the problem could be.Thanks! -
Handling dynamic IP in Django ALLOWED_HOSTS with nginx
I'm having issues with what i believe is my nginx.conf which is causing the instance to be restarted again and again, as the health-checks fail on my managed container service. I'm running my setup in AWS Lightsail Containers, where I have three containers running: nginx django nextjs When publishing a new release on my AWS Lightsail instance it runs fine for a few minutes, then I hit a 503 error, which causes the instance to reboot - run a few minutes then reboot again. Looking at the logs I can see that the health-check failed, and django throws and error saying that I should add the request IP to the allowed hosts: [28/Aug/2021:13:56:23] Invalid HTTP_HOST header: 'x.x.x.x'. You may need to add 'x.x.x.x' to ALLOWED_HOSTS. [28/Aug/2021:13:56:23] Bad Request: /health.txt The problem is that my lightsail container service does not have a static IP (nor do I believe I can get a static IP). My current nginx.conf is below (feedback is appreciated). My question here is how should I deal with this issue? I feel like setting ALLOWED_HOSTS = ['*'] is not a great approach. Can I hardcode the host for the healthcheck or similar? nginx.conf: upstream backend { server ${BACKEND_HOST}:${BACKEND_PORT}; … -
Why data from table is not recieving in djagno?
When i tried to retrieve data from table it is not showing any thing without giving error message. This is my model class staff(models.Model): id = models.AutoField name = models.CharField(max_length=250) role = models.CharField(max_length=250) salary = models.CharField(max_length=250) address = models.CharField(max_length=250) number = models.CharField(max_length=250) date = models.DateField() This is my views file def user(request): staffs = staff.objects.all() params = {'staff': staffs} return render(request, "salary/user.html", params) and this is my template <td> 02312 </td> {% for staff in staffs %} <td>{{ staff.name }} </td> {% endfor %} <td> $14,500 </td> -
Simplifying Django Query Annotation
I've 3 models and a function is called many times, but it generates 200-300 sql queries, and I'd like to reduce this number. I've the following layout: class Info(models.Model): user = models.ForeignKey(User) ... class Forum(models.Model): info = models.ForeignKey(Info) datum = models.DateTimeField() ... class InfoViewed(models.Model): user = models.ForeignKey(User) infokom = models.ForeignKey(Info) last_seen = models.DateTimeField() ... . I need to get all the number of new Forum messages, so only a number. At the moment it works so that I iterate over all the related Infokoms and I summerize all Forums having higher datum than the related InfoViewed's last_seen field. This works, however results ~200 queries for 100 Infos. Is there any possibility to fetch the same number within a few queries? I tried to play with annonate and django.db.models.Count, but I failed. Thanks. -
Django query return array data
I want to query some values from my Postgresql database in Django and want to show in my table. but problem is I am getting some array data like ['Dish', 'LNB Inverto']. I want to show values in my table like Dish| 1000 | 5 |5000 ------------------------- LNB | 500 | 10 |5000 ------------------------- my views: def purchaseDetails(request,pk): invo_data = PurchaseInvoice.objects.all().filter(invoice=pk) return render(request,'purchase/invoice_details.html',{'invoice':invo_data}) my html: {% for data in invoice %} <tr><td> {{data.product_name}} </td><td> {{data.price}} </td><td> {{data.quantity}} </td></tr> {% endfor %} I am getting like ['Dish', 'LNB Inverto'] ['810.00', '214.00'] ['8', '8']