Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getiing an AttributeError at /pay/ 'str' object has no attribute 'get' while trying to render another view
//models.py from django.db import models class CustomerInfo(models.Model): full_name = models.CharField(max_length = 150) email = models.EmailField() phone = models.CharField(max_length = 150) def __str__(self): return self.email //the code from my views.py from .forms import CustomerInfoForm def customer_info(request): if request.method == 'POST': customer_form = CustomerInfoForm(request.method) if customer_form.is_valid() and customer_form.cleaned_data: customer_form.save() return render(request, 'pay/payment.html', {'email': customer_form.email}) else: return HttpResponse('invalid input try again') else: customer_form = CustomerInfoForm() return render(request, 'pay/customer_info.html', {'customer_form':customer_form}) -
Django return none when y try to save in vars by POST method
I'm trying to save the data from a form by POST method. When i try to save in vars at views.py it put inside none here i show important parts of my code: add.html: <form method="POST"> {% csrf_token %} <h5>AÑADIR PEDIDO</h5> <div class="form-group"> <label for="cliente">Nombre del Cliente</label> <input type="text" class="form-control" id="cliente" placeholder="pepito" /> </div> <div class="form-group"> <label for="producto">Codigo del Producto</label> <select class="form-control" id="producto"> {% for cantidades in cantidad_pedido %} <option value="{{cantidades.Cproducto}}"> {{cantidades.Cproducto}} </option> {% endfor %} </select> </div> <div class="form-group"> <label for="cantidad">Cantidad de dicho producto</label> <input type="number" class="form-control" id="cantidad" placeholder="cantidad" /> </div> <button type="submit" class="btn btn-dark" style="margin-bottom: 1%;">Añadir!</button> </form> models.py: class Stock(models.Model): Cproducto = models.CharField(max_length=50, primary_key=True) cantidad = models.IntegerField() class Pedido(models.Model): Cpedido = models.CharField(max_length=50, primary_key=True) Ccliente = models.CharField(max_length=50) FechaPedido = models.DateField(default=datetime.now) class detallePedido(models.Model): Cpedido = models.ForeignKey(Pedido, on_delete=models.CASCADE) Cproducto = models.ForeignKey(Stock, on_delete=models.CASCADE) Cantidad = models.IntegerField() views.py : def add(request): cantidad_pedido = Stock.objects.all() if request.POST: client = request.POST.get('cliente') producto = request.POST.get('producto') cantidad = request.POST.get('cantidad') stock_producto = Stock.objects.get(Cproducto=producto) if(cantidad > stock_producto.cantidad): messages.error(request, 'Error, la cantidad es mayor') return render(request, 'add.html', {'cantidad_pedido': cantidad_pedido}) and here one picture of the vars: -
CSRF verification failed when logging into admin panel
In production my app is giving me CSRF verification failed when I log into my admin panel. I have the following in my settings.py: 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', ] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True As my site doesn't currently have an SSL certificate I have ignored the following after running python manage.py check --deploy: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. -
page not found when making new url / view Django
Hello i am trying to add a basic url called localhost:8000/shop so that when i am on my homepage, I can click a link called shop and It will lead me to localhost:8000/shop in my urls.py i added from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from homepage import views urlpatterns = [ path('' , views.home), path('admin/', admin.site.urls), path('reviews/' , include('reviews.urls')), path('shop/' , include('product.urls')), ] in my folder called product i have a urls.py file with from django.urls import include, path from . import views urlpatterns = [ path('shop/' , views.shop), ] and in my product folder i have a views.py file with from django.shortcuts import render # Create your views here. def shop(request): return render(request, 'product/shop.html') linking It to my html file inside my product folder.. when i run the server, I get this error message Page not found (404) Request Method: GET Request URL: http://localhost:8000/shop Using the URLconf defined in yorleico.urls, Django tried these URL patterns, in this order: admin/ reviews/ shop/ The current path, shop, didn't match any of these. What am i doing wrong?! -
Why is any jwt authenticating the user in djangrestframework_simplejwt?
I am implementing jwt token authentication method using djangoreostframework_simplejwt module. It seemed to be working normally, but I decided that there was no problem with putting jwt in the header that was not issued by my server and passed it. I wonder if this is the problem of my server, this module or the inevitable problem of jwt. Can anyone give me an answer? -
File Upload Multiple Change On Input Gives Unexpected Results
I wrote a fileupload handler in JavaScript to send multiple files using formdata to django. The script works as expected if the user sends multiple files to the server using the input. However, if the user sends multiples files, and then tries to send multiple files BEFORE the last input (of multiple files) has finished, then the program gives unexpected results. Can anyone explain why? Possible solutions: change loop indices create some type of fileupload queue (which I think I already somewhat implemented) disable the input button until the first round of uploads is done processing (last resort) var uploadcount = 0; var folderuploadsinprogress = 0; var uploadfinished = 0; var uploadscanceled = 0; var uploadsize = 0; var fdata = new FormData(); var datalist = []; var xhrcancel = new Set() var xhr; $("#uploadstop").click(function(e){ if(xhrfolder){ xhrfolder.abort(); $("#fu").css("display","none"); return; } xhr.abort(); for(let i=uploadfinished+1; i<uploadcount; i++){ xhrcancel.add(i); } datalist = []; uploadcount = 0; fdata = new FormData(); return; }); function cancelupload(thisid){ console.log('cancel upload ',thisid); console.log('cancel upload finished ',uploadfinished); $("#"+thisid).css("display","none"); //check if canceled upload is a folder if(uploadfinished+uploadscanceled == thisid){ //cancel current upload console.log('cancel current'); if($("#"+thisid).hasClass("folder")){ console.log('has class folder'); xhrfolder.abort(); }else{ console.log('does not have class folder'); xhr.abort(); } uploadscanceled++; $("#"+thisid).css("display","none"); console.log('dl … -
How to set environment variable DJANGO_SETTINGS_MODULE
I've bee trying to send a pandas dataframe to the django database, though when I try this: user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] # host = settings.DATABASES['default']['HOST'] # port = settings.DATABASES['default']['PORT'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) I get this: ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What could I do to fix this? thanks -
Django 1 parent table that contains 2 children models, instead of creating 2 children tables
I have three models as following: class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="%(class)ss") timestamp = models.DateTimeField(default=timezone.now) amount = models.IntegerField(null=False) class Meta: abstract = True class Income(Transaction): INCOME_CATEGORIES = [ ("YEARLY", "Yearly"), ("MONTHLY", "Monthly"), ("ONETIME", "One-time"), ] category = models.CharField(max_length=9, choices=INCOME_CATEGORIES, null=False) class Expense(Transaction): EXPENSE_CATEGORIES = [ ("LUXURY", "Luxury"), ("ESSENTIAL", "Essential"), ] category = models.CharField(max_length=9, choices=EXPENSE_CATEGORIES, null=False) can_be_cheaper = models.BooleanField(default=False) But this creates 2 tables for Income and Expense models. I want to have 1 table called Transaction that'll contain these child models in it, is this possible? -
How do I do a Django query filter that matches against a list of values?
Hey guys I'm doing a small social media app and right now I'm having trouble figuring out how to display the posts of users someone is following. Right now I create a list that adds all of the usernames to it as values. How can I filter out the Django query results where it prints out all the results of those contained in the list? I can do it where it prints out only one of the followers posts, since I can compare one value easily. But how can I do the same when I need to compare to a list of values? Any ideas? Thanks guys. Below is my code: def follows(request, username): # create list list = [] # get the username of the signed in user userSearch = User.objects.get(username = username) # get the user ID of the signed in user userID = userSearch.id # get the user IDs of the followers of the signed in user query = Follow.objects.filter(follower_id = userID) #get the usernames of the followers of the signed in user query2 = User.objects.filter(id = query[0].following_id) #add the usernames to a list for i in query: list.append(i.following_id) query3 = NewPost.objects.filter(username = query2[0].username) paginator = Paginator(query3, … -
Using formsets to upload many files to a record, it isn't quite working
I have used as many examples online as I could cobble together in an attempt to get my two simple models: class Technical_Entry(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ema = models.ForeignKey(EMA, on_delete=models.CASCADE) system = models.ForeignKey('System', on_delete=models.CASCADE) # are SYSTEMS RELATED TO SUBSYSTEMS OR JUST TWO GROUPS? sub_system = models.ForeignKey(SubSystem, on_delete=models.CASCADE) drawing_number = models.CharField(max_length=200) drawing_title = models.CharField(max_length=255) engineer = models.CharField(max_length=200) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) date_drawn = models.DateField() ab = models.BooleanField() class Technical_Entry_Files(models.Model): tech_entry = models.ForeignKey(Technical_Entry, on_delete=models.CASCADE) file = models.FileField(upload_to='techdb/files/') def __str__(self): return self.tech_entry.drawing_number To upload using a formset. While the page 'displays' mostly correctly, it flat out does not create the record in the Technical_Entry_Files model. Relevant forms.py: class FileUploadForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FileUploadForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-4' self.helper.field_class = 'col-lg-8' class Meta: model = Technical_Entry_Files fields = ('file',) TechFileFormSet = inlineformset_factory(Technical_Entry, Technical_Entry_Files, form=FileUploadForm, extra=1) class Technical_EntryForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(Technical_EntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-4' self.helper.field_class = 'col-lg-8' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = Technical_Entry fields = ('category', 'ema', 'system', 'sub_system', 'drawing_number', 'drawing_title', 'engineer', 'vendor', 'date_drawn', 'ab') widgets = { 'date_drawn':DateInput(attrs={ 'class':'datepicker form-control', 'id' : 'datetimepicker2', 'tabindex' : '1', 'placeholder' : 'MM/DD/YYYY hh:mm', 'autocomplete':'off', }, format='%m/%d/%Y'), … -
Getting really strange error when deploying a django app on Heroku
I tried to deploy my django application to heroku using the starter guide and the other manual that shows you to create your runtime, requirements, procfiles, installing django-heroku, etc. So I've now deployed my site but recieve the following error.My error I'm unsure of why this error is showing up at all especially when it worked perfectly fine locally. I haven't followed all of the django deployment checklist yet, such as setting DEBUG to False because I'd like to ensure that it works correctly before I do. If anyone could help me, that'd be much appreceiated! -
Django get children of parent on parent detail page
I'm trying to get access to the children of a model and list them on the parents details page. Here is how I have it set up... Models: class Destination(models.Model): title = models.CharField( null=True, max_length=60, blank=True) featuredimage = models.ImageField(null=True, blank=True, upload_to ='media/') location = PlainLocationField(based_fields=['title'], zoom=7, null=True, blank=True) class Airport(models.Model): title = models.CharField( null=True, max_length=60, blank=True) city = models.ForeignKey(Destination, null=True, blank=True, on_delete=models.SET_NULL) Views: def destination_detail(request, slug): destination = Destination.objects.get(slug=slug) context = { 'destination': destination, 'airport': Airport.objects.filter(city = destination.id), } return render(request,"destination/detail.html",context) Template: <h1> {{ airport.title }} </h1> It doesn't throw an error or anything but nothing is displayed. I have everything imported and set up correctly, I think I'm just missing on how to properly set it up in my views. Any insight would be greatly appreciated. -
Django template breaking model value string at space
I have the following HTML template in Django: <select name="store" id="store_select"> <option>Search by Store</option> {% for store in stores%} <option value= {{store.store_name}} >{{store.store_name}}</option> {% endfor %} </select> However, it renders the following: <select name="store" id="store_select"> <option>Search by Store</option> <option value= "Best" buy >Best buy</option> <option value= "Costco" >Costco</option> <option value= "Staples" >Staples</option> </select> How do I make it render "Best buy" and not "Best" buy ? TIA -
Django-templated-email does not send email
I am using the following package https://github.com/vintasoftware/django-templated-email in a Django app to try and send an email. I am running it inside a django management command. When I run the command the email part outputs to the console but no email is actually sent out. The SMTP settings and such are correct as emails work fine for other areas of the application. from templated_email import send_templated_mail send_templated_mail( template_name='welcome', from_email='from@example.com', recipient_list=['to@example.com'], context={ 'username':"test", 'full_name':"test", 'signup_date':"test" }, ) Any help is appreciated. I suspect I have misunderstood the syntax of the package. -
Django3: How to display the results of a model function into an HTML template and/or Admin
So I have the following Classes one for user and one for "Project": class CustomUser(AbstractUser): pass class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=6, decimal_places=2, editable=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) def monthlyTotal(self,user): this_month = now().month return Project.objects.filter( created__month=this_month, user=user ).aggregate( sum_total=Sum('total') )['sum_total'] def __str__(self): return self.name and my view which is also used to populate the Project Class: def homepage(request): if request.method == "POST": project = Project() name = request.POST.get('name') total = request.POST.get('total') created = datetime.datetime.now() user = request.user project.user = user project.name = name project.total = total project.created = created project.save() #return HttpResponse(reverse("homepage.views.homepage")) return render(request, 'homepage.html') else: return render(request, 'homepage.html') I would like to pass the currently logged in user to the function monthlyTotal so that it displays on my template. This is what I tried so far <p>Total monthly sales = {{ Project.monthlyTotal(user.username) }}</p> <p>Total monthly sales = {{ Project.monthlyTotal(request.user) }}</p> but can't get it to work, also would I be able to display this field in the admin so you see it when you look at a user admin portal? Thanks -
Update A Profile Picture In Django ImageField : Dynamic Method Used In Django Admin
My Application has a system where user can upload his profile pic. I created this feature later so used the foreignkey method this is the model class Profile_Pic(models.Model): user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic') profile_pic = StdImageField(upload_to='photos', default='', blank=True, ) and the html page {% extends 'datas/base.html' %} {% block content %} {% load static %} <h1 class="text-center" style="color: white">Add Profile Picture</h1> <br><br> <div class= "col-md-6.offset-md-3"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissable" role="alert"> <button class="close" data-dismiss="alert"> <small><sup>x</sup></small> </button> <p>Data Error, Please Check Again.....</p> {% for field in form %} {% if field.errors %} {{ field.errors }} {% endif %} {% endfor %} </div> {% endif %} {{ form.as_p }} <input type="submit" value="Save" class="btn btn-primary"> </form> </div> {% endblock %} the view @login_required def profile_pic(request): if request.method == 'POST': form = Photo(request.POST, request.FILES) if form.is_valid(): form.instance.user = request.user form.save() messages.success(request, 'Your Profile Picture Has Been Updated Successfully') return redirect('profile') else: form = Photo() return render(request, 'datas/user_image.html', {'form': form}) and finally the form class Photo(forms.ModelForm): class Meta: model = Profile_Pic fields = ['profile_pic'] widgets = { 'Add Profile Pic': forms.FileInput(attrs={'class': 'form-control'}), } Now when we upload from the admin site,the system automatically deletes … -
Braintree hosted fields not appearing when using server side generated client token
I'm using the hosted fields example from braintree: https://developers.braintreepayments.com/guides/3d-secure/client-side/javascript/v3 Inside their javascript there is a function which calls: https://braintree-sample-merchant.herokuapp.com/client_token function getClientToken() { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 201) { onFetchClientToken(JSON.parse(xhr.responseText).client_token); } }; xhr.open("GET", "https://braintree-sample-merchant.herokuapp.com/client_token", true); xhr.send(); } I substitute that endpoint with my own, which generates my client token using the settings I got from braintree sandbox. #settings.py from braintree import Configuration, Environment Configuration.configure( Environment.Sandbox, BT_MERCHANT_ID, BT_PUBLIC_KEY, BT_PRIVATE_KEY ) #views.py import braintree def return_client_token(request): return JsonResponse({ "client_token": braintree.ClientToken.generate() }) My endpoint returns the client token, but when I use it, the hosted fields do not materialize. The length of the key from the Braintree's example endpoint is 3664, whereas my is 2364. -
Is there a django package which locks certain objects / records?
How to prevent a user from editing an object / record already being edited from another? Obviously this would be easy enough to design myself. I guess I would want a model a bit like the ContentType model. A column for appname, a column for model, a column for primary key, and a column for the user currently editing the record. Whenever somebody requests a URL the software checks this table to see if another is already editing the record. If there is, this user would see a message like "Record currently being edited by user ..." Is there a package which does this to save me the effort? To be clear I'm not talking about locking the row at the SQL level or Django auth permissions. -
How to make a django field choosable
I need to define one field of my django model in a way that takes either X/Z, True/False or 0/1. I mean when I select one checkbox I expect be able to choose just one checkbox not both together(Like select between Yes or No) and after submit I see one of those mentioned values in the database table field. What I have tried so far: class Post(models.Model): STATUS = Choices( (1, 'x', ('select X')), (2, 'z', ('Select Z')) ) action_style = models.CharField( max_length=32, choices=STATUS, default='x' ) and in form: class Postform(forms.ModelForm): STATUS = Choices( (1, 'x', ('select X')), (2, 'z', ('Select Z')) ) status = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, required=False, choices=STATUS ) class Meta: model = Post fields = ['status'] and in template: <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.status }} <input type="submit" value="submit"/> </form> -
Django object of type 'method' has no len()
I just added pagination to a ListView in Django, but it is returning object of type 'method' has no len() error, even though I am overriding the get_queryset method and it is not returning anything different from the queryset. The view causing the error looks like this: class ProductList(ListView): paginate_by = 10 model = Product context_object_name = 'products' template_name = 'catalog/product/product_list.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def queryset(self): categories = Category.objects.filter(company=self.request.user.profile.company) return Product.objects.filter(category__in=categories) def get_context_data(self, **kwargs): context = super(ProductList, self).get_context_data(**kwargs) context['customers'] = Customer.objects.filter(company=self.request.user.profile.company) context['categories'] = Category.objects.filter(company=self.request.user.profile.company) return context How am I supposed to paginate with an overriden queryset without it showing this error? -
How can group this relations on Django Rest Framework
Currently, I've the next models: class Variant(models.Model): name = models.CharField('name', max_length=60) class VariantValue(models.Model): value = models.CharField('value', max_length=60) variant = models.ForeigKey('variant', to=Variant, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField('name', max_length=60) I want to get the next json result: { "name": "My product", "variants": [ { "variant_id": 1, "values": ["Value 1", "Value 2", "Value 3"] }, { "variant_id": 2, "values": ["Value 4", "Value 5", "Value 6"] }, ] } It's possible with a Serializer or do I've to make the json manually? I just have the next ModelSerializer: class ProductModelSerializer(serializers.ModelSerializer): variant_list = serializers.SerializerMethodField('get_variant_list', read_only=True) class Meta: model = Product fields = [..., 'variant_list'] def get_variant_list(self, obj): variant_list = VariantValue.objects.filter(product_id=obj.id) variant_list_grouped = variant_list.values('variant', 'value').annotate(count=Count('variant')) res = [] for variant in variant_list_grouped: pass return [] Thanks! -
MultiValueDictKeyError at /signup/ 'password11'
I'm trying to signup user but getting some weird error. please help me to solve it This is my view file with the function named signup def signup(request): if request.method=='POST': username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password11 = request.POST['password11'] if password1==password11: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('/account') elif User.objects.filter(email=email).exists(): messages.info(request,'Email Taken') return redirect('/account') else: user=User.objects.create_user(username=username, password=password1, email=email) user.save(); auth.login(request,user) print('user created') else: messages.info(request,'Password not Matching') return redirect('/account') return redirect('/') else: return render(request,'account.html') And this is my signup file. I've save file with the name account.html. <form id="regform" style="margin-top: -40px;" action="/signup/" method="post"> {% csrf_token %} <input type="text" placeholder="Username" name="username"> <input type="email" placeholder="Email" name="email"> <input type="password" placeholder="Password" name="password1"> <input type="password" placeholder="Confirm Password" name="Password11"> <button type="submit" id="btn2">Register</button> <div> {% for message in messages %} <h6>{{message}}</h6> {% endfor %} </div> </form> -
docker-compose.yml for production - Django and Celery
I'm looking to deploy a simple application which uses Django and celery. docker-compose.yml: version: "3.8" services: django: build: . container_name: django command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app/ ports: - "8000:8000" environment: - DEBUG=1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=djcelery.backends.database:DatabaseBackend depends_on: - redis celery: build: . command: celery -A core worker -l INFO volumes: - .:/usr/src/app environment: - DEBUG=1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=djcelery.backends.database:DatabaseBackend depends_on: - django - redis redis: image: "redis:alpine" volumes: pgdata: Dockerfile: FROM python:3.7 WORKDIR /app ADD . /app #Install dependencies for PyODBC RUN apt-get update \ && apt-get install unixodbc -y \ && apt-get install unixodbc-dev -y \ && apt-get install tdsodbc -y \ && apt-get clean -y # install ODBC driver in docker image RUN apt-get update \ && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \ && curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list \ && apt-get update \ && ACCEPT_EULA=Y apt-get install --yes --no-install-recommends msodbcsql17 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* \ && rm -rf /tmp/* # install requirements RUN pip install --trusted-host pypi.python.org -r requirements.txt EXPOSE 5000 ENV NAME OpentoAll CMD ["python", "app.py"] Project Directories: When I run "docker-compose up" locally, the celery worker is run and I am able to go to localhost:8000 to … -
Django - 404 static in Docker on react app
I have backend on Django and storefront/dashboard on React. Django in docker container. Dockerfile (Django) ### Build and install packages FROM python:3.8 as build-python RUN apt-get -y update \ && apt-get install -y gettext \ # Cleanup apt cache && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements_dev.txt /app/ WORKDIR /app RUN pip install -r requirements_dev.txt ### Final image FROM python:3.8-slim RUN groupadd -r saleor && useradd -r -g saleor saleor RUN apt-get update \ && apt-get install -y \ libxml2 \ libssl1.1 \ libcairo2 \ libpango-1.0-0 \ libpangocairo-1.0-0 \ libgdk-pixbuf2.0-0 \ shared-mime-info \ mime-support \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN mkdir -p /app/media /app/static \ && chown -R saleor:saleor /app/ COPY --from=build-python /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=build-python /usr/local/bin/ /usr/local/bin/ COPY . /app WORKDIR /app ARG STATIC_URL ENV STATIC_URL ${STATIC_URL:-/static/} RUN SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic --no-input EXPOSE 8000 ENV PYTHONUNBUFFERED 1 CMD ["gunicorn", "--bind", ":8000", "--workers", "4", "--worker-class", "uvicorn.workers.UvicornWorker", "saleor.asgi:application"] When I go to the Dashboard and access objects with pictures, I get error: error on Dashboard Thanks for help me! -
Fill list using Counter with 0 values
Is possible to have a count of how many times a value appears in a given list, and have '0' if the item is not in the list? I have to use zip but the first list have 5 items and the other one created using count, have only 3. That's why I need to fill the other two position with 0 values.