Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fetch data from backend django and react
i'm trying to fetch data from my backend and i'm resiving this error "SyntaxError: Unexpected end of input" this my react app import './App.css'; import { useState, useEffect } from 'react'; function App() { const [articles, setArticles] = useState([]) useEffect(() => { fetch('http://127.0.0.1:8000/api/users/', { mode: 'no-cors', 'method':'GET', headers: { 'Content-Type':'application/json', 'Authorization':'token 2e8bfe0b7ff1716c0c255ac62adad9d9832e7173' } }) .then(resp => resp.json()) .then(resp => setArticles(resp)) .catch(error => console.log(error)) }, []) return ( <div className="App"> {articles.map(article => { return ( <h2>{article.first_name}</h2> ) })} </div> ) } export default App; -
Protection of Django Rest Framework API with AllowAny permission
I have a full-stack app and I am taking measures to protect the application from DDOS or bot attacks. All the sensitive data is protected by IsAuthenticated permission but there are still open APIs with public data with AllowAny permissions. I have so far added throttling and limited the request rate to 100 for both anonymous and authenticated users and on the frontend side I've added Captcha to protect the server from mass user registration, what are more ways to protect the server? REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("accounts.authentication.Authentication",), # "EXCEPTION_HANDLER": "accounts.custom_exception_handler.custom_exception_handler" 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '100/minute', 'user': '100/minute' } } -
How to check whether the database is closed in django
from django.db import connections from django.db.utils import OperationalError db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: connected = False else: connected = True In server I have not close the connection but unable to update the query it shows the db connection is closed. Is there any solution in django to check whether the database is closed -
how can I solve UNIQUE constraint failed: core_labor.id? I used shortuuid to generate uid?
from django.db import models from django.utils import timezone # Create your models here. class Labor(models.Model): id = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=256) created_at =models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(auto_now=True) def __str__ (self): return f"Name: {self.name}" This is the serializers from rest_framework import serializers from ..models import Labor class LaborSerializer(serializers.ModelSerializer): class Meta: model = Labor fields = ['name'] This is the views from ..serializers.labor_serializers import LaborSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from ..models import Labor from django.utils import timezone from django.http import Http404 from rest_framework.permissions import IsAuthenticated from ..utils.utilities import generate_uuid generate_uid = generate_uuid() class LaborDetailViews(APIView): def get_labor(self, pk): try: return Labor.objects.filter(pk=pk) except Labor.DoesNotExist: raise Http404 def get(self, request, pk ): labor = self.get_labor(pk) serializer = LaborSerializer(labor ,many = True) return Response(serializer.data) def post(self, request): serializer = LaborSerializer(data = request.data) if serializer.is_valid(): Labor.objects.create(id = generate_uid, name = request.data['name'],modified_at = timezone.now()) labor = Labor.objects.filter(id= generate_uid).values() return Response ({"Message": "New Labor Status Added!", "Labor": labor, "Errors": serializer.errors}) I can't create new labor unless I reload the localhost server. When I use postman and try to add new labor(model) it throws me an error. which is that -
cart_total_amount showing 0 in django-shopping-cart
I have added cart.context_processor.cart_total_amount in settings.py But when i use it in the template it shows 0 I was expecting the total cart amount so want to know why the total cart amount is not showing up in {{cart_total_amount}} -
Django restarted (trigger file change) on every request when using runserver_plus
Django always detect file changes on every request on development mode. it was restarting even though i didn't make any change at all on the code. for a simple view this is not causing a problem. the process of rendering one page done before restart triggered. but if i have more complex logic in view, django restarted before the process of rendering a page completed. is any body know is this an expected behaviour? and why this is happened? how can i solve my problem? render a complex logic before django restarted. Is there are a way to disable that false positive trigger of file change? -
Try to make input file Not Required but it still Required in Django Python
Hi im still learning django and python, i made function to upload file, but i want the file is not required. heres my code: model.py class Ticket(models.Model): status = models.CharField(max_length=20, default="Pending") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) docfile = models.FileField(upload_to='attachments/file/%Y/%m/%d/%P', blank=True, null=True) views.py def new_ticket(request): form = TicketForm() if request.method == 'POST': form = TicketForm(request.POST, request.FILES) if form.is_valid() : form = form.save(commit=False) form.owner = request.user form.save() if form.docfile == 'docfile' : newdoc = TicketForm(docfile=request.FILES['docfile']) newdoc.save() return redirect('helpdesk:dashboard') documents = Ticket.objects.all() return render(request, 'helpdesk/new_ticket.html', {'form':form,'documents':documents}) forms.py class TicketForm(forms.ModelForm): status = forms.CharField(required=True) docfile = forms.FileField(required=False) class Meta: model = Ticket fields = ('status', 'docfile') new_ticket.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="status">Status</label> {% render_field form.status class="form-control"%} </div> <div class="form-group"> <label for="docfile">File Upload: </label> {% render_field form.docfile required=false class="form-control" %} </div> <hr> <input class="form-group button_main btn-lg" type="submit" value="Send" style="border: 0px;"></form> i already tried some solutions from this link : Django ModelChoice field is set to required=False but is still required in the browser Django Make ContentType Not Required Django form always shows error "This field is required" Django TextField always is required, despite blank=True,Null=True Django - Form template throws "This field is required" for Imagefield but the input field still … -
Vue-loader not recognizing template tag in a django + vue + tailwind SPA
I'm trying to set up a Django + GraphQL + Vue + Tailwindcss project on Windows 11 that would use static files generated by webpack but I'm getting the following 2 errors on vue files when trying to run npm run serve: ERROR in ./src/index.css (./node_modules/css-loader/dist/cjs.js??clonedRuleSet-14.use[1]!./node_modules/@vue/cli-service/node_modules/postcss-loader/dist/cjs.js??clonedRuleSet-14.use[2]!./node_modules/vue-style-loader/index.js!./node_modules/css-loader/dist/cjs.js!./node_modules/postcss-loader/dist/cjs.js!./src/index.css) Module build failed (from ./node_modules/@vue/cli-service/node_modules/postcss-loader/dist/cjs.js): SyntaxError (1:4) C:\Users\deteu\Development\django\application\frontend\src\index.css Unknown word > 1 | // style-loader: Adds some css to the DOM by adding a <style> tag | ^ 2 | 3 | // load the styles @ ./src/index.css 4:14-324 15:3-20:5 16:22-332 @ ./src/main.js 9:0-21 ERROR in ./src/views/ProfileView.vue Module Error (from ./node_modules/vue-loader/dist/index.js): At least one <template> or <script> is required in a single file component. @ ./src/router.js 16:19-52 @ ./src/main.js 10:0-33 20:8-14 The second error is different on npm run build: ERROR Error: Build failed with errors. Error: Build failed with errors. at C:\Users\deteu\Development\django\application\frontend\node_modules\@vue\cli-service\lib\commands\build\index.js:207:23 at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\webpack.js:148:8 at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\HookWebpackError.js:68:3 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) at Cache.shutdown (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Cache.js:150:23) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:1225:15 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) at Compiler.close (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:1218:23) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\webpack.js:147:16 at finalCallback (C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:441:32) at C:\Users\deteu\Development\django\application\frontend\node_modules\webpack\lib\Compiler.js:458:13 at Hook.eval [as callAsync] (eval at create (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:33:1) at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\deteu\Development\django\application\frontend\node_modules\tapable\lib\Hook.js:18:14) … -
Django admin display queryset
In my admin panel, i want to display the userdetail objects for users who meet specific requirements: premium_users = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False,) But its not working and its not display this on the admin page. Here is my full code: class UserDetailAdmin(admin.ModelAdmin): def show_premium_users(self, request, queryset): premium_users = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False,) self.message_user(request, f'{premium_users.count()} premium users found') queryset = queryset.filter(plan__in=['codera+', 'codera premium'], plan_purchase_date__isnull=False) print(queryset) return queryset show_premium_users.short_description = 'Show Premium Users' search_fields = ('user__username',) actions = ('show_premium_users') admin.site.register(UserDetail, UserDetailAdmin) How can I make it so i display the userdetail objects that meet the premium requirement on my admin page? -
Django ModelForm as controller of model field validation
I have an authorization form, and I get an error - "already have a user with this email". I want to use the forms as a layer of validating the data. I now, that i can pass instance of CustomUser in my form, but i can`t do it. Need other solution. @require_http_methods(["POST"]) @not_logged_in_user_only() def auth(request: WSGIRequest): form = UserAARForm(data=request.POST) if not form.is_valid(): return JsonResponse({'status': 'error', 'message': f'{form.errors.as_json()}'}) else: service = AuthenticateAndAuthOrRegistrUser() service.execute(req=request, data=form.clean()) if service.errors: return HttpResponseServerError() return redirect("profile_page") class SoundHomeUsers(models.Model): email = models.EmailField( max_length=254, unique=True, validators=[UserEmailValidator().is_valid]) password = models.CharField( max_length=254, validators=[UserPasswordValidator().is_valid]) class UserAARForm(ModelForm): class Meta: model = SoundHomeUsers fields = ['email', 'password'] -
How do I make an auto increment field that references other model fields in Django?
I'm making an Author model and I need to create an automatically increasing field by writing Post: Class Author(models.Model): author_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) post_count = models.PositiveIntegerField(default=0, null=True) # This field! Class Post(models.Model): post_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) body = models.TextField() author = models.ForeignKey('Author', to_field="author_id", null=True, on_delete=models.SET_NULL, db_column="author") created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) How do I make it? -
Django 4.2 and NGINX - The page isn’t redirecting properly
I am trying to add ssl to my test django server that is on AWS. I followed a tutorial to add ssl with certbot, add the proxy_pass but I never got it to work, so after three days trying all kinds of things, I give up. Could you guys please have a look and let me know where I am wrong? I am also confused about the environment variables, $host is blank and so are the others, I am going to assume they should be populated? I know nothing about NGINX, sorry about the noob questions. server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 404; } server { listen 80; listen [::]:80; server_name techexam.hopto.org; return 301 https://$server_name$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name techexam.hopto.org; ssl_certificate /etc/letsencrypt/live/techexam.hopto.org/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/techexam.hopto.org/privkey.pem; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; include /etc/nginx/mime.types; charset UTF-8; location /static/ { alias /home/sfarmer/code/django_workspace/exam/Quiz/static/Quiz/; } location /media/ { alias /home/sfarmer/code/django_workspace/exam/Quiz/static/Quiz/; } location / { proxy_pass http://127.0.0.1:8000/; proxy_set_header Host $host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Additional logging access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; error_page 502 /error_pages/502.html; location = /error_pages/502.html { internal; root /usr/share/nginx/html; } } } -
Gunicorn, serve VPS, can't load CSS to admin panel
Previously, I have never been involved in setting up and maintaining a VPS. I recently launched a project using ubuntu + nginx + gunicorn. Everything works fine, but the CSS are not loaded to admin panel. At first, not understanding what was the reason, I tried to install grappelli - without success. After I found information that gunicorn cannot load admin CSS. The solution I see is to configure nginx to render CSS to admin panel. However, I couldn't to set up nginx correctly when I tried to set up a server without gunicorn. As a result, the server gave the nginx stub and I couldn't log into the server (although nginx did not show any syntax errors) - I had to delete the server and set up a new one. Therefore, I ask for help: what needs to be written in the nginx configuration so that, in addition to transmitting traffic, it also gives the CSS of the admin panel? I will be grateful for any answer! -
Django docker: docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed
I want to deploy my django project with docker and uwsgi on windows 11, but get some errors. docker build . -t djangohw docker run -it --rm djangohw -p 8080:80 docker: Error response from daemon: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "-p": executable file not found in $PATH: unknown. Dockerfile FROM python:3.9 ENV DEPLOY=1 WORKDIR /opt/tmp COPY . . RUN pip install -r requirements.txt EXPOSE 80 CMD ["sh", "start.sh"] start.sh python3 manage.py makemigrations board python3 manage.py migrate uwsgi --module=mysite.wsgi:application \ --env DJANGO_SETTINGS_MODULE=mysite.settings \ --master \ --http=0.0.0.0:0 \ --processes=5 \ --harakiri=20 \ --max-requests=5000 \ --vacuum requirements.txt django==4.1.3 django-cors-headers pytest pytest-django coverage uwsgi -
Form wont update home db page. django and python
My django project wont update my home db page with the information from the join.html page. My urls.py file from django.urls import path from . import views urlpatterns = [ path( '' , views.home, name ="home"), path('join',views.join, name ="join"), ] views.py from django.shortcuts import render from .models import PersonInfo from .forms import PersonInfoForm import csv from django.core.files.base import ContentFile from django.core.files.storage import FileSystemStorage #from rest_framework.decorators import action #from rest_framework.response import Response # Create your views here. def home(request): all_members = PersonInfo.objects.all return render(request, 'home.html', {'all':all_members}) def join(request): if request.method == "POST": #console.log("hello") #if "submitButton" in request.POST: form = PersonInfoForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'join.html', {}) else: return render(request, 'join.html', {}) forms.py from django import forms from .models import PersonInfo class PersonInfoForm(forms.ModelForm): class Meta: model = PersonInfo fields = ['customerName','address','age','email','accountId'] models.py from django.db import models from django.utils.translation import gettext # Create your models here. class PersonInfo(models.Model): accountId = models.IntegerField(default=None) customerName = models.CharField(max_length = 50, default=None ) address = models.CharField(max_length = 50, default=None) email = models.EmailField(max_length = 200, default=None) age = models.IntegerField(max_length = 3, default=None) def __str__(self): return self.customerName + ' ' #return self.accountId class book(models.Model): accountId = models.IntegerField( ("Account_ID") ) customerName = models.CharField( ("Customer_Name"), max_length = 50, default=None … -
How to prevent the creation of same object using Faker?
I have the following factory: class MonthFactory(factory.django.DjangoModelFactory): class Meta: model = Month year = factory.Faker("random_int", min=2014, max=2022) month = factory.Faker("random_int", min=1, max=12) Both year and month are unique in my Django class: class Meta: unique_together = ( "month", "year", ) When I want to create two objects for a test, let's say: month1 = MonthFactory() month2 = MonthFactory() sometimes I hit the jackpot and get: django.db.utils.IntegrityError: duplicate key value violates unique constraint because Faker got the same month and year for both objects. Is there a way to prevent this? -
Microsoft Access design View in django
How can I create one model that can takes all these models to look exactly like Microsoft Access Design View? I want to put these model into a one called TablesDesign so that it would enable user to design how their data could be stored in the application, is there anyone who can help? class Numbers(models.Model): num = models.IntegerField() class Characters(models.Model): char = models.CharField(max_length=1000) class Check(models.Model): check = models.BooleanField() class Date(models.Model): date = models.DateField() class LargeNumber(models.Model): larger_num = models.DecimalField(max_digits=30 decimal_places=15) class TablesDesign(model.Models): """" I want to put all these models into the TablesDesign to create something similar to Microsoft Access Design View. -
Django: Use Proxy Models and lost history
i implement two proxy models from a main model to use them in different ModelAdmins with different get_queryset´s. ALl is running fine. But i lost the change history of the object if it switches between the main model to the proxy model. Is there a solution for that ? -
why pipenv install gives me Package installation failed... error
i want to run django app so whenever i run pipenv install to install all the packages from my pipfile it gives me this error note : -i'm running on windows -cmake did nothing -it doesn't change anything if pipenv shell is opened or closed -i tried to delete pipenv manually and reinstall -i tried to install and update wheel and thank you in advance Installing dependencies from Pipfile.lock (631114)... An error occurred while installing boto3==1.26.86 --hash=sha256:7e8fc7bfef6481e48380d13e18a0a036413d126dc7eda37eadc1a052a3426323 --hash=sha256:e981703b76d2fb9274ce5cdda6ea382e29c9e7c65bc400c94c0a259b26f8914a! Will try again. An error occurred while installing botocore==1.29.86 ; python_version >= '3.7' --hash=sha256:8a4afc6d540c01890e434b9a31fb1b17f8c759001e12c7ad7c49f55ea5805993 --hash=sha256:6083c649791559dd916c9ff7ac62486b391f6f9464d3cf6964582a489c866b11! Will try again. An error occurred while installing charset-normalizer==3.1.0 ; python_full_version >= '3.7.0' --hash=sha256:4155b51ae05ed47199dc5b2a4e62abccb274cee6b01da5b895099b61b1982974 --hash=sha256:322102cdf1ab682ecc7d9b1c5eed4ec59657a65e1c146a0da342b78f4112db23 --hash=sha256:e89df2958e5159b811af9ff0f92614dabf4ff617c03a4c1c6ff53bf1c399e0e1 --hash=sha256:73dc03a6a7e30b7edc5b01b601e53e7fc924b04e1835e8e407c12c037e81adbd --hash=sha256:7381c66e0561c5757ffe616af869b916c8b4e42b367ab29fedc98481d1e74e14 --hash=sha256:34e0a2f9c370eb95597aae63bf85eb5e96826d81e3dcf88b8886012906f509b5 --hash=sha256:74db0052d985cf37fa111828d0dd230776ac99c740e1a758ad99094be4f1803d --hash=sha256:891cf9b48776b5c61c700b55a598621fdb7b1e301a550365571e9624f270c203 --hash=sha256:e1b25e3ad6c909f398df8921780d6a3d120d8c09466720226fc621605b6f92b1 --hash=sha256:fca62a8301b605b954ad2e9c3666f9d97f63872aa4efcae5492baca2056b74ab --hash=sha256:c36bcbc0d5174a80d6cccf43a0ecaca44e81d25be4b7f90f0ed7bcfbb5a00909 --hash=sha256:6734e606355834f13445b6adc38b53c0fd45f1a56a9ba06c2058f86893ae8017 --hash=sha256:3573d376454d956553c356df45bb824262c397c6e26ce43e8203c4c540ee0acb --hash=sha256:20064ead0717cf9a73a6d1e779b23d149b53daf971169289ed2ed43a71e8d3b0 --hash=sha256:78cacd03e79d009d95635e7d6ff12c21eb89b894c354bd2b2ed0b4763373693b --hash=sha256:9a3267620866c9d17b959a84dd0bd2d45719b817245e49371ead79ed4f710d19 --hash=sha256:d2686f91611f9e17f4548dbf050e75b079bbc2a82be565832bc8ea9047b61c8c --hash=sha256:d7fc3fca01da18fbabe4625d64bb612b533533ed10045a2ac3dd194bfa656b60 --hash=sha256:de5695a6f1d8340b12a5d6d4484290ee74d61e467c39ff03b39e30df62cf83a0 --hash=sha256:830d2948a5ec37c386d3170c483063798d7879037492540f10a475e3fd6f244b --hash=sha256:1435ae15108b1cb6fffbcea2af3d468683b7afed0169ad718451f8db5d1aff6f --hash=sha256:ea9f9c6034ea2d93d9147818f17c2a0860d41b71c38b9ce4d55f21b6f9165a11 --hash=sha256:75f2568b4189dda1c567339b48cba4ac7384accb9c2a7ed655cd86b04055c795 --hash=sha256:6f6c7a8a57e9405cad7485f4c9d3172ae486cfef1344b5ddd8e5239582d7355e --hash=sha256:22908891a380d50738e1f978667536f6c6b526a2064156203d418f4856d6e86a --hash=sha256:dd5653e67b149503c68c4018bf07e42eeed6b4e956b24c00ccdf93ac79cdff84 --hash=sha256:ac3775e3311661d4adace3697a52ac0bab17edd166087d493b52d4f4f553f9f0 --hash=sha256:628c985afb2c7d27a4800bfb609e03985aaecb42f955049957814e0491d4006d --hash=sha256:a04f86f41a8916fe45ac5024ec477f41f886b3c435da2d4e3d2709b22ab02af1 --hash=sha256:04afa6387e2b282cf78ff3dbce20f0cc071c12dc8f685bd40960cc68644cfea6 --hash=sha256:12d1a39aa6b8c6f6248bb54550efcc1c38ce0d8096a146638fd4738e42284448 --hash=sha256:3160a0fd9754aab7d47f95a6b63ab355388d890163eb03b2d2b87ab0a30cfa59 --hash=sha256:3d9098b479e78c85080c98e1e35ff40b4a31d8953102bb0fd7d1b6f8a2111a3d --hash=sha256:0be65ccf618c1e7ac9b849c315cc2e8a8751d9cfdaa43027d4f6624bd587ab7e --hash=sha256:ac0aa6cd53ab9a31d397f8303f92c42f534693528fafbdb997c82bae6e477ad9 --hash=sha256:b116502087ce8a6b7a5f1814568ccbd0e9f6cfd99948aa59b0e241dc57cf739f --hash=sha256:10c93628d7497c81686e8e5e557aafa78f230cd9e77dd0c40032ef90c18f2230! Will try again. An error occurred while installing colorama==0.4.6 ; platform_system == 'Windows' --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44! Will try again. An error occurred while installing django==4.2b1 --hash=sha256:33e3b3b80924dae3e6d4b5e697eaee724d5a35c1a430df44b1d72c802657992f --hash=sha256:9bf13063a882a9b0f7028c4cdc32ea36fe104491cd7720859117990933f9c589! Will try again. An error occurred while installing django-admin==2.0.2 --hash=sha256:a92f9fb21f63edabb5db9030f36b62c6c16a0187183e7e7de4142aee4472b70f --hash=sha256:43c9f94ca5ad498789c0282691931c609c8e26db61aeb49ae8ad90d15b80cb75! Will try again. An error occurred while installing django-excel-response2==3.0.5 --hash=sha256:ba908be16decbdc97b998bd20e596c27da78d23f97b533853c778c8c9c0974e3 --hash=sha256:4bbdd374cadd2d85723d5cd4b49822301141f7e4fef69616639cf3b7535e9ea5! Will try again. An error occurred while installing django-six==1.0.5 … -
Django: How to make model for list of string as one-to-many relation?
I have data like so: [ { "name": "Alice", "hobbies": ["programming", "swimming"] }, { "name": "Bob", "hobbies": ["sleeping", "skiing", "skating"] } ] I want to be able to use hobbies for later filtering, so I would like to have separate Hobby model with many-to-one relation to the Person model. What is a good practice to do so? Is there any simple way how to save person and hobbies at once (for example using singular serializer) and/or use serializer to retrieve data in the simmilar fashion as the input? -
Switched from WSGI to ASGI for Django Channels and now CircleCI throws "corrupted double-linked list" even though tests pass
I've been working on a project which requires WebSockets. The platform is built with Django and was running the WSGI server gunicorn. We decided to implement WebSockets using Django Channels. I set everything up including switching from gunicorn to the ASGI server daphne. Everything works great in local development environment. Deployment to AWS is working and everything works great on dev/staging. pytest works and all tests pass locally. On CircleCI all the tests are passing, but at the end of the "test" step we get the following and CircleCI shows a failed status: ================== 955 passed, 2 skipped in 216.09s (0:03:36) ================== corrupted double-linked list /bin/bash: line 2: 278 Aborted (core dumped) poetry run coverage run -m pytest $TESTFILES -vv --junitxml htmlcov/junit.xml Exited with code exit status 134 CircleCI received exit code 134 There are no other errors, warnings, or unexpected output. I cannot replicate the issue outside of CircleCI. I tried adding the @pytest.mark.asyncio decorator to the one async test we have and still got the above. Even when I totally remove said test CircleCI still throws the same. Google has not been helpful. Edit: This same thing has also happened a couple of times during the "migrate" step … -
Python Django: Inline edit and sub-total automatic
I have a simple application for forecasting hours in projects for team members. The 'view' mode: For the "edit" mode I have this interface: Instead of a new view/template for "edit" I would like to have inline edit functionality. Is that feasible with Python Dango only as I don't want to use jquery or JavaScript. Similarly, can the sub-total be calculated automatically on the page just using Python Django? -
Using shell_plus doesn't import models with the same name
Let's say we have app1 and app2 that both have models MyModel. When using the console, I've noticed that app1's MyModel is the only one that is imported: python manage.py tenant_command shell_plus The above command only imports the first MyModel, and I'm assuming it doesn't do the second since there's already a MyModel imported. Is there anyway to deal with the above? Thanks I've tried to use import as but that doesn't seem to work and causes issues in a larger codebase. I can get around this by manually importing the model, but that will overwrite the one that's already imported within shell_plus -
Nginx no such file or directory unix:/run/gunicorn.sock
Разворачиваю Django на сервере. Использую Nginx и gunicorn. После настройки, получаю ошибку 502 от Nginx. В логах запись о том, что не найден файл unix:/run/gunicorn.sock, хотя файл существует и gunicorn запущен Логи Nginx (https://i.stack.imgur.com/Ru8xK.jpg) Конфиг Nginx (https://i.stack.imgur.com/VlBiD.png) Настройки Gunicorn (https://i.stack.imgur.com/CT5XP.png) Статус Gunicorn (https://i.stack.imgur.com/lj4tS.png) -
Django - New object is not created if html action argument is provided
I have simple contact form: <form method="post"> {% csrf_token %} {{ form_email.as_div }} {{ form_message.as_div }} <button name="submit">Send</button> </form> When text is provided in both fields (email and message) and then the user click on submit button, the data should be saved in data base. View function: def index(request): """The home page.""" # Send a message. if request.method != 'POST': # No data submitted; create a blank form. form_email = EmailForm() form_message = EmailMessageForm() else: # POST data submitted; proecess data. form_email = EmailForm(data=request.POST) form_message = EmailMessageForm(data=request.POST) if form_email.is_valid() and form_message.is_valid(): form_email.save() email = Email.objects.last() message = form_message.save(commit=False) message.email = email message.save() # Display a blank or invalid form. context = {'form_email': form_email, 'form_message': form_message} return render(request, 'home/index.html', context) Until now everything works as expected, but when I add action argument in order to redirect the user to the 'Thank you' page if form has been sent, the data is not saved. <form action="{% url 'home:contact_thank_you' %}" method="post"> {% csrf_token %} {{ form_email.as_div }} {{ form_message.as_div }} <button name="submit">Send</button> </form> Do you have any idea why the data is not saved when I add the action argument?