Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / Signal / Admin forms - actions: a way to automize login/pwd send to user but pre_save.connect not sets off with action
I have a model Profile that is related to User model. This Profile model contain a field pro_mai (0 : login/pwd not send / 1 : login/pwd send). models.py class Profile(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE pro_ide = models.AutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) site = models.ForeignKey(Site, on_delete = models.CASCADE) ... pro_mai = models.IntegerField("Send user login/password? (y/n)",default=0, null=True, blank=True) ... I have a 'signal' in Profile model that send an email to user with his login/pwd when is updated with pro_mai = 1. It works when I update this field from admin form display view. 'signal function' def send_user_account(sender,instance,**kwargs): if not instance._state.adding and instance.pro_mai == 1: user = User.objects.get(username=instance.user) # mail user # do stuff # pre_save.connect(send_user_account, sender=Profile) post_save.connect(send_user_account, sender=Profile) Now, I would like to automatize this action. So I have created a action 'Send login/password' in my Profil Admin form. This action update Profile model (pro_mai = 1) but signal is not sets off. admin.py def send_login_password(modeladmin, request, queryset): queryset.update( pro_mai = 1, ) send_login_password.short_description = 'Send login/password to user' class ProfileAdmin(SimpleHistoryAdmin): list_display = ('name','contact','mail','fonction',) actions = [send_login_password] form = ProfileFormAdmin Is it the good way to do? What I do wrong? -
Im trying to use class based views for a second app in the same project, however, the changes are not pulling through?
url.py for todo from django.urls import path from . import views from .views import TodoListView urlpatterns = [ path('todo/', TodoListView.as_view(), name='blog-todo') ] views.py for todo from django.shortcuts import render from django.http import HttpResponse from .models import Todo from django.views.generic import ListView def todo(request): context = { 'todo_list': Todo.objects.all(), 'title': 'Todo' } return render (request, 'todo/to_do.html', context) class TodoListView(ListView): model = Todo template_name = 'todo/to_do.html' context_object_name = 'todo_list' ordering = ['-date_posted'] this is my regular urls.py for the project from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static from todo import views urlpatterns = [ path('admin/', admin.site.urls), path('todo/', views.todo, name='blog-todo'), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='logout_pages/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='logout_pages/logout.html'), name='logout'), path('', include('blog.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py for todo from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Todo(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Im trying to create a list for view for all the todo tasks that pull from the database. However this is not pulling the necessary changes … -
Is AUTHENTICATION_BACKENDS a default setting found in settings.py in Django 3?
Following a book on django, at the point where it is discussing building a custom authentication backend. It states "The AUTHENTICATION_BACKENDS settings includes the list of authentication backends for your project. By default, this setting is set as follows: ['django.conrib.auth.backends.ModelBackend']" but nowhere in my settings.py do I see AUTHENTICATION_BACKENDS = ['django.conrib.auth.backends.ModelBackend'], here is my full settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&5bic7q4#osz31w6ojc@@4_&6!xsts^7w764g1=+0^v&0r&-la' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'account.apps.AccountConfig', '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', ] ROOT_URLCONF = 'bookmarks.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bookmarks.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': … -
Django maximum recursion dept exceeded error
I am trying to build a push notification application using django for web browsers. It will be great if any one has a working code !! I encountered the following error while running manage.py (venv) C:\Users\MAC Pathak\PycharmProjects\webpush\fbpush>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\MAC Pathak\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\MAC Pathak\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check messages.extend(check_resolver(pattern)) ... continues for around 60-80 iterations line 408 and line 23 File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\urls\resolvers.py", line 409, in check messages.extend(self._check_custom_error_handlers()) File "C:\Users\MAC Pathak\PycharmProjects\webpush\venv\lib\site-packages\django\urls\resolvers.py", line 426, in _check_custom_error_handlers signature = inspect.signature(handler) File "C:\Users\MAC Pathak\AppData\Local\Programs\Python\Python38-32\lib\inspect.py", line 3093, in signature return Signature.from_callable(obj, follow_wrapped=follow_wrapped) File "C:\Users\MAC Pathak\AppData\Local\Programs\Python\Python38-32\lib\inspect.py", line 2842, in from_callable return _signature_from_callable(obj, sigcls=cls, File "C:\Users\MAC Pathak\AppData\Local\Programs\Python\Python38-32\lib\inspect.py", line 2292, … -
Failed GET requests to AWS S3 from website running on local host
Problem: I am developing a website using django, with images and static content stored in S3. I get 403 forbidden errors when I run my site on local host. GET https://mybucket.s3.amazonaws.com/static/image.jpg 403 (Forbidden) What I have tried so far: Configured CORS on my S3 bucket <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Stored S3 credentials in environment variables. I have been able to run python manage.py collectstatic to upload static files to S3, so I know this connection is established. Does anyone know what I am missing? -
How to call Python script from Javascript
I am currently using Django framework for my project. I want to call a Python script from Javascript so that after my views renders the html, a button can be pressed by the user where javascript will request to run a python function. This is so that the html doesn't refresh every time I run a python function. I tried looking at other similar questions' however there is no clear answer for me to follow so any help and direction is much appreciated. I'll provide any sample code if required. Thank you again. -
How to configure django automatically create folders for each user image
For example, I want to create an Ebay clone. I want that each user, who will upload an item have his own folder, that would be created automatically, after user log-in, so, pictures, that user would upload store in his own folder! What is the best solution for this problem? -
Environnement variable missing in Django
I am have issue with my GeoDjango app and I think it is linked a missing environment variable. I have the following error on a simple GeoJSONLayerView: GDALException at /GeoJSONTrialView/9020/ OGR failure. Request Method: GET Request URL: https://realregatta.com/GeoJSONTrialView/9020/ Django Version: 3.0.6 Exception Type: GDALException Exception Value: OGR failure. Exception Location: /opt/bitnami/python/lib/python3.7/site-packages/django/contrib/gis/gdal/error.py in check_err, line 59 Python Executable: /opt/bitnami/python/bin/python3 Python Version: 3.7.7 I found a workaround by adding the environment variable in the view: class GeoJSONTrialView(GeoJSONLayerView): def get_queryset(self): os.environ["PROJ_LIB"] = "/home/bitnami/stack/postgresql/share/proj" context = Trial.objects.filter(id=self.kwargs['pk']) return context Note that I have the variable set in my settings.py (and it shows on the Django debug crash page, even without my workaround): PROJ_LIB = "/home/bitnami/stack/postgresql/share/proj" Traceback: Environment: Request Method: GET Request URL: https://realregatta.com/GeoJSONTrialView/9020/ Django Version: 3.0.6 Python Version: 3.7.7 Installed Applications: ['RR.apps.AppConfig', 'djgeojson', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis'] Installed 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'] Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/bitnami/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/bitnami/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/bitnami/python/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/opt/bitnami/python/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File … -
Object is not iterable in django rest
I have a simple view in DRF that looks like this: class AdminDocumentListUpdateView(generics.ListAPIView, mixins.UpdateModelMixin): queryset = Document.objects.all() serializer_class = AdminDocumentSerializer pagination_class = None def get_queryset(self): user_id = self.kwargs.get('user_id') qs = Document.objects.filter(user=user_id).latest('created_at') return qs But the get_queryset function raises an error 'Document' object is not iterable. This only happens when I add something like latest('created_at') or first() or I try to index the queryset ([0]). Why is this happening? -
DecimalField without defining precision and scale
How to not specify DecimalField with precision and scale? I got many columns with different values and would like to take what is there without specifying specific precision and scale for every column. Can I define somehow DecimalField without specifying precision and scale so data will be taken as it is? In my source database columns are marked either numeric or numeric(x,y). Maybe defining in django just as numeric instead decimalfield? -
how to disappear label after 1 week for django template
lets think you have a blog with entrys. You want that the newly created entry has a label "new" and you want that this "new" label should disappear after 1 week from ceated_date. What kind of way would you follow. I try this in django template. Thank you -
How to get the value of a hidden input in django views
I am working on a django application. In the application, I have a drop-down button in a form. There also is a hidden input field that will hold the value of the drop-down item selected. (I achieved this with jQuery). I want to access the value of the hidden field in the views.py file. Right now when the form is submitted, I am only getting a None value returned. I am not sure what I am doing wrong. This is my code so far HTML template <form method="post" action="{% url 'test_app:get_data' %}"> {% csrf_token %} <div class="dropdown"> <button class="btn btn-primary btn-lg btn-block dropdown-toggle fruit-btn" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Fruit </button> <input type="hidden" name="fruit-name" id="fruit-name" value="" disabled> <div class="dropdown-menu"> <ul class="list-group" role="menu" aria-labelledby="dropdownMenu"> <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Apple</a></li> <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Banana</a></li> <li class='list-group-item'><a class="btn btn-lg dropdown-item" href="#">Mango</a></li> </ul> </div> </div> ... <button type="submit" class="btn btn-primary btn-block btn-lg mt-5">Submit</button> </form> views.py def test_data(request): if request.method == 'POST': fruit = request.POST.get('fruit-name') print(fruit) return redirect("test_app:root") return render(request, 'test_app/root.html') jquery code to get the value of the button in the hidden input field $(document).ready(function() { $('.dropdown-item').click(function() { $('.fruit-btn').text($(this).text()); $('.fruit-btn').val($(this).text()); $('#fruit-name').val($(this).text()); console.log($('#fruit-name').val()) }) }) This is the output of the jquery … -
How to increment "number" field for each owner(ForeignKey) in Django
Please help ! Here is my model , I want to have a number for each address each owner. Like for owner A he might have address 1 address 2 .. owner B also : address 1 address 2 .. class Address(TimeStamp): number = models.IntegerField(default=0, null=False) owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='owner_address') def save(self, *args, **kwargs): if self.pk: for owner in self.owner: self.number += 1 return super(DeliveryAddress, self).save(*args, **kwargs) -
<HaltServer 'Worker failed to boot.' 3> Gunicorn error, log-file shows no errors
So I just set up my Django up on server with Nginx and Gunicorn, and it was working fine with my development settings, however when I added the production settings it stopped working for some reason. Here are the tracebacks. ~/mediabiz$ gunicorn --log-file=- mediabiz.wsgi:application [2020-06-17 11:15:53 +0000] [10691] [INFO] Starting gunicorn 20.0.4 [2020-06-17 11:15:53 +0000] [10691] [INFO] Listening at: http://127.0.0.1:8000 (10691) [2020-06-17 11:15:53 +0000] [10691] [INFO] Using worker: sync [2020-06-17 11:15:53 +0000] [10694] [INFO] Booting worker with pid: 10694 ~/mediabiz$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2020-06-17 11:14:38 UTC; 3min 11s ago Main PID: 10583 (code=exited, status=1/FAILURE) Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: self.stop() Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: File "/home/simeon/lib/python3.6/site-packages/gunicorn/arbiter.py", line 393, in stop Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: time.sleep(0.1) Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: File "/home/simeon/lib/python3.6/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: self.reap_workers() Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: File "/home/simeon/lib/python3.6/site-packages/gunicorn/arbiter.py", line 525, in reap_workers[m Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 gunicorn[10583]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Jun 17 11:14:38 ubuntu-s-2vcpu-4gb-nyc1-01 systemd[1]: … -
How to give proper path to FFMPEG in Django for using django-video-encoding package?
Hey guys I am using django-video-encoding package, I followed the documentation but it isn't working when I upload videos. I don't know how to properly provide the path for ffmpeg path for django in windows 10. This is what i have given now. VIDEO_ENCODING_FFMPEG_PATH = "c:\\ffmpeg\\bin\\ffmpeg.exe" but it doesn't seem to work and no errors are showing, as the video is getting uploaded, but not getting converted. How to properly provide the path in windows? Thanks -
How to pass data from jquery to views.py django
I Have data in a variable need to pass in views.py in Django. Code: index.html <table class="table table-striped table-dark" cellspacing="0"> <thead class="bg-info"> <tr> <th>Company's Symbol</th> <th>Current Price</th> <th>View Current chart</th> <th>Action</th> </tr> </thead> <tbody> {% for a,b in stocks %} <tr> <th scope="row" class="comp_name">{{ a }}</th> <td>{{ b }}</td> <td> <button class="btn graph-btn">View Graph</button> </td> <td> <button class="btn predict-btn">Predict Closing Price</button> </td> </tr> {% endfor %} </tbody> </table> When I click on .graph-btn it will get data from .comp_name.(Here is the code): <script> $(".graph-btn").click(function() { var $row = $(this).closest("tr"); var $text = $row.find(".comp_name").text(); }); </script> so here data in text I want to pass in views.py. -
How to manually render django forms and grab the data on submit
I have the codes below from a forms.Form (I don't want to use ModelForm) because i want to manage the look of HTML form and I am unable to see the data that i post on submit. forms class SearchForm(forms.Form): hotel_name = forms.CharField(max_length=40) check_in_date = forms.DateField() check_out_date = forms.DateField() guest_number = forms.IntegerField() views from .forms import SearchForm import datetime def index(request): date_ = datetime.date.today() today = date_.strftime("%Y-%m-%d") if request.method == "POST": form = SearchForm(request.POST) print(form) # me trying to print only the data received on POST else: form = SearchForm() context = { 'form': form, } return render(request, 'hotels/index.html', context) template <table> <tr> <th> <label for="destination">Destination:</label> </th> <td> <input type="search" id="search_name" placeholder=" Where would you like to stay?" name="search" size="40"><br> </td> </tr> <tr> <th> <label for="check_in">Check In:</label> </th> <td> <input id="check-in" name="check-in" type="date" min="{{today}}" onchange="checkInDate(event)"><br> </td> </tr> <tr> <th> <label for="check-out">Check Out:</label> </th> <td> <input id="check-out" name="check-out" type="date" min="{{today}}" onchange="checkOutDate(event)"><br> </td> </tr> <tr> <th> <label for="id_mime">Mime:</label> </th> <td> <input id="guests" name="guests" type="number" min="1" max="5" size="10"><br> </td> </tr> <tr> <td></td> <td><input type="submit"></td> </tr> </table> Is there anything that i am doing wrong? Any help would be helpful. -
How i solve this below issue get authenticate user detals?
** that time i get authenticated user data my condition is not true but when i get not authenticated user data below condition is true so can anyone help me what can i do..................................................................................................................................................................................................................** header.html <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if request.user.is_authenticated%} <a class="navbar-brand" href="">Welcome{{user.get_username}}</a> <!-- Welcome {{ user.get_username}} --> {% else %} <a class="navbar-brand" href="">no</a> {% endif %} **And when i write this code condition is true show username in template what can i do?** <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if not request.user.is_authenticated%} <a class="navbar-brand" href="">Welcome{{user.get_username}}</a> <!-- Welcome {{ user.get_username}} --> {% else %} <a class="navbar-brand" href="">no</a> {% endif %} views.py def registration_view(request): # if this is a POST request we need to process the form data template = 'home/login.html' if request.method == 'POST': print("post") # create a form instance and populate it with data from the request: form = RegisterForm(request.POST) # check whether it's valid: if form.is_valid(): print("okk valid") if User.objects.filter(username=form.cleaned_data['username']).exists(): messages.error(request,'Username already exists') return render(request, template, { 'form': form, 'error_message': 'Username already exists.' }) elif User.objects.filter(email=form.cleaned_data['email']).exists(): messages.error(request,'Email already exists') return render(request, template, { 'form': form, 'error_message': 'Email already exists.' }) elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']: messages.error(request,'Password do not … -
Calling a django function view from an aws lambda function
I want to run my django views on AWS Lambda. For this I had created a lambda function which is calling that view function. The AWS lambda function is something like this -> import app.views as v def functionA_handler(event, context): some_value = v.functionA(event) return some_value The corresponding view in app.views file would be something like this -> from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse @csrf_exempt def functionA(request): request_body = json.loads(request.body) return JsonResponse(request_body, status=200) How can I link the above lambda function to the view function? The view takes an input of the form request which is creating an issue here. Any solution? -
Elastic Beanstalk - Command failed on instance.An unexpected error has occurred [ErrorCode: 0000000001]
First time I'm trying to deploy a django app to elastic beanstalk. The application uses django channels. These are my config files: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard/dashboard/settings.py" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /websockets/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP container_commands: 00_pip_upgrade: command: "source /opt/python/run/venv/bin/activate && pip install --upgrade pip" ignoreErrors: false 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "django-admin.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' When I run eb create django-env I get the following logs: Creating application version archive "app-200617_112710". Uploading: [##################################################] 100% Done... Environment details for: django-env Application name: dashboard Region: us-west-2 Deployed Version: app-200617_112710 Environment ID: e-rdgipdg4z3 Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.7 running on 64bit Amazon Linux 2/3.0.2 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2020-06-17 10:27:48.898000+00:00 Printing Status: 2020-06-17 10:27:47 INFO createEnvironment is starting. 2020-06-17 10:27:49 INFO Using elasticbeanstalk-us-west-2-041741961231 as Amazon S3 storage bucket for environment data. 2020-06-17 10:28:10 INFO Created security group named: sg-0942435ec637ad173 2020-06-17 10:28:25 INFO Created load balancer named: awseb-e-r-AWSEBLoa-19UYXEUG5IA4F 2020-06-17 10:28:25 INFO Created security group named: awseb-e-rdgipdg4z3-stack-AWSEBSecurityGroup-17RVV1ZT14855 2020-06-17 10:28:25 INFO Created Auto Scaling launch configuration named: awseb-e-rdgipdg4z3-stack-AWSEBAutoScalingLaunchConfiguration-H5E4G2YJ3LEC 2020-06-17 10:29:30 INFO Created Auto Scaling group … -
Can't test uploading file with Django clien.post method
I have problem with testing API method. I have model Game with such field: background = models.ImageField(max_length=255, null=True, blank=True, storage=s3_storage, upload_to='game_back/%Y/%m/%d') Serializer for that model looks like: class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = (<list_of_fields>, 'background') I tried to write test that cat pass image to this model. But i have problem with Djnago test build-in method for post. If i write: file = open('<path_to>/test_image.png', 'rb') content_bytes = file.read() img = SimpleUploadedFile("uni_image.png", content_bytes, content_type="image/png") response = self.client.post( reverse('game_create'), data={'background': img}, format="multipart" ) Django raise an exception UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte on row with client.post I tried to pass base64 encoded data instead of SimpleUploadedFile use, but in this case my API serializer cant validate and save image file. Thanks for reacting! -
Django Rest Framework: Get field name from model definition
Within the Django Rest framework documentation it is suggested to declare the "field" list explicitly to avoid providing the data of new columns just by adding them to the model which may contain sensitive information. The field list is an array of strings, containing the field ids. To avoid declaring field ids, which actually do not exist in the model (e.g. typos or changed models) I tried to declare the list using object references - but always end up with "DeferredAttribute: object has no attribute ". I have read something that meta information is not available in objects and that you could solve that by defininig your own Meta class using Object._meta.get_fields() and store it in the class, but I thought there might be a simpler/more elegant way (and I do now know, how, in detail ;-)). Example: class Samples(models.Model): # Meta data, primarily used in AdminSite. class Meta: verbose_name = _('Samples') verbose_name_plural = _('Samples') samples_boolfield = models.BooleanField samples_textfield = models.CharField(max_length=2000, blank=True) views.py: class SamplesView(viewsets.ModelViewSet): serializer_class = SamplesSerializer queryset = Samples.objects.all() serializers.py: Version 1, which does not show any errors in pyCharm or makemigrations, but calling the API reults in "TypeError at /api/samples/: argument of type 'DeferredAttribute' is not iterable": … -
Django and Amazon Lambda: Best solution for big data with Amazon RDS or GraphQL or Amazon AppSync
We have a system with large data (about 10 million rows in on a table). We developed it in Django framework and also we want to use Amazon Lambda for serving it. Now I have some question about it: 1- If we want to use Amazon RDS (MySql, PostgresSQL), which one is better? And relational database is a good solution for doing this? 2- I read somewhere, If we want to use a relational database in Amazon Lambda, Django for each instance, opens a new connection to the DB and it is awful. Is this correct? 3- If we want to use GraphQL and Graph database, Is that a good solution? Or we can combine Django Rest-API and GraphQL together? 4- If we don't use Django and use Amazon AppSync, Is better or not? What are our limitations for use this. Please help me. Thanks -
Django channels on Elastic Beanstalk - is this config file correct?
Following this guide https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 to deploy a django project which uses channels. In the guide they mention to create the file <PROJECT_DIR>/.ebextensions/01_env.config with the following: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: <PROJECT_DIR/.../>wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: <PROJECT_DIR...CONFIG.FILE> PYTHONPATH: /opt/python/current/app/<PROJECT_DIR>:$PYTHONPATH If my project is called dashboard, is the following correct? option_settings: aws:elasticbeanstalk:container:python: WSGIPath: "dashboard/dashboard/wsgi.py" aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "dashboard/dashboard/settings.py" PYTHONPATH: /opt/python/current/app/dashboard:$PYTHONPATH -
Django User and Group model permissions fields as manytomany
In my project, I'm using custom overridden admin templates but I cannot figure out how to change the permissions and groups selector in the User and Group models. I want to change them to how the ManyToMany field handles it or a multi-select. How to I change it? Thank you for reading this.