Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: The view videos.views.add_comment_post didn't return an HttpResponse object. It returned None instead in Django
I tried to add comments with the post and it raise this error, and I supmit my comment using ajax but it seems the problem coming from the view but I couldn't figure out what exactly the problem My add comments View @login_required def add_comment_post(request): comment_form = PostCommentForm(request.POST) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) user_comment.author = request.user user_comment.save() result = comment_form.cleaned_data.get('content') user = request.user.username return JsonResponse({'result': result, 'user': user}) My comment Model class PostCommentIDF(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children') author = models.ForeignKey(Account, on_delete=models.CASCADE) content = models.TextField() publish = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) likes = models.ManyToManyField(Account, blank=True, related_name='pos_com') class MPTTMeta: order_insertion_by = ['-publish'] def __str__(self): return f'{self.author}---{self.content[:15]}' My form for the comments class PostCommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = PostCommentIDF fields = {'post', 'content'} widgets = { 'content': forms.Textarea(attrs={'class': 'rounded-0 form-control', 'rows': '1', 'placeholder': 'Comment', 'required': 'True'}) } def save(self, *args, **kwargs): PostCommentIDF.objects.rebuild() return super(PostCommentForm, self).save(*args, **kwargs) the comments form in the template <form id="Postcommentform" class="Postcommentform" method="post" style="width: 100%;"> {% load mptt_tags %} {% csrf_token %} <select class="d-none" name="video" id="id_video"> <option value="{{ video.id }}" selected="{{ video.id }}"></option> </select> <div class="d-flex"> <label class="small font-weight-bold">{{ comments.parent.label }}</label> {{ comment_form.parent }} {{comments.content}} <button … -
Implementation of Nginx Container for Reverse Proxying and SSL certificates for Django Containers inside Docker Swarm
I want to deploy Django Application with Docker Swarm. I was following this guide where it does not use the docker swarm nor docker-compose, and specifically created two Django containers, one Nginx container, and a Certbot container for the SSL certificate. The Nginx container reverse proxy and load balance across the two Django containers which are in the two servers using their IPs upstream django { server APP_SERVER_1_IP; server APP_SERVER_2_IP; } server { listen 80 default_server; return 444; } server { listen 80; listen [::]:80; server_name your_domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name your_domain.com; # SSL ssl_certificate /etc/letsencrypt/live/your_domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/your_domain.com/privkey.pem; ssl_session_cache shared:le_nginx_SSL:10m; ssl_session_timeout 1440m; ssl_session_tickets off; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off; ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384"; client_max_body_size 4G; keepalive_timeout 5; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } location ^~ /.well-known/acme-challenge/ { root /var/www/html; } } I want to implement all this same functionality but with Docker Swarm so that I can scale the containers with one command docker service update --replicas 3 <servicename> The problem is I am not able to understand How to use implement the Nginx container in this scenario, Docker Swarm … -
The gunicorn server of the blog system deployed on EKS becomes "WORKER TIME OUT"
We are migrating the blog system that was previously deployed on EC2 to the AWS EKS cluster. On EC2 of the existing system, it operates in two containers, a web server (nginx) container and an AP server (django + gunicorn) container, and can be accessed normally from a browser. So, when I deployed it to the node (EC2) on AWS EKS in the same way, I could not access it from the browser and it was displayed as "502 Bad Gateway". The message "TIMEOUT (pid: 18294)" is displayed. We are currently investigating the cause of this, but the current situation is that we do not know. If anyone has any idea, I would appreciate it if you could teach me. gunicorn of log・status root@blogsystem-apserver01:/# systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Sun 2021-05-09 08:57:19 UTC; 5 days ago Main PID: 18291 (gunicorn) Tasks: 4 (limit: 4636) Memory: 95.8M CGroup: /kubepods/besteffort/podd270872c-cc5b-4a3b-92ed-f463ee5f5d77/1eafc79ffd656ff1c1bc39175ee06c7a5ca8692715c5e2bfe2f979d8718411ba/system.slice/gunicorn.service ├─18291 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/socket/myproject.sock myproject.wsgi:a pplication ├─18295 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/socket/myproject.sock myproject.wsgi:a pplication ├─18299 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/socket/myproject.sock myproject.wsgi:a pplication └─18300 /home/ubuntu/python3/bin/python /home/ubuntu/python3/bin/gunicorn --access-logfile - … -
launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} -Error While Creating Django Project
When I tried to create Django project in virtual Environment, I am getting below Error, C:\Users\new\Desktop\Desktop Files\Django Projects>activate myDjangoEnv (myDjangoEnv) C:\Users\new\Desktop\Desktop Files\Django Projects>django-admi n startproject first_project Traceback (most recent call last): File "C:\Users\new\anaconda3\envs\myDjangoEnv\lib\site-packages\django\apps\config.py", line 7, in from django.utils.deprecation import RemovedInDjango41Warning File "C:\Users\new\anaconda3\envs\myDjangoEnv\lib\site-packages\django\utils\deprecation.py", line 5, in from asgiref.sync import sync_to_async File "C:\Users\new\anaconda3\envs\myDjangoEnv\lib\site-packages\asgiref\sync.py", line 114 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax Please help me on this.Thanks in advance -
parse multiple values to user_passes_test in a function-based view
I have a function-based view #views.py def my_view(request,pk): post = Posts.get(pk) . . . return redirect("my-view") I want to make sure, that the user created the post, also is the one approaching the page. In the class-based update-view we can define the test_func class MyPosts(UserPassesTestMixin): def test_func(self): """ Check if the logged in user is the one created the link """ post= self.get_object() #Gets the current post if self.request.user == post.user: return True return False but I cannot figure out how to parse the post argument (or the post.user) to the user_passes_test function in the function-based view. According to the documentation the user_passes_test decorator has to take a function which takes a User argument as the first arguemnt and two optional arguments - and I need to parse both the User and the post-user i.e two user objects and not 1 e.g something like def my_test_func(User,post-user): if User==post-user: return True return False How do I accomplish this w/o using a Class-based view as described above? -
How to call python api from android?
I want to make login app in android which should call python api for matching username and password in database. I know how to call php api but don't know calling python api. Can anyone please help me! -
when i am trying to add post then add successfully but it is not show in dashboard it is show only home page what i do for show post in dashboard
when i am add post then add successfully but it is not show in dashboard it is show only home page what i do to add post in dashboard please help me login code def user_login(request): if not request.user.is_authenticated: if request.method == "POST": form = LoginForm(request=request, data=request.POST) if form.is_valid(): uname = form.cleaned_data['username'] upass = form.cleaned_data['password'] user = authenticate(username=uname, password=upass) if user is not None: login(request, user) messages.success(request, 'Login Successfully !!') return HttpResponseRedirect('/dashboard/') else: form=LoginForm() else: return HttpResponseRedirect('/dashboard/') return render(request, "login.html", {'form':form} ) Sign UP code def user_signup(request): if request.method =="POST": form = SignUpForm(request.POST) if form.is_valid(): messages.success(request, 'Successfully SignUp') form.save() form = SignUpForm(request.POST) else: form = SignUpForm() return render( request, "signup.html", {'form' : form} ) Dashboard code def dashboard(request): if request.user.is_authenticated: current_user = request.user posts = Post.objects.filter(user=current_user) else: redirect('/login/') return render( request, "dashboard.html", {'posts':posts} ) Dashboard HTML code Dashboard <a href="{% url 'addpost' %}" class="btn btn-success">Add Post</a> <h4 class="text-center alert alert-info mt-3">Show Post Information</h4> {% if posts %} <table class="table table-hover bg white"> <thead> <tr class="text-center"> <th scope="col" style="width: 2%;">ID</th> <th scope="col" style="width: 25%;">Title</th> <th scope="col" style="width: 55%;">Description</th> <th scope="col" style="width: 25%;">Action</th> </tr> </thead> <tbody> {% for post in posts %} {% if post.user == request.user%} <tr> <td scope="row">{{post.id}}</td> <td>{{post.title}}</td> <td>{{post.decs}}</td> … -
Id Field Showing null while saving data in Django rest framework
Whenever I try to add new recored to data base using django rest api it is showing 'null' in the id field I haved attached my serializers code and views code, Views.py @api_view(['POST']) def createcostumer(request): serializer = Costumerdetailsserializer(data=request.data) print(request.data) if serializer.is_valid(): # some_dict = {'id': serializer.data['id']} serializer.save() else: pass return Response(serializer.data) Serializers.py class Costumerdetailsserializer(serializers.ModelSerializer): class Meta: model = Costumerdetails fields = '__all__' Help me to fix This OUTPUT image Here -
Django - At least one inline formset filled out of multiple inline formsets
is there a way to validate that at least 1 of the many different formsets are not empty inside forms.py? I have a working validation inside views.py but this validation don't apply to admin form. I want my code to be DRY and so my idea is to write the validation inside forms.py, so that both admin and HTML form share the same validation. models.py, Person can have multiple PersonAddress and PersonEmail class Person(models.Model): ... class PersonAddress(models.Model): person = models.ForeignKey( Person, null=True, on_delete=models.SET_NULL, related_name="person_address", ) ... class PersonEmail(models.Model): person = models.ForeignKey( Person, null=True, on_delete=models.SET_NULL, related_name="person_email", ) ... forms.py, PersonAddressFormSet and PersonEmailFormSet will become inline formsets of PersonForm class PersonForm(forms.ModelForm): ... class PersonAddressForm(forms.ModelForm): ... class PersonEmailForm(forms.ModelForm): ... PersonAddressFormSet = forms.models.inlineformset_factory( Person, PersonAddress, form=PersonAddressForm, can_delete=False, extra=1, ) PersonEmailFormSet = forms.models.inlineformset_factory( Person, PersonEmail, form=PersonEmailForm, can_delete=False, extra=1, ) views.py, under form_valid method, if both address and email formset are not has_changed, I will return form error class PersonCreateView(SuccessMessageMixin, MetadataMixin, LoginRequiredMixin, CreateView): model = Person form_class = PersonForm template_name = "person/person_form.html" def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) if self.request.POST: context["addresses"] = PersonAddressFormSet(self.request.POST, self.request.FILES) context["emails"] = PersonEmailFormSet(self.request.POST, self.request.FILES) else: context["addresses"] = PersonAddressFormSet() context["emails"] = PersonEmailFormSet() return context def form_valid(self, form): form.instance.created_by = self.request.user context = … -
Django: Execution order of multiple decorators login_required and permission_required
This question is asked here. However, I am still confused with the answers as the Django behavior does not follow Python's decorators execution order behavior. In summary, in Django you have to use the order for login_required and permission_required from top to bottom like below: @login_required @permission_required('perm.create', raise_exception=True) def my_view(request): ... However, looking at decorators in Python, it is the other way around. The first decorator closest to the function will be run first. Look at the following example taken from here (I modified it a bit). # code for testing decorator chaining def decorTop(func): def inner(): x = func() print("in decorTop: x =",x,"; output would be x^2 =",x*x) return x * x return inner def decorBottom(func): def inner(): x = func() print("in decorBottom: x =",x,"; output would be 2x =",2*x) return 2 * x return inner @decorTop @decorBottom def num(): return 10 print(num()) This is the output: in decorBottom: x = 10 ; output would be 2x = 20 in decorTop: x = 20 ; output would be x^2 = 400 400 Can somebody please explain more why the behavior in Django is the other way around? -
In Django, what is the difference between "{% load i18n %}" and "{% load i18n static %}"
I noticed that in password_reset_confirm.html, Django uses {% load i18n static %}. However, I have always used {% load i18n %} for translation. What is the difference between the two? What does adding static keyword achieve here? -
Django: A Case has many Person as debitor and has one Person as creditor
guys! I'm doing a test and I have some questions. The basic structure: Case case_number creditor debitors Person name document The test says that a person can be a creditor/debitor, and a case can have multiple debitors and one creditor. It is possible to do this with a single person table or I'm overthinking it and have to divide it into two? -
Django `request.query_params.get("page")` returns None?
I use Next.js for front end and this is how I send the query params. export const getServerSideProps = wrapper.getServerSideProps( async (context) => { const { store, query } = context; console.log("params", query); store.dispatch(fetchProductsStart(query)); store.dispatch(END); await (store as SagaStore).sagaTask.toPromise(); const state = store.getState(); const productListState = state.productList ? state.productList : null; return { props: { productListState } }; } ); console.log("params", query) returns this object:"{ keyword: 'g', page: '1' }". This is what I am sending to backend. This is how I tried to get the params in the backend: @api_view(['GET']) def getProducts(request): q=request.query_params.get("page") print("page query param",q) query = request.query_params print("query_params",query) print("page query param",q) returns "None" print("query_params",query) returns "<QueryDict: {'[object Object]': ['']}>" I cannot figure out how to reach "keyword" and "page" query paramters inside django queryDict. -
How add categories in my webside with django?
Im beginner in django and im trying to make a webside. I want to filter the categories in my webside but i have a error (UnboundLocalError) when introduce the url in browser. models.py from django.db import models from django.contrib.auth.models import User class Categoria(models.Model): nombre=models.CharField(max_length=50) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='categoria' verbose_name_plural='categorias' def __str__(self): return self.nombre class Post(models.Model): titulo=models.CharField(max_length=50) contenido=models.TextField() imagen=models.ImageField(upload_to='blog', null=True, blank=True) autor=models.ForeignKey(User, on_delete=models.CASCADE) categorias=models.ManyToManyField(Categoria) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='post' verbose_name_plural='posts' def __str__(self): return self.titulo urls.py from django.urls import path from . import views urlpatterns = [ path('',views.blog, name='Blog'), path('categoria/<int:categoria_id>/', views.categoria, name='categoria'), ] views.py from django.shortcuts import get_object_or_404, render from blog.models import Categoria, Post def blog(request): posts=Post.objects.all() return render(request, 'blog/blog.html', {'posts':posts}) def categoria(request, categoria_id): categoria=get_object_or_404(Categoria, id=categoria_id) return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts}) blog.html {% extends 'ProyectoWebApp/base.html' %} {% load static %} {% block content %} {% for post in posts %} <div class="intro"> <img class="intro-img img-fluid mb-3 mb-lg-0 rounded" src="{{post.imagen.url}}" alt="" style="width: 50%;"> <div class="intro-text left-0 text-center bg-faded p-5 rounded"> <h2 class="section-heading mb-4" > <span class="section-heading-lower">{{post.titulo}}</span> <span class="section-heading-upper">{{post.contenido}}</span> </h2> <div style="text-align: left; font-size: 0.8em;"> Autor: {{post.autor}} </div> </div> </div> </div> </section> {% endfor %} <div style="width: 75%; margin: auto; text-align: center; color: white;"> Categorias: {% for post in posts %} {% for … -
I'm not sure why im getting this async error in python
I managed to get my api request asynchronous but then received this error when trying to implement it into the main project. What does this mean that I have done wrong? ERROR Exception has occurred: SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. File "C:\Users\Admin\Desktop\djangoProjects\dguac\Signal.py", line 124, in main await asyncio.wait([sigBuy(count) for count, bot in enumerate(activeBots)]) File "C:\Users\Admin\Desktop\djangoProjects\dguac\Signal.py", line 126, in <module> loop.run_until_complete(main()) I don't understand what this error means and how I would be able to fix it. Here is my code async def sigBuy(count): bot_dict = Bot.to_dict(activeBots[count]) sigSettings_dict = Bot.to_dict(activeBots[count].sigSettings) # Binance API and Secret Keys Bclient = CryptoXLib.create_binance_client(sigSettings_dict['API_key'], sigSettings_dict['API_secret_key']) p = round(float(percentage(7, bot_dict['ct_balance']) / (float(bin_asset_price['price']) / 1)), 8) # Round and Asign the asset_amount asset_amount = round(p, 2) # shouldILog = await makeBuy(market, asset_amount, Bclient, sigSettings_dict['base_currency']) shouldILog = 2 if shouldILog == 2: asset_amount = int(asset_amount) last_trade = await Bclient.get_all_orders(pair = Pair(market, sigSettings_dict['base_currency'])) last_trade = last_trade['response'][-1] print(last_trade) # asset_price = float(last_trade['cummulativeQuoteQty']) / float(last_trade['executedQty']) asset_price = 0.00000123 buyInPrice = float(last_trade['cummulativeQuoteQty']) for otrade in activeBots[count].opentrades.all(): trade = Bot.to_dict(otrade) del trade['id'] otradesUpdate.append(trade) openTrades_dict = {'bot_ID': bot_dict['id'], 'date': date, 'market': market, 'trade_mode': 'Buy', 'price': asset_price, 'amount': asset_amount, 'amount_in_base_currency': buyInPrice, 'result': 0} otradesUpdate.append(openTrades_dict) BotsUpdate.append(bot_dict) SigSettingsUpdate.append(sigSettings_dict) … -
Deploy Django on Docker app to PythonAnyWhere
I tried to deploy my project django on Docker app to (Python Anywhere) after i deployed when i press in the link it didn't open and this error appeared (Something went wrong 🙁 This website is hosted by PythonAnywhere, an online hosting environment. Something went wrong while trying to load it; please try again later There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception) These are the steps that I took: I changed the settings.py in api first--> ALLOWED_HOSTS = ['localhost','roka5.pythonanywhere.com'] and then in DATABASES 'NAME': str(BASE_DIR / 'db.sqlite3') then --> STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') and in terminal make collectstatic then i made a zip file and upload it in pythonAnywhere then decompressed it and then added a new web app and put source code in it and add some changes to configuration file related to Django and install library djangorestframework then i made a reload and then i tried to open the link but it didn't you can find settings.py code here: https://ideone.com/RjbfVp and configuration file code here: https://ideone.com/XPYOSb -
Why form with the ImageField is not valid in DJango?
I have model in Django which name is "User": class User(models.Model): user_id = models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID') surname = models.CharField(max_length=100) name = models.CharField(max_length=100) patronymic = models.CharField(max_length=100) email = models.CharField(max_length=100) avatar = models.ImageField(upload_to='store/static/store/user_avatars/') Also I include columns of this model into my form: class UserForm(forms.Form): surname = forms.CharField(max_length=100) name = forms.CharField(max_length=100) patronymic = forms.CharField(max_length=100) email = forms.CharField(max_length=100) password = forms.CharField(max_length=100) avatar = forms.ImageField() View which gets that data: def sign_up(request): if request.method == 'GET': return render(request, 'store/sign_up.html') elif request.method == 'POST': form = UserForm(request.POST, request.FILES) if form.is_valid(): user = User(surname=form.cleaned_data['surname'], name=form.cleaned_data['name'], patronymic=form.cleaned_data['patronymic'], email=form.cleaned_data['email'], avatar=form.cleaned_data['avatar']) user.save() return HttpResponse("Alright, you signed up! " + form.cleaned_data['email']) else: print(form.as_table()) return HttpResponse("Data is error!") And, finally, front of this view: <form method="post"> {% csrf_token %} <div class="user_data"> <div class="user_data_grid"> <input type="text" name="surname" placeholder="Surname" id="surname" style="grid-row: 2 / span 1"> <input type="text" name="name" placeholder="Name" id="name" style="grid-row: 3 / span 1"> <input type="text" name="patronymic" placeholder="Patronymic" id="patronymic" style="grid-row: 4 / span 1"> <input type="email" name="email" placeholder="Enter your mail" id="email" style="grid-row: 5 / span 1"> <input type="password" name="password" id="password" placeholder="Enter password" style="grid-row: 6 / span 1"> <input type="checkbox" id="checkbox" onclick="seePassword()" style="grid-row: 6 / span 1"> <label for="checkbox" style="grid-row: 6 / span 1"></label> <p … -
How can I define a ModelSerializer ChoiceField's choices according to object attribute?
My Beta model's stage field provides 5 choices. I want my serializer to not always accept all these choices but only some of them according to the serialized object's actual stage value. For example, if my_beta_object.stage == 1, then the serializer should expect (and offer) only stages 2 and 3, if my_beta_object.stage == 2, only stages 2 and 4, etc. # models.py class Beta(models.Model): class BetaStage(models.IntegerChoices): REQUESTED = (1, "has been requested") ACCEPTED = (2, "has been accepted") REFUSED = (3, "has been refused") CORRECTED = (4, "has been corrected") COMPLETED = (5, "has been completed") stage = models.ChoiceField(choices=self.BetaStage.choices) # serializers.py class BetaActionSerializer(serializers.ModelSerializer): stage = serializers.ChoiceField( # choices=? ) class Meta: model = Beta fields = ("stage",) How can I dynamically limit the choices of that field according to the serialized object's field value? -
How to trigger allauth.account.signals.user_signed_up signal using pytest?
I have a OneToOneField between my UserTrust model and django.contrib.auth.models.User that I would like to create whenever a new User registers. I thought on creating the UserTrust instance using the user_signed_up signal. I have the following code in my AppConfig def ready(self): # importing model classes from .models import UserTrust @receiver(user_signed_up) def create_usertrust(sender, **kwargs): u = kwargs['user'] UserTrust.objects.create(user=u) ... and this is in my pytest test @pytest.fixture def test_password(): return 'strong-test-pass' @pytest.fixture def create_user(db, django_user_model, test_password): def make_user(**kwargs): kwargs['password'] = test_password if 'username' not in kwargs: kwargs['username'] = str(uuid.uuid4()) return django_user_model.objects.create_user(**kwargs) return make_user @pytest.mark.django_db def test_my_user(create_user): user = create_user() assert user.usertrust.available == 1000 Still, the test fails with django.contrib.auth.models.User.usertrust.RelatedObjectDoesNotExist: User has no usertrust. What did I miss? -
python/django can't deploy to heroku
i get this error when i try to deploy my project on heroku i have followed a tutorial for proshop for him it worked fine without any issues but i get this error below -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed i already tried some of the mentioned stuff like heroku buildpacks:set heroku/python and have requirments.txt and procfile in my project -
Docker and Zappa: Wrong python path
I'm trying to run Django in a Lambda using Zappa and Docker, I'm following the instructions outlined here. Wwhen I run zappa deploy dev I keep getting the FileNotFound error below. It looks like my pythonpath and virtual environment path is wrong, and I've no idea how it got in there. I tried setting the pythonpath in my Dockerfile but with no luck. ============== Traceback (most recent call last): File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 2779, in handle sys.exit(cli.handle()) File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 509, in handle self.dispatch_command(self.command, stage) File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 546, in dispatch_command self.deploy(self.vargs['zip']) File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 718, in deploy self.create_package() File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 2216, in create_package archive_format='tarball' File "/var/task/venv/lib/python3.7/site-packages/zappa/core.py", line 544, in create_lambda_zip copytree(cwd, temp_project_path, metadata=False, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) File "/var/task/venv/lib/python3.7/site-packages/zappa/utilities.py", line 63, in copytree copytree(s, d, metadata, symlinks, ignore) File "/var/task/venv/lib/python3.7/site-packages/zappa/utilities.py", line 63, in copytree copytree(s, d, metadata, symlinks, ignore) File "/var/task/venv/lib/python3.7/site-packages/zappa/utilities.py", line 65, in copytree shutil.copy2(s, d) if metadata else shutil.copy(s, d) File "/var/lang/lib/python3.7/shutil.py", line 248, in copy copyfile(src, dst, follow_symlinks=follow_symlinks) File "/var/lang/lib/python3.7/shutil.py", line 120, in copyfile with open(src, 'rb') as fsrc: FileNotFoundError: [Errno 2] No such file or directory: '/var/task/env/bin/python' ============== This is my Dockerfile: FROM lambci/lambda:build-python3.7 LABEL maintainer="email@gmail.com" WORKDIR /var/task # Fancy prompt to remind you are in zappashell … -
no such table: app_user
im currently making a django rest framework web app for a client, the thing is that an error ocurred: File "E:\Co2\Trabajos\WarDogs\pagina-reload\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: api_usuario This is my Usuario model: from django.contrib.auth.models import AbstractUser from django.core.files import storage from django.db import models from api.utils import OverwriteStorage from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class Usuario(AbstractUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) USERNAME_FIELD='email' REQUIRED_FIELDS=['username'] def imgUsuario(self, *args, **kwargs): if self.usuario_img: data = {} for elemento in self.usuario_img.all(): if elemento.img: data["url"] = elemento.img.url data["id"] = elemento.id else: data["url"] = "" return data else: return "" And this my settings.py # Autenticacion de usuarios AUTH_USER_MODEL = 'api.Usuario' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', 'api.backends.CaseInsensitiveModelBackend', ) I tried this on python manage.py shell >> user = Usuario.objects.all() >> for u in user: >> u.id >> >> Error: django.db.utils.OperationalError: no such table: api_usuario Thank you guys! -
Ordering data, Paginator on django
The program I'm making is to display information about a product from the database. The program works fine, the problem is that I want to order by last name and not the "owner". For example. If the customer username is ewOI, which this is the "owner", and his name is Robert and last name is Bosh, I want to order the queryset by the last name and not the owner. Here is the views code: class ExpView(ListView): context_object_name = 'product' queryset = Product.objects.filter(prod__isnull=True).order_by('owner') template_name = 'productrecords.html' paginate_by = 10 there are two models, the one in product, and the one in user The product models: class Product(models.Model): owner = models.ForeignKey( User, on_delete=models.PROTECT, related_name='products' ) id_subscription = models.CharField(max_length=30, unique=True) amount = models.DecimalField(max_digits=11, decimal_places=2, null=True) interest_rate = models.DecimalField(max_digits=4, decimal_places=2) start_date = models.DateField(null=True) And the user models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True) second_name = models.CharField(max_length=32, blank=True) last_name2 = models.CharField(max_length=32, blank=True) recovery_email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=16, unique=True, null=True) Which for example if i go to the terminal and try to bring the query from the db: But I want to order_by('last_name') but that doesn't work. How can I order it? Thank you very much -
Django: Auto generate ID when form loads in a read only field
I want to generate a unique code base on month, year and number sequence for each transaction. Example 052101 Where 05 is the month, 21 is the year, and 01 is the count of number. The next code will be 052102 in that order. l want the generated code as value in a read only field when the form loads. -
Django - How to create a TableView out of many models that inherit same abstract class?
I'm trying to create a TableView that displays all objects in my project that inherit from the same abstract class. I know I may have needed to make the original class not abstract, but the project is already running and I'd rather not change the models now. The abstract class is this: class WarehouseBase(models.Model): region = models.ForeignKey(Region, on_delete=models.PROTECT, null=True, blank=False, verbose_name='Región') name = models.CharField(max_length=50, verbose_name='Nombre', unique=True) class Meta: abstract = True And the classes that inherit from it are: class SaleWarehouse(WarehouseBase): TYPES = ( (0, 'Autotanque'), (1, 'Estación de carburación') ) type = models.IntegerField(choices=TYPES, null=False, blank=False, verbose_name='Tipo') # price = models.ForeignKey(SpecificPrice, on_delete=models.SET_NULL, null=True, blank=True, related_name='warehouse') lat = models.DecimalField(max_digits=9, decimal_places=6, null=True) lng = models.DecimalField(max_digits=9, decimal_places=6, null=True) price = models.FloatField(verbose_name='Precio', validators=[MinValueValidator(0.0), MaxValueValidator(1000.0)], null=True, blank=True) price_date = models.DateField(verbose_name='Fecha de precio', null=True, blank=True, auto_now_add=True) def __str__(self): return '{} - {}'.format(str(self.pk), self.name) class GeneralWarehouse(WarehouseBase): @property def total_capacity(self): capacity = 0.0 for tank in self.tanks: capacity += tank.max_capacity return capacity def __str__(self): return "Almacén general '{}'".format(self.name) The new requirement for a view that enlists all warehouses was just added, but when the project was made this was not needed. I've been searching and I've found ways to change the database models so that I can make …