Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sentry Python stack trace showing built-in rows from logging
When I use Sentry with LoggingIntegration to capture logging events (log.error etc.) am I supposed to see the Python logging built-in lines in the stack trace (for example the highlighted line 894 in __init__.py as seen in the attached image)? Or is this due to some misconfiguration? Is it possible to the show only the lines starting from where log.warning is used (in this case, xxx/apiclient.py line 52)? For me, the built-in stack trace is just noise. -
Select particular Foreign key from one django model choice session to another model
I am trying to do a django practice and while doing I tried to add a foreign key to one model to another model. I have a model called "Employee_detail" and it have a session called "Position". Position is a choice field and the choices are 'Manager', 'Supervisor' and 'Employee'. I have another model called "Department" and I used OneToOneField to get the Employee details(Manager) in this model. I wanted to add the department manager(only) to "Dept_Manager" field. class Department(models.Model): Dept_No = models.CharField(primary_key=True, max_length=6) Dept_Name = models.CharField(unique=True, max_length=20) Dept_Manager = models.OneToOneField('Employee_Detail', models.DO_NOTHING) def __str__(self): return self.Dept_No class Employee_Detail(models.Model): Employee_ID = models.CharField(primary_key=True, max_length=6) Employee_Name = models.CharField(unique=True, max_length=30) Primary_Phone = models.IntegerField(unique=True, max_length=10) p = ( ("Manager","Manager"),("Supervisor","Supervisor"),("Employee","Employee") ) Position = models.CharField(max_length=15, choices= p, default="Employee") Email = models.EmailField(max_length=50, unique=True) def __str__(self): return str(self.Employee_Name) But when I try to do it like this (please check the image blow) in the "Dept_Manager" it is showing and allowing to add "Supervisor" or "Employee" in that field. I want it to show only the Managers name as options. Can anyone tell me how to implement that please? -
s3boto and presigned s3 urls
I'm using django-storages and s3boto. I'm able to generate presigned urls that expire after x seconds. This functions as desired and the url no longer works after x seconds. The url looks like this. https://mybucket.s3.us-east-2.amazonaws.com/media/Users/sale-20200727053948.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQVNWS6JIFDS34635fasdFS%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20200727T061840Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=e26a5521268623513182e170fda433kj3lfklejfaslkjdsf Now, I've found that I'm able to remove the content after the '?' in the string to get the following url, and it never expires. https://mybucket.s3.us-east-2.amazonaws.com/media/Users/sale-20200727053948.jpg What setting do I need to ensure that the image is not accessible without the perameters that are on the presigned URL? Thanks! -
Can aws lambda be used as REST API endpoint?
My usecase is: I need to call an API_1 with query param: time import requests result = requests.get("https://api.sample.com/?time=6000") and this API_1 internally calls different API_2 after query param time seconds. I need to implement API_1. So right now i have used a celery task in my django service for the purpose. I just call the celery task (which calls API_2) after time seconds. Can I implement the same functionality using AWS lambda instead of celery? Is it possible to expose some lambda function as an API ? -
NameError: name '_mysql' is not defined after setting change to mysql
I have a running Django blog with sqlite3 db at my local machine. What I want is to convert db to sqlite3 change Django settings.py file to serve MySQL db Before I ran into the first step, I jumped into the second first. I followed this web page (on MacOS). I created databases called djangolocaldb on root user and have those infos in /etc/mysql/my.cnf like this: # /etc/mysql/my.cnf [client] database=djangolocaldb user=root password=ROOTPASSWORD default-character-set=utf8 Of course I created db, but not table within it. mysql> show databases; +--------------------+ | Database | +--------------------+ | djangolocaldb | | employees | | information_schema | | mydatabase | | mysql | | performance_schema | | sys | +--------------------+ 7 rows in set (0.00 sec) I changed settings.py like this as the web page suggested. Here's how: # settings.py ... # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'OPTIONS' : { 'read_default_file': '/etc/mysql/my.cnf', } } } ... Now, when I run python manage.py runserver with my venv activated, I got a brutal traceback like this(I ran python manage.py migrate first, and the traceback looked almost the same anyway): (.venv) ➜ django-local-blog git:(master) ✗ python manage.py runserver Watching for file changes … -
Configuring backup nginx server
Currently I am using (Django + Gunicorn + nginx) over Ubuntu to host my application from my server PC. I am very new to nginx and webservers. So pardon if some questions are very basic. I want to configure a backup server machine which does not work as load balancer but just a backup server if the primary server fails. I came across the upstream module of the nginx to cater the application. Will it be applicable for my problem statement? Lets say IP addresses of primary and backup server are xxx.xxx.xxx.1 and xxx.xxx.xxx.2 Following is my nginx configuration file under /etc/nginx/sites-available: server { listen 80; server_name xxx.xxx.xxx.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root "static folder path"; } location /media/ { root "media folder path"; } location / { include proxy_params; proxy_pass http://unix:"websocket file path"; } } The above configuration file works successfully on the primary server. Can I use upstream module in this setup or do I need to perform any other operation. Will following configuration work for the same? [I am not able to test by myself right away as servers are inaccessible for me for now] upstream **backend** { server … -
Why am I getting error when i am importing the app called as users in Django. I already made changes in the installed apps file
[![` I created two apps. the first one works fine. The same way I created another app called as users. But when I import it, it says unreferenced error. I already added it in installed apps in the main settings.py file of the project `]1]1 There are two apps. The first one is working fine. The second one is giving error when I import it. It says unreferenced error -
Block API on the basis of payload size
My use case is to block API when payload size exceeds more than 5mb, how can I do that? APIs are written in python (Django) and deployed on AWS Beanstalk with a classic load balancer and without AWS API gateway. I know I can check payload/body size in method implementation but what I want is to block at gateway or load balancer level so that server denies request in the start not penetrate into the code. Please help me out on this. Thanks -
Django - Update multiple objects at once
I have Blank model with foreign key Branch. When objects from Blank model created they have no Branch. In other window I have share button, by which I should assign Branch to these Blank objects in the given number range. For example, branches of blanks with number from 1 to 3 must be updated. But I don't know where and how should I realize update process. Here are my codes: views.py: def blanks(request): if request.method == 'POST' and 'create-blank' in request.POST: form = CreateBlankForm(request.POST) if form.is_valid(): form.save() else: form = CreateBlankForm() blank_list = Blank.objects.all().order_by('-created') # Realize pagination paginator = Paginator(blank_list, 5) page = request.GET.get('page', 1) try: blanks = paginator.page(page) except PageNotAnInteger: blanks = paginator.page(1) except EmptyPage: blanks = paginator.page(paginator.num_pages) context = { 'form': form, 'blanks': blanks, } return render(request, 'blank.html', context) models.py: class Blank(models.Model): blank_series = models.CharField(max_length=3) blank_number = models.IntegerField(blank=True, null=True) shared = models.DateField(blank=True, null=True) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True) number_from = models.IntegerField() number_to = models.IntegerField() def __str__(self): return self.blank_series forms.py: class CreateBlankForm(ModelForm): def save(self, commit=False): blank = super(CreateBlankForm, self).save(commit=False) number_of_objects = range(blank.number_from, blank.number_to+1) for i in number_of_objects: Blank.objects.create( blank_series = blank.blank_series, blank_number = i, shared = blank.shared, branch=blank.branch, number_from = blank.number_from, number_to = blank.number_to ) blanks.html" <form> {% … -
Django if elif else statement
I'm trying to print the result according to the user's age selection in the form, but my if,elif and else statements are not working. class Quiz(models.Model): age_choices = (('10-12', '10-12'), ('13-16', '13-16'), ('17-20', '17-20'), ('21-23','21-23'), ) age = models.CharField(max_length = 100, choices = age_choices) views.py def create_order(request): form = QuizForm(request.POST or None) if request.method == 'POST': quiz = Quiz.objects if quiz.age=='10-12': print("10-12") elif quiz.age=='13-16': print("13-16) elif quiz.age=='17-20': print("17-20") elif quiz.age=='21-23': print("21-23") else: return None context = {'form':form} return render(request, "manualupload.html", context) -
Change URL Of Overridden Templates
On my website users access their accounts by going to the following address: http://127.0.0.1:8000/users_area/username/profile There they will find a button 'change password' (an overridden django template) which will take them to: http://127.0.0.1:8000/accounts/password/change/ It is very small and I'm probably being too picky but is it possible to keep this overridden template but change its url? I'd instead like the change password url to be something like: http://127.0.0.1:8000/users_area/username/password/change/ I'll add as a side note. I actually have two user types, users and powerusers. Each has a unique and rather different 'users_area': http://127.0.0.1:8000/users_area/username/profile and http://127.0.0.1:8000/powerusers_area/username/profile If I get an answer to my above question I'm actually hoping to apply it to both of my different user types (shouldn't be hard but thought I should mention it). Thank you. -
Convert token request from Sign in with Apple returns HTTP 400 form Django REST social auth
I implemented Sign in with Apple backend to Django according to articles below https://medium.com/@kaseyb002/apple-sign-in-with-django-rest-framework-3fdbdae6a1d4 https://python-social-auth.readthedocs.io/en/latest/backends/apple.html When I send convert-token request from iOS App to Django it returns HTTP 400. In the same project(iOS app and Django backend), I also implemented Facebook auth and this is working fine. My guess is that request from iOS app is OK but some settings on Django is wrong but I am not sure about it. What Im I doing wrong and how can I make it work? Django Code Django settings.py, Sign in with Apple related code SOCIAL_AUTH_AUTHENTICATION_BACKENDS = ( # Apple (Sign in with Apple) 'social_core.backends.apple.AppleIdAuth', ) # Social Auth: Apple SOCIAL_AUTH_APPLE_ID_CLIENT = os.environ['MY_BUNDLE_ID'] # App's Bundle ID SOCIAL_AUTH_APPLE_ID_TEAM = '' # From Apple Dev Portal Membership Detail page SOCIAL_AUTH_APPLE_ID_KEY = '' # Created it from Apple Dev Portal SOCIAL_AUTH_APPLE_ID_SECRET = os.environ['MY_SOCIAL_AUTH_APPLE_ID_SECRET'] # I set some random string SOCIAL_AUTH_APPLE_ID_SCOPE = ['email', 'name'] # Same as ones set on iOS app SOCIAL_AUTH_APPLE_ID_EMAIL_AS_USERNAME = True Django settings.py, other code may be related to the problem(Mainly Facebook Auth related) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20 } AUTHENTICATION_BACKENDS = ( # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # Django 'django.contrib.auth.backends.ModelBackend', ) Django's … -
Is it possible to access values submitted through HTML Form, rendered in Preview page, in another views.py method
I am newbie in a django framework. And trying to print PDF from the submitted data through HTML form. For that I have 2 stages. Fillup the form Preview(result) those filled up data Generate PDF from the preview(result) page I have managed to post data using HTML form. My views.py def preview(request): if request.method == "POST": formvals = Formdata() formvals.date = request.POST["date"] formvals.name = request.POST["name"] return render(request, "result.html", {'formvals':formvals}) def getpdfPage(request): formvals = preview(request) print(formvals.date) print(formvals.name) data = {'date':formvals.date, 'formvals.name'} template = get_template("pdf_page.html") data_print = template.render(data) response = BytesIO() pdfPage = pisa.pisaDocument(BytesIO(data_print.encode("UTF-8")),response) if not pdfPage.err: return HttpResponse(response.getvalue(),content_type="application/pdf") else: return HttpResponse("Error faced") Urls.py urlpatterns = [ path('',views.home, name='home'), path('getpdfPage',views.getpdfPage, name='getpdfpage'), path('preview',views.preview, name='preview') ] Here I get None values when i try to print data dict in getpdfPage() Is there any way to access the data of preview() in getpdfPage(). Thanks in advance -
Field 'sno' expected a number but got ''
I am creating a website where anyone can ask questions and on that question, anyone can give answer, but when i code to get answer from user, when user submit his answers they found Error that is ValueError:Field 'sno' expected a number but got ''. Here is my codes: models.py # This code handle user posts class QueryPost(models.Model): sno = models.AutoField(primary_key = True) user = models.ForeignKey(User, on_delete=models.CASCADE) Query_post = models.TextField() Query_image = models.ImageField(upload_to = "Query_image", blank=True) slug = models.CharField(max_length=30) timeStamp = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.user) + ' ' + str(self.timeStamp.date()) #This code for get user answers class QueryAns(models.Model): sno = models.AutoField(primary_key = True) Query_ans = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) ans_image = models.ImageField(upload_to = "Query_ans_image", blank=True) queryPost = models.ForeignKey(QueryPost, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timeStamp = models.DateTimeField(default=now) def __str__(self): return str(self.user) + ' ' + str(self.timeStamp.date()) views.py def queryPost(request): if request.method =="POST": user_ = request.user Query_post_ = request.POST.get('Query_post','') Query_image_ = request.POST.get('Query_image','') #condition if len(Query_post_) == 0: messages.error(request, "somting went wrong") return redirect('Home') #creat post Query_obj = QueryPost(user=user_ , Query_post=Query_post_, Query_image=Query_image_) Query_obj.save() messages.success(request, "Successfully Query post") return redirect('/Query') else: messages.error(request, "somting went wrong") return HttpResponse('404-not found') def queryAns(request): if request.method == "POST": Query_ans_ = request.POST.get("Query_ans") user = request.user … -
How to use Bootstrap tabs with Block Content in Django
I cannot figure out how to use Boostrap Tabs, when block content is needed and I am unable to make sue of the href in tab li a item. See below for any ideas. thanks for any help. When you click on the below, it changes the tabs as expected, however, how do you incorporate django views? for example when the email tab is clicked, show the tab view for {% url 'account_email' %} in the content pane? <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-lg-7"> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-email-tab" data-toggle="tab" href="#nav-email" role="tab" aria-controls="nav-email" aria-selected="true">E-mail</a> <a class="nav-item nav-link" id="nav-password-tab" data-toggle="tab" href="#nav-password" role="tab" aria-controls="nav-password" aria-selected="false">Password</a> <a class="nav-item nav-link" id="nav-connect-tab" data-toggle="tab" href="#nav-connect" role="tab" aria-controls="nav-connect" aria-selected="false">Connect</a> </div> </nav> </div> </div> <div class="row justify-content-center"> <div class="col-lg-8"> <div class="container mt-5 text-center mx-auto"> <div class="card p-5"> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-email" role="tabpanel" aria-labelledby="nav-email-tab"> {% block email_content %}{% endblock %} </div> <div class="tab-pane fade" id="nav-password" role="tabpanel" aria-labelledby="nav-password-tab"> {% block password_content %}{% endblock %} </div> <div class="tab-pane fade" id="nav-connect" role="tabpanel" aria-labelledby="nav-connect-tab"> {% block connect_content %}{% endblock %} </div> </div> </div> </div> </div> </div> </div> -
How to send a custom message in case of Missing Permission in Django
I am trying to send error message if a user does not have permission to transact on a given model. So suppose I have this model: class MyBooks(models.Model): name = models.CharField(max_length=150, verbose_name='Book Name') ISBN = models.... date_published = models..... I am assigning permissions to users for transactions such as create, change etc. Now using PermissionRequiredMixin I am trying to restrict a user from createing an instance of MyBooks model. By default, the app takes one to a 403 Forbidden page in case of missing permission (to create). What I am trying to do is to display a custom message using TemplateView directly on the urls.py file like this: from django.views.generic import TemplateView urlpatterns = [ ... path('error_msg/', TemplateView.as_view(template_name='error_403.html'), name='error_403'), ... ] As of now I have put plain text message in the template which unfortunately is not of much help to the user as to what caused the error or more specifically, which missing permission cause the transaction to fail. How can I display the permission's name or codename field values in my "custom" message? -
How to generate error message for the field that is not in models in django
I have the following models in two different apps that are related in some sense. Student model in accounts app that stores first_name last_name email reg_number roll_number status guardian (fk) Other two models are in campus app, ClassRoom model and ClassRoomStudents. ClassRoom model stores the following room_number (pk) level (fk) section student_capacity incharge (fk) ClassRoomStudents is a join table between ClassRoom and Student tables ClassRoomStudents stores the following class_room (fk) student (fk) session Now when I create a new student I'm adding the student to a class room hence all the three tables are being populated. Take a look at the view that is adding a new student. if std_user_form.is_valid() and std_profile_form.is_valid(): std_user_instance = std_user_form.save() std_user_instance.groups.add(Group.objects.get(name='Student')) parent_obj = request.POST.get('guardian') class_room_obj = request.POST.get('class_room') std_instance = Student.objects.create( user=std_user_instance, gender = std_profile_form.cleaned_data.get('gender'), photo = std_profile_form.cleaned_data.get('photo'), birth_date = std_profile_form.cleaned_data.get('birth_date'), reg_number = str(datetime.datetime.now().year-2000)+ str(datetime.date.today().strftime('%m'))+ str(101+self.getTotalStudentCount()), roll_number = 1, # temporarily giving 1 roll_number and updating again to the number of students in the class status = 'A', # student will be active on creation and Inactive only when passed out of left school guardian = get_object_or_404(Parent, id=parent_obj) ) student_class_room = ClassRoomStudents.objects.create( class_room = get_object_or_404(ClassRoom, pk=class_room_obj), student = get_object_or_404(Student, pk=std_instance.reg_number), session = datetime.datetime.now().year ) Student.objects.filter(user=std_user_instance).update( roll_number … -
wagtail streamField in template forms
I have exceptional requirements on wagtail. I like wagtail StreamField very well. I am trying to take wagtail streamField outside of wagtail admin. I want all the user can write article after they signup to my site but i don't want to let user to see the wagtail admin page. I have very different url to write and submit the article. but the problem is, i am confused if it is possible to bring wagtail streamField/Rich text editor or etc to the django custom template? Anyone have done this kind of job before? is it possible? -
Django admin page refused to connect
So I'm realtively new on Python and Django . I was creating a blog application using django and I'm facing problems regarding my django admin page. I did all the migrations and created superuser as told in a paritcular tutorial. But after that when I'm trying to open Django admin page , it says that my localhost refused to connect C:\Users\HP\Desktop\django_project>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 27, 2020 - 09:27:16 Django version 3.0.8, using settings 'django_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [27/Jul/2020 09:27:33] "GET / HTTP/1.1" 200 3899 [27/Jul/2020 09:27:33] "GET /static/blog/main.css HTTP/1.1" 304 0 Not Found: /favicon.ico [27/Jul/2020 09:27:34] "GET /favicon.ico HTTP/1.1" 404 2317 My urls.py looks like this... from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ] And my Installed apps and Middleware in settings.py looks like.. INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I'm using Python 3.7 , Django version 3.0.8 and Windows 10. -
How to make interactive tables in Django?
I am a beginner at Django and I am trying to make a time-table app. I want the user to be able to add/remove rows and columns, edit cell values and merge cells together in a table. How can I build that. I do not want to use a front-end framework like Angular or React for this. -
Why won't my view load in properly? (Django)
I am extremely new to Django's framework and recently finished the introductory series on their website, and I have tried adding a new view in which I use a form to create an object. The problem is, whenever I access the view, it immediately executes the HttpResponseRedirect(), and second of all it does not even return a response. views.py def create(request): context = { 'questionfields': Question.__dict__, } submitbutton = request.POST.get('Create', False) if submitbutton: new_question = Question(question_text=request.POST.get('question_text', ''), pub_date=timezone.now()) if new_question.question_text == '': context = { 'questionfields': Question.__dict__, 'error_message': "No poll question entered." } del new_question return render(request, 'polls/create.html', context) else: return HttpResponseRedirect(reverse('create')) create.html {% extends "polls/base.html" %} {% block title %}Create a Poll{% endblock title %} {% block header %}Create:{% endblock header %} {% load custom_tags %} {% block content %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:create' %}" method="post"> {% csrf_token %} {% for field in questionfields %} {% if field == 'question_text' %} <label for="{{ field }}">{{ field|capfirst|replace }}:</label> <input type="text" name="{{ field }}" id="{{ field }}"> <br> {% else %} {% endif %} {% endfor %} <br> <input type="submit" value="Create" name="submit"> </form> {% endblock content %} I attempted to make it so … -
E.408, E.409 error on running manage.py runserver
ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. Django: 2.2 Python 3.6 I have already renamed "MIDDLEWARE" as in Django-2.2 From settings.py DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'music.apps.MusicConfig', 'advancedConfig.apps.AdvancedconfigConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'autodynatrace.wrappers.django', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have initially installed the project on 1.9 Django and now I upgraded Django to 2.2 and getting this error. I have checked other threads, however, nothing helped. -
SES from AWS does not work with Django due to not verified Email
I tried to sign up on Deployed Django app as a sample user but Server Error (500) comes up. Here is error log raise error_class(parsed_response, operation_name) botocore.errorfactory.MessageRejected: An error occurred (MessageRejected) when calling the SendRawEmail operation: Email address is not verified. The following identities failed the check in region US-EAST-1: webmaster@localhost 2020-07-27 12:32:52,406 [ERROR] /home/app_admin/venv_private_diary/lib64/python3.7/site-packages/django/core/servers/basehttp.py(Line:154) "POST /accounts/login/ HTTP/1.0" 500 27 In the error message "webmaster@localhost" indicates that Django app sends default email address, hence I had added this statement to settings.py. DEFAULT_FROM_EMAIL = 'my@emailaddress.com' but still, the same error message came up. where should I check?? -
Django subtract from another model
I'm currently working on a stock handling function. I have a form that allows a customer to select any 1 product among 4 products and it's quantity either 30 or 60. In my stock model, I have created 4 objects each object holding the total amount of quantity of each product. I want to create a function in which when a customer selects a product and the quantity he/she would like to purchase and submits the form the quantity selected should be subtracted from the total_quanity of that particular product in stock model. models.py class Product(models.Model): product_choices = (('product1', 'product1'),('product2','product2'),('product3', 'product3'),('product4','product4') quantity_choices = (('30','30'),('60','60'),) product = models.CharField(max_length = 100, choices = product_choices) quantity = models.CharField(max_length = 100, choices = quantity_choices) class Stock(models.Model): stockId = models.AutoField(primary_key=True) productID = models.ForeignKey(Order,on_delete= models.CASCADE) product_name = models.CharField(max_length=100) total_quantity = models.IntegerField(default='0', blank=True, null=True) -
django & AWS S3 - network/performance cost difference on enabling pre-signed url
Say, I have a django project with static files stored on Amazon S3 with django-storage as a custom storage. Say, I have a static file called style.css. According to this question: By default, AWS_QUERYSTRING_AUTH is set to True, and the generated link will be as such : https://bucket.s3.amazonaws.com/style.css?AWSAccessKeyId=xxxxxx&Signature=xxxx&Expires=1595823548 But if I set AWS_QUERYSTRING_AUTH to False, the generated link will be as such : https://bucket.s3.amazonaws.com/style.css (e.g. without accessId, signature, and expire) for public file, they said I should set this to False If I get this correctly, this is what people call a "signed url". Functionality-wise, both of these 2 options above will work exaclty as the same, despite the longer link on the first option. My question are: performance-wise, does pre-signed url affect CPU/networking bandwith as much? If I have a hundreds of public files that can be served without pre-signed url, does my server get the overhead (in terms of CPU and networking) if I insist to serve all of it with presigned url ?