Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am creating a backend for eber website but in got his error
i am creating backend for eber website but got an error this is the code 'from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. class CustomUserManager(BaseUserManager): def create_user(self, email, password = None, **kwargs): if not email: raise ValueError('Users must have an email address') user = self.model( email = self.normalize_email(email), ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email, password= None): user = self.create_user( email, password = password, ) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name = 'email address', max_length = 255, unique = True, ) is_admin = models.BooleanField(default = False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' objects = CustomUserManager() #USERNAME_FIELD = 'email' def __str__(self): return self.email def has_perm(self, perm, obj= None): "Does the user have a specific permission?" return True def has_module_perms(self, app_label): "Does the user have permissions to view the app?" return True' the error i got is this 'TypeError at /api/v1/users/ create_user() missing 1 required positional argument: 'username' Request Method: POST Request URL: http://127.0.0.1:8000/api/v1/users/ Django Version: 3.1.5 Exception Type: TypeError Exception Value: create_user() missing 1 required positional argument: 'username' Exception Location: /home/danish-khan/django_drf/eberbackend/apps/users/views.py, line 14, in create Python Executable: /home/danish-khan/django_drf/django/bin/python Python Version: 3.8.5 … -
Convert to python TimeField object
I have been googling around but surprisingly haven't seen what I was looking for. I have strings like these '11:00 am', '12:00 pm', How does one convert this to Django models.TimeField() object. -
Django get request.POST.get() parameter not working as expected, parameter name with brackets[]
I have a code that is behaving really strange. The view receives a POST request with a key "tags[]", it is a list. I need to get that list but request.POST.get() only returns the last item of the list. This is the code: .... elif request.method == "POST": print("REQUEST POST:") print(request.POST) print("---------------------------") tags = request.POST.get("tags[]") print("tags: %s" % tags) print("---------------------------") And it prints the following: REQUEST POST: <QueryDict: {'csrfmiddlewaretoken': ['PAgg9VKGosBQUn8tBBb09NdeVgE8tcAaQz2EMbkQZPiJi289hBf7MHIKM1jF8mvp'], 'event_type_description': ['live_course'], 'title': [''], 'description': [''], 'platform_name': ['Zoom'], 'other_platform': [''], 'record_date': [''], 'date_start': [''], 'date_end': [''], 'time_day': ['12:00 PM'], 'schedule_description': [''], 'tags[]': ['not', 'normal', 'very', 'strange'], 'event_picture': ['']}> --------------------------- tags: strange --------------------------- As you can see, the value of the tags variable is "strange", the last item in the list. Why not all the list? request.POST.get is behaving in an unexpected way. Am I missing something? -
Username state gets undefined / null after a few minutes in JWT authentication React Django
I am making a React application with the backend of the Django REST framework. Everything works fine except when retrieving the username. Retrieving the username is no problem but keeping it for a time is a problem. I'm going to explain using comments now in the code; import React, { Component } from 'react'; import Nav from './Components/Navbar'; import LoginForm from './Components/LoginForm'; import SignupForm from './Components/SignupForm'; import Layout from './Containers/Layout'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { displayed_form: '', logged_in: localStorage.getItem('token') ? true : false, username: '', // username state error: null }; } componentDidMount() { if (this.state.logged_in) { fetch('http://localhost:8000/core/current_user/', { // fetch is used to get current user headers: { Authorization: `JWT ${localStorage.getItem('token')}` } }) .then(res => res.json()) .then(json => { this.setState({ username: json.username }); // set the state }); } } handle_login = (e, data) => { e.preventDefault(); fetch('http://localhost:8000/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => { try { localStorage.setItem('token', json.token); this.setState({ logged_in: true, displayed_form: '', username: json.user.username, error: '', }) } catch (error) { this.setState({error: "We Couldn't log you in, maybe theres a typo in the data you entered"}) this.handle_logout() } }); … -
Can you use MapBox to have web users add locations?
I am very new to webdesign. I want to create a website where users can add locations/ change information about a location using MapBox. Is this possible? Can someone help me understand this process. If I can't use mapbox, could someone give me an alternate platform? -
Python virtualenv installed package not found
I cannot import djangoin my fresh virtualenv installation (python 3.7.9). So far : $ virtualenv env $ source env\bin\activate $ (env) pip install django $ (env) pip freeze asgiref==3.3.1 Django==3.1.7 pytz==2021.1 sqlparse==0.4.1 All good so far. Except: $ (env) python >>> import django ModuleNotFoundError: No module named 'django' I've tried : where django-admin my_website/env/bin/django-admin So clealy if my command line can recognise it but not python, it has to do with PYTHONPATH.. I'm just not sure how to proceed now, it gets very confusing from here. Note : I've also aliased my python version to 3.7.9 in bash. $ (env) python --version Python 3.7.9 -
Django ForeignKey serve nested objects with GET but accept id with POST request
I am new to Django. In my app, each Topic has Category fields. When fetching list of topics, it was serving id as category field like this: { id: 1, topic: "title", category: 1 } I added this to my serializer.py file: class TopicSerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = Topic fields = "__all__" Now I am able to receive the whole category object: { id: 1, topic: "title", category: { name: "Category name" }, } However, when adding a new topic, it is expecting a dictionary. I still want to be able to add a new topic by passing category id in the dictionary like this: { topic: "new topic title", category: 1 } How can I make it so that POST request accepts category field as id but still serves category object in GET request? Thanks. -
Do I need an nginx container inside my Kubernetes cluster to serve my static files if I am using Ingress-Nginx service on the cluster?
Might be a dumb question but I have a relatively simple Django App running in a docker container, also I have an Nginx container as a reverse-proxy serving my static files for the same app. Now, the question is, when I am to put the Django app inside a K8s cluster and spin up an Ingress-Nginx service, would I still need an Nginx container running inside the cluster to serve static files or I can use Ingress-Nginx for that? Thanks -
Django rest framework: serializing extra fields that depend on other state?
This question asks how to add an additional field to ModelSerializer. This answer says you can add a SerializerMethodField. But, how to implement a method field if the value of the call depends on some other parameter, like the request? -
Django error: NoReverseMatch at : I get this error
I have the following conceptual error which I am not undertstanding: Please have a look at the thrown error: NoReverseMatch at /watchlist Reverse for 'auction' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<auction_id>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/watchlist This is my urls.py file: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("<int:auction_id>", views.auction, name="auction"), path("new", views.newItem, name="newItem"), path("watchlist", views.watchlist, name="watchlist"), path("addwatchList/<int:auction_id>", views.add_watchlist, name="add_watchlist"), path("remwatchList/<int:auction_id>", views.rem_watchlist, name="rem_watchlist"), ] And the views.py file fragment where the errors occurs is this: @login_required def watchlist(request): u = User.objects.get(username=request.user) return render(request, "auctions/watchlist.html", { "watcher": u.watchingAuction.all() }) Assigning the "watcher" variable makes the application brake and show the error message. Can you please help me out? Where is the conceptual mistake? Thnkass -
How does Django handles multiple request
This is not a duplicate of this question I am trying to understand how django handles multiple requests. According to this answer django is supposed to be blocking parallel requests. But I have found this is not exactly true, at least for django 3.1. I am using django builtin sever. So, in my code(view.py) I have a blocking code block that is only triggered in a particular situation. It takes a very long to complete the request for this case. This is the code for view.py from django.shortcuts import render import numpy as np def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key def home(request): a = request.user.username print(a) id = int(request.GET.get('id','')) if id ==1: arr = np.arange(100000) arr = arr[::-1] insertionSort(arr) # print ("Sorted array is:") # for i in range(len(arr)): # print ("%d" %arr[i]) return render(request,'home/home.html') so only for id=1 it will execute the blocking code block. But for other cases, it is supposed to work normally. Now, what I found is, if I make two multiple requests, one with id=1 and another with id=2, second request … -
installation de mysqlclient sur mon site en production
Salut j'essaie d'installer mysqlclient sur mon site développé avec django en production ,sur un hébergement offrant un cpanel comme o2switch, mais j'y arrive pas. J'ai essayé le pip install mysqlclient et j'ai cette erreur mais j'ai une erreur : Failed to build mysqlclient. Après beaucoup j'ai trouvé une autre façon de faire avec les fichiers mysqlclient-1.4.6-cp38-cp38-win32.whl mais j'ai l'erreur suivante: ERROR: mysqlclient-1.4.6-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. Pouvez vous m'aider s'il vous plaît? Merci -
Deploy django app that uses docker run command
I have a Django app that I want to deploy on Heroku. The application calls the command docker run hello-world in views.py when the button is pressed. As far as I know, on Heroku you can set up a stack on Ubuntu or Docker. When I use Ubuntu, I install docker using heroku-buildpack-apt. Unfortunately I then get the following error: docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?. See 'docker run --help'. I tried using docker run -v /var/run/docker.sock:/var/run/docker.sock hello-world but to no effect. Aptfile uidmap iptables daemon apt-transport-https ca-certificates curl gnupg-agent software-properties-common http://security.ubuntu.com/ubuntu/pool/universe/d/docker.io/docker.io_19.03.8-0ubuntu1.20.04.1_amd64.deb When I try to dockerize the django app (and apply docker in docker), I have the same problem. I tested it locally. After typing django-compose up and clicking button, I get docker: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?. See 'docker run --help'. Dockerfile FROM python:3.8-buster ENV PATH="/scripts:${PATH}" ENV LD_LIBRARY_PATH=/usr/local/lib COPY ./requirements.txt /requirements.txt RUN apt-get update RUN pip install --upgrade pip RUN pip install -r /requirements.txt # install Docker RUN apt-get remove docker docker-engine docker.io runc RUN apt-get install -yq --no-install-recommends apt-utils RUN apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common RUN curl -fsSL … -
Django Ajax - Update table after submitting form
Good evening, inside my page there are two areas - one in which the form with the new data is submitted and a second one where all the entries should be displayed inside a table.. I'm still new to javascript, so I'm asking myself, wether it's possible to update the table with the new data after pressing the submit button (and without refreshing the whole page)!? models.py class AjaxTable(models.Model): first_name = models.CharField(max_length=25, null=False, blank=False) last_name = models.CharField(max_length=25, null=False, blank=False) age = models.IntegerField(default=0, validators=[MinValueValidator(1), MaxValueValidator(100)]) def __str__(self): return f"{self.first_name} {self.last_name}" views.py def javascript_ajax_table_update(request): qs_table = AjaxTable.objects.all() form = AjaxTableForm() data = {} if request.is_ajax(): form = AjaxTableForm(request.POST, request.FILES) if form.is_valid(): form.save() data['first'] = form.cleaned_data.get('first_name') data['last'] = form.cleaned_data.get('last_name') data['age'] = form.cleaned_data.get('age') data['status'] = 'ok' return JsonResponse(data) context = {'formset': form, 'qs_table': qs_table} return render(request, 'app_django_javascript/create/django_javascript_ajax_table_update.html', context) forms.py class AjaxTableForm(ModelForm): class Meta: model = AjaxTable fields = '__all__' template.html <div class="grid-container"> <div class="cnt-create"> <div class="card"> <div class="card-body"> <form action="" method="post" autocomplete="off" id="post-form" name="post-form"> {% csrf_token %} <div class="div-post-input-flex"> <div class="div-post-input"> <label>First Name</label><br> {{ formset.first_name }} </div> <div class="div-post-input"> <label>Last Name</label><br> {{ formset.last_name }} </div> <div class="div-post-input"> <label>Age</label><br> {{ formset.age }} </div> </div> <div class="div-post-input"> <button class="btn btn-success" type="submit"> Save </button> </div> </form> </div> … -
'RiskData' object has no attribute 'device_data_captured' using Python Braintree
For a Customer I created a project using Django. I implemented some RESTful API for Client's mobile apps. We integrated Braintree to have a Payments Gateway. Everything worked fine for years.. At the moment, the mobile apps haven't been updated for several months. Some mouths ago, Server side, we upgraded Python and Django version (as also Braintree SDK to the version 4.5.0) and inexplicably, from 2, 3 days the payments using credit cards getting in fails (using PayPal works fine. In theory, the money are withdrawn by the Customer cards but the flow mobile-server it's broken now so, server side, I'm not able to complete Braintree transaction flow. In particular, when I try to call this method to validate the transaction (as described into Braintree documentation) result = gateway.transaction.sale({ "amount": orderPrice, "order_id": str(order.uuid), "payment_method_nonce": nonce_payment, "customer": GatewayManager._generateCustomerInfo(order.owner), "options": { "store_in_vault_on_success": STORE_IN_VAULT_ON_SUCCESS, "submit_for_settlement": SUBMIT_FOR_SETTLEMENT, } }) I obtain this error: 'RiskData' object has no attribute 'device_data_captured' I'm not able to understand the reason... Why from some days it's broken? What's we missed or what's we need to do? -
Django And AJAX: Errors When Trying To Pass A List In POST Request
I am trying to pass a list to the view so that i can filter by that list. i have taken some ideas from another Stack Overflow question here which should be working but is giving me some errors. attempt 1 shown below prints as an empty array [] attempt 2 shown below gives error the JSON object must be str, bytes or bytearray, not NoneType the ajax code consol log error [1] so the list works there Here is the code view def find(request): Posts = Post.objects.all() genre_list = Genres.objects.all() if request.method == 'POST': #attempt 1 genres_selected_use = request.POST.getlist('genres_selected') # this when printed shows an empty array [] #attempt 2 #genres_selected_use = json.loads(request.POST.get('genres_selected')) # this gives error *the JSON object must be str, bytes or bytearray, not NoneType* for arg in genres_selected_use: Posts = Posts.filter(genres=arg) print(genres_selected_use) #return redirect('find') context = { 'products': Posts, 'keyword_list': Keywords.objects.all(), } return render(request, 'find/find.html', context) AJAX $('.filter_form').submit(function(e){ const url = $(this).attr('action') var genres_selected_initial = []; var genre_item = document.getElementById(`filter_idAction`); var genres_selected_id = $(genre_item).attr('value'); var g = parseInt(genres_selected_id) if (genre_item.classList.contains("clicked_filter")) { genres_selected_initial.push(g); } //var genres_selected = genres_selected_initial; //attempt 1 var genres_selected = JSON.stringify(genres_selected_initial); //attempt 2 $.ajax({ type: 'POST', url: url, data: { 'genres_selected': genres_selected, }, … -
Email activation in class based view
I'm trying to register users but not making them active until they activate their accounts withe the email activation link but.. I get a 'UserBase' object has no attribute 'email_user' error and when changing it to 'email' instead of 'user_email' i get a 'str' object is not callable error I get the activation link from the error page and it works when trying it on another tab (makes account active) but it also gives me a The view account.views.account_activation didn't return an HttpResponse object. It returned None instead. error View: class UserReigster(CreateView): model = UserBase form_class = Registration template_name = 'account/registration/registration.html' success_url = '/' def form_valid(self, form): user = form.save() # Email Activation Setup current_site = get_current_site(self.request) subject = 'Activate Your Account' message = render_to_string('account/registration/account_activation_email.html', { 'user':user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) # Success registration message messages.add_message( self.request, messages.SUCCESS, 'Check Your Email For Account Activation Link' ) return super().form_valid(form) def account_activation(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except(): pass if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) else: return render(request, 'account/registration/activation_invalid.html') models: class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is … -
Django form doesn't send data
I am trying to add a user to some events in the calendar (using fullcalendar), but when putting the form to request the data from the user, this form does not send me the data. How can I get the data it is supposed to send? This is my event_register.html: <div class="col-xl-6"> <p>Apuntarse como invitado.</p> <form action="" method="POST"> {% csrf_token %} <div class="form-group"> <label for="first_name">Nombre:</label> <!--<input id="first_name" name="first_name" placeholder="Nombre del participante" type="text" required="required" class="form-control">--> <div class="input-group"> {{form.first_name}} </div> </div> <div class="form-group"> <label for="last_name">Apellidos:</label> <!--<input id="last_name" name="last_name" placeholder="Apellidos del participante" type="text" required="required" class="form-control">--> <div class="input-group"> {{form.last_name}} </div> </div> <div class="form-group"> <label for="phone">Teléfono:</label> <!--<input id="phone" name="phone" placeholder="Teléfono del participante" type="text" required="required" class="form-control">--> <div class="input-group"> {{form.phone}} </div> </div> <div class="form-group"> <label for="email">Correo electrónico:</label> <!--<input id="email" name="email" placeholder="Correo electrónico del participante" type="text" required="required" class="form-control">--> <div class="input-group"> {{form.email}} </div> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-block py-2" value="Enviar"> </div> </form> </div> <div class="col-xl-6"> </div> This is my view.py: def attend_to(request): event_form = EventForm() print('Hola') if request.method == 'POST': event_form = EventForm(data=request.POST) if event_form.is_valid(): Assistant.objects.create(UserManegement=None, Event=request.event_id, frist_name=request.POST["first_name"], last_name=request.POST["last_name"], phone=request.POST["phone"], email=request.POST["email"]) return render(request, "core/home.html") else: Assistant.objects.create(UserManegement=request.POST["user"], Event=request.POST["event"]) return render( "core/home.html") This is my forms.py: from django import forms class EventForm(forms.Form): first_name = forms.CharField(label="first_name", required=True, widget=forms.TextInput( attrs={'class':'form-control', … -
How to use ElasticSearch with Django
I have written an article on "How to use ElasticSearch with Django". Requesting you to please go through it and provide your valuable feedback. Thanks in advance -:) Link: https://hiteshmishra708.medium.com/how-to-use-elasticsearch-with-django-ff49fe02b58d -
TypeError: cannot unpack non-iterable Race object
I know it seems like a stupid quotation but I truly cant find an answer. I dont know where my problom is in my code, the only thing I do know is that I ran the site, and when i insert an object of type Race, I couldnt run the site anymore, i checked the database and it was added as it should. when I checked the error in the internet i couldnt find an answer because all of the answers dont include an answer about a Foregin key. Here is the Traceback: Traceback (most recent call last): File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 48, in … -
React Forms and axios
I have a Django REST api that I am consuming the POST endpoint in React using Axios. Here is my React code: class FormComponent extends React.Component{ constructor(props){ super(props); this.state = { shipment: { requestType: "" } }; this.handleChange = this.handleChange.bind(this); this.handleFormSubmission = this.handleFormSubmission.bind(this); } submitRequest = (event) =>{ axios.post("http://localhost:8000/app/shipments/create/", this.state.shipment) .then((data) =>{ console.log(data); }).catch((error) =>{ console.log(error); }); } handleChange(event){ //selecting shipment from the state const request = this.state.shipment; //updating the shipment keys and values request[event.target.name]= event.target.value //setting the state this.setState({shipment: request}); console.log("Input change detected") } handleFormSubmission(event){ event.preventDefault(); console.log("Submitted Successfully!"); console.log(this.state.shipment); } render() { return ( <form className="parent-container" onSubmit={this.handleFormSubmission}> <select className="quoteOrLabel" name="quoteOrLabel" value={this.state.shipment.requestType} onChange={this.handleChange} placeholder="Request Type" required> <option>Quote</option> <option>Label</option> </select> </form> ); } My Questions are: *1) I want the value of requestType in the state in the constructor of the class to change whenever the user selects an option from the dropdown menu tag ? My other question is in Google Chrome browser, when I click on submit button, I see that the data gets submitted, but it does not get passed into Django REST api POST endpoint using axios, what is the reason behind that?* -
Get The Title Of An MP3 File After It Has Been Uploaded By Django
I set up an upload form in Django and everything is working perfectly fine. I was just wondering how to access the title of an mp3 file after it has been uploaded, however. I will be allowing users to upload audio tracks and would like to automatically generate the song titles instead of having the users type them in themselves. Any assistance on this is greatly appreciated! -
Navigation to BBDD
I have a program on AppFolder and need acces to BBDD of django, how can I point to the root folder? Is what I do for a website okay? Best Regards. -
How deploy Django Project with Bitbucket Pipelines and AWS Elastic Beanstalk?
I have a django project running perfect in AWS Elastic Beanstalk in awsgi mode. I want add an pipeline from Bitbucket to simplify deploy process. bitbucket-pipelines.yml image: atlassian/default-image:2 pipelines: default: - step: name: "Build and Test" script: - echo "Everything is awesome!" - apt-get update - apt-get install -y zip - zip application.zip application/* - pipe: atlassian/aws-elasticbeanstalk-deploy:0.5.0 variables: AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION S3_BUCKET: $S3_BUCKET APPLICATION_NAME: $APPLICATION_NAME ENVIRONMENT_NAME: $APPLICATION_ENVIRONMENT COMMAND: 'upload-only' ZIP_FILE: 'application.zip' artifacts: - application.zip - step: name: "Deploy to Production" deployment: production script: - echo "Deployment to Production!" - pipe: atlassian/aws-elasticbeanstalk-deploy:0.5.0 variables: AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION APPLICATION_NAME: $APPLICATION_NAME ENVIRONMENT_NAME: $APPLICATION_ENVIRONMENT COMMAND: 'deploy-only' WAIT: 'true' I make a new folder called application and put all my Django project inside. Bitbucket pipelines works fine but show 502 error. -
I did deploy a project in django using google cloud platform and I have 502 Bad Gateway nginx
It is the first time that I use google cloud platform and I don't know much about this, I did my first deployment of the project and it worked correctly, but the second time I did deployment it did not appear And when I run it locally it works This is my settinggs.py file: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # SECURITY WARNING: App Engine's security features ensure that it is safe to # have ALLOWED_HOSTS = ['*'] when the app is deployed. If you deploy a Django # app not on App Engine, make sure to set an appropriate host here. # See https://docs.djangoproject.com/en/2.1/ref/settings/ ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_userforeignkey', 'applications.pruebapdf', 'applications.home', 'applications.inventario', 'applications.factura', 'applications.compra_proveedor', 'applications.api' ] 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', 'django_userforeignkey.middleware.UserForeignKeyMiddleware', ] ROOT_URLCONF = 'mysite.urls' This is the configuration of my app.yaml file: runtime: python39 handlers: # This configures Google App Engine to serve the files in the app's static # directory. - url: /static static_dir: static/ # This handler routes all requests not caught above to your main app. It is # …