Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to return human readable from an enum (for multicheckbox forms)
I have this code, but it only returns the shorter variable values, 'Plan 1', 'Plan 2', not their longer human-readable forms which I have defined in the model. I generate checkboxes in a HTML template from a form.py and view.py by calling and passing in the variable (correct instance).student_loan_plan.all(), and passing that through the 'context' variable in the 'render' function MODEL # U.K. STUDENT LOAN PLAN MODEL class UK_Student_Loan_Plan(models.Model): STUDENT_LOAN_PLANS = [ ('Plan 1', 'Plan 1: English or Welsh student'), ('Plan 2', 'Plan 2: English or Welsh who started on 1 September 2012'), ('Plan 4', 'Plan 4: Scottish student who started on 1 September 1998'), ('Postgraduate', 'Postgraduate: English or Welsh student'), ] student_loan_plan_id = models.BigAutoField(verbose_name='Student Loan Plan ID', primary_key=True, serialize=False, auto_created=True) student_loan_plan = models.CharField(verbose_name='Student Loan Plan', max_length=12, choices=STUDENT_LOAN_PLANS, blank=True, unique=True, null=True) def __str__(self): return self.student_loan_plan QUESTION Q1. How do I get the full human readable form returned? I've tried this, but no success def __str__(self): return self.student_loan_plan.choice -
'modelBlog' object has no attribute 'CommentModel_set'
Im try make blog detail and comment in one page but if im try posting comment i got error like this 'modelBlog' object has no attribute 'CommentModel_set' My views def comment(request, id): blog = get_object_or_404(modelBlog, id=id) form = CommentForm(request.POST or None) heading = blog.title if request.method == 'POST': if form.is_valid(): data={ 'name':request.POST['name'], 'komentar':request.POST['komentar'], } blog.CommentModel_set.create(**data) return redirect('blog:detail', id) context = { 'title':'Detail', 'heading': heading, 'blog':blog, 'comment':comment, 'form':form } return render(request, 'blog/detail.html', context) And my model class modelBlog(models.Model): title = models.CharField(max_length=200) description = models.TextField() body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) def __str__(self): return ('{}.{}').format(self.id, self.title) class CommentModel(models.Model): user = models.ForeignKey('auth.User',default=1, on_delete=models.CASCADE) blog = models.ForeignKey(modelBlog, on_delete=models.CASCADE) name = models.CharField(max_length=200) komentar = models.TextField() pub_date = models.DateTimeField(auto_now_add=True,) My templates <form action="{% url 'blog:comment' blog.id %}" method="post"> {% comment %} {% endcomment %} {% csrf_token %} {% for forms in form %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">{{forms.label}}</label> <input type="{{forms.type}}" name="{{forms.name}}" class="form-control" id="exampleFormControlInput1"> </div> {% endfor %} <button type="submit" class="btn btn-primary">Kirim</button> </form> -
Hx-push-url doesn’t work on back button click
I am trying to integrate Htmx with django and achieve single page application behaviour. I am rewritting Djangoproject.com poll app with htmx. When I click on detail page link, content loads, htmx push a new url in address bar. When I press back button, it took me to index page perfectly for the first time, after that if I again go to detail page and click back button, url shows of the index, button index content doesn’t load, content remains same as detail page. Here is my code views.py def index(request): latest_question_list = Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} if request.headers.get("Hx-Request") is not None: return render(request, 'main/index/index.html', context) else: return render(request, 'main/index/index-full.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) print(request.headers.get("Hx-Request")) if request.headers.get("Hx-Request") is not None: return render(request, 'main/detail/detail.html', {'question': question}) else: return render(request, 'main/detail/detail-full.html', {'question': question}) index.html <div id="index" class=""> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><div class="has-text-link" hx-get="{% url 'main:detail' question.id %}" hx-push-url="true" hx-target="#index" hx-swap="outerHTML">{{ question.question_text }}</div></li> {% endfor %} </ul> {% else %} <p> No polls are available. </p> {% endif %} </div> index-full.html {% extends 'base.html' %} {% block content %} {% include 'main/index/index.html' %} {% endblock content %} detail.html <div id="detail" … -
TypeError: 'NoneType' object is not callable django websockets
i'm trying to add a notification feature to my projet. but when i try to connect using postman i get TypeError: 'NoneType' object is not callable. i have no idea why im getiing this error. the error doesnt even indicate a line in my code. this is my consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class NotificationConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['user_id'] user = self.scope['user'] if self.room_name == user: async_to_sync(self.channel_layer.group_add)( self.room_name, self.channel_name ) self.accept() return async def disconnect(self, code): return await self.close() def receive(self, text_data=None): return def send_notifications(self, event): data = json.loads(event.get('value')) self.send(text_data=json.dumps({'payload':data})) this is my routing.py from django.urls import re_path from .consumers import NotificationConsumer websocket_urlpatterns = [ re_path(r'ws/notification/(?P<user_id>\w+)/$', NotificationConsumer.as_asgi()), ] this is my channelsmiddleware.py from django.db import close_old_connections from rest_framework_simplejwt.tokens import UntypedToken from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from jwt import decode as jwt_decode from clothRentalBackend import settings from django.contrib.auth import get_user_model from urllib.parse import parse_qs class TokenAuthMiddleware: """ Custom token auth middleware """ def __init__(self, inner): # Store the ASGI application we were passed self.inner = inner def __call__(self, scope): # Close old database connections to prevent usage of timed out connections close_old_connections() # Get the token token = parse_qs(scope["query_string"].decode("utf8")).get("token")[0] try: UntypedToken(token) except (InvalidToken, TokenError) … -
django.core.exceptions.FieldDoesNotExist: User has no field named 'phone'
I'm trying to customize Django's AbstractBaseUser and make phone as a main field like username in AbstractUser model. But when I'm trying to migrate or run the server I'm getting the follow error: "django.core.exceptions.FieldDoesNotExist: User has no field named 'phone'". USERNAME_FIELD, REQUIRED_FIELDS are all set in Custom User and AUTH_USER_MODEL = 'users.User' is also available in settings.py. Here is the code: class User(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): USER = 1 BUSINESS_OWNER = 2 #choices for user type USER_TYPE_CHOICES = [ (USER, _('User')), (BUSINESS_OWNER, _('Business Owner')) ] first_name = models.CharField( _('first name'), max_length=200 ), user_type = models.PositiveSmallIntegerField( _('user type'), choices=USER_TYPE_CHOICES, default=USER ) phone = models.CharField( _('phone number'), max_length=13, unique=True ), sms_code = models.CharField( _('SMS code'), null=True #TODO: if verification requires change null ) last_name = models.CharField( _('last name'), max_length=200, null=True, blank=True ), is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('is active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) date_joined = models.DateTimeField( _('date joined'), default=timezone.now ) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['first_name'] objects = users_managers.UserManager() class Meta: verbose_name = _('User') verbose_name_plural = _('Users') db_table = 'users' Code of UserManager: … -
generate presigned url sse-c s3
How to generate a presigned url to get an URL to an object using when SSE-C is used in python? When I upload the file, this is what my code looks like secret = '?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf' # just pasting here. In general, it's usually derived from .env file return client.put_object( Bucket=os.environ.get('S3_DOCS_BUCKET'), Key='koushik.jpg', # giving a random name for .jpg image file Body=file, ContentType=fileobject.content_type, SSECustomerAlgorithm='AES256', SSECustomerKey=secret, ) Now, this uploads fine. But the problem is that I can't generate pre signed URL like this url = client.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': os.environ.get('S3_DOCS_BUCKET'), 'Key': 'koushik.jpg', 'SSECustomerAlgorithm': 'AES256', 'SSECustomerKey': '?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf', # just pasting here }, ExpiresIn=3600, ) The key that it generates says that the signature doesn't match. Now I've searched, at some places, it says that I've to provide the SSECustomerKeyMD5 params as well. I've tried doing that and still doesn't work. url = client.generate_presigned_url( ClientMethod='get_object', Params={ 'Bucket': os.environ.get('S3_DOCS_BUCKET'), 'Key': 'koushik.jpg', 'SSECustomerAlgorithm': 'AES256', 'SSECustomerKey': '?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf', # just pasting here, 'SSECustomerKeyMD5': hashlib.md5('?D(G+KbPeSgVkYp3s6v9y$B&E)H@McQf'.encode('utf-8')).hexdigest() }, ExpiresIn=3600, ) I've spent days but still can't get a working solution. If anyone can, please show an working example of file upload(a.k.a put_object) by providing SSECustomerKeyMD5. I think that would help me a lot. Thank you in advance. -
Migrating content type is throwing an error
When I run this command python manage.py migrate contenttypes I am seeing an error as django.db.utils.DataError: (1264, "Out of range value for column 'id' at row 1"). I have no tables in my database it is all empty. I have deleted all the migration folders and then I tried to migrate the contenttypes. My Django versions is django~=3.2.12 Here is the complete traceback of the error - Operations to perform: Apply all migrations: contenttypes Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/usr/local/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.DataError: (1264, "Out of range value for column 'id' at row 1") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", … -
Popup not showing after adding my frontend with react inside a Django project
I am using Reactjs to create a Popup that should appear when I click on a button. Tha same code is running when the project is alone, but once I insert it in django, Everything is working except the popup of the form. When I click on it i get a blank page. Ps: When I set the useState(true), nothing appears from the start.(white page again) (Even my confirmation dialog is working) (I am using some components from material ui) This is the main page where I have the button, and where the popup should appear: export default function Documents() { const [openPopup, setOpenPopup] = useState(false); return ( <div className={classes.newButton}> <Buttons text="My Button" color="warning" startIcon={<AddCircleOutlineOutlinedIcon />} onClick={() => { setOpenPopup(true); }} /> </div> <Popup title="Title of my Popup" openPopup={openPopup} setOpenPopup={setOpenPopup}> <DocumentForm /> </Popup> ) This is the Popup component: import { Dialog, DialogContent, DialogTitle, Typography } from "@mui/material"; import React from "react"; import ActionButton from "./Controls/ActionButton"; import CancelIcon from "@mui/icons-material/Cancel"; export default function Popup(props) { const { title, children, openPopup, setOpenPopup } = props; return ( <Dialog open={openPopup} maxWidth="md"> <DialogTitle> <div style={{ display: "flex" }}> <Typography variant="h6" component="div" style={{ flexGrow: 1 }}> {title} </Typography> <ActionButton onClick={() => { setOpenPopup(false); }}> … -
How to get or create on Django Rest Framework and return it
I would like to send post request with json data as shown below. { "checkin_date": "2022-02-15", "checkout_date": "2022-02-18", "guest_number": 1, "user": { "first_name": "Huesped", "last_name": "1", "email": "huesped_1@mail.com", "phone": "+34 12345678" } } How can I override some ModelSerializer method to get the user if the email exists, or create it and return its id for reservation related? Can it be done in a single query with nested objects or should I do 2 queries? Here are my python files. models.py: class Reservation(models.Model): user = models.ForeignKey(get_user_model(), verbose_name="User", related_name='user_reservations', on_delete=models.CASCADE) serializers.py: class ReservationPostSerializer(serializers.ModelSerializer): user = UserPostSerializer() Thanks in advance. -
Increment the order attribute in model according to the data in spreadsheet
I have spreadsheet column which has two types of choices A and B when i extract the data from the excel sheet it will check the choice type and increment the field order how can i achieve this the data can be like only Data. Order A 1 A 2 A 3 A 4 A 5 B 6 B 7 B 8 Mymodel.objects.create(order='',) How can i increment the order according to the retreived data -
Best practice put nginx + django in AWS subnet private?public?
I want to put the fargate container which contains django + nginx However what subnet should be used for? At first I put this in public subnet, of course it works well. However, is it possible to put this in private subnet with NAT gateway? A few users(admin) need to access to this django, it doesn't need to get access from other users. -
The input field could not show the expected result that I filled in Django
customer/update_order.html <table class="table table-striped table-bordered"> <form method="POST" action="."> {% csrf_token %} <tr> <th style="width:160px;text-align:center;background-color: blue;color:red;">食物</th> <th style="width:100px;text-align:center;background-color: blue;color:red;">單價</th> <th style="width:100px;text-align:center;background-color: blue;color:red;">數量</th> <th style="width:100px;text-align:center;background-color: blue;color:red;">總價</th> <th style="width:100px;text-align:center;background-color: blue;color:red;"></th> </tr> {% for item in food %} <tr> <td style="text-align:center;vertical-align:middle;"> {{ item.product.name }} </td> <td style="text-align:center;vertical-align:middle;">$ {{ item.unit_price }}</td> <td style="text-align:center;vertical-align:middle;"> <input name="qty{{ item.id }}" type="text" value="{{ item.quantity }}"> </td> <td style="text-align:center;vertical-align:middle;"> <a href="{% url 'update_item_qty' item.id %}" class="btn btn-warning">更新</a> </td> <td style="text-align:center;vertical-align:middle;">$ {{ item.total_price }}</td> </tr> {% endfor %} <tr> <td colspan="4" align="left" class="upline"><strong>總計</strong></td> <td align="center" class="upline">$ {{ order.total_price }} (包括$100運費)</td> </tr> <tr> <td colspan="4" align="left" class="upline"><strong>換領積分</strong></td> <td align="center" class="upline">{{ order.points_earned }}</td> </tr> </form> </table> views.py def update_order(request,order_id): global cartlist_update order = Order.objects.get(id=order_id) food = OrderDetail.objects.filter(order=order) cartlist_update = [] for item in food: cart = [] menu_food = Menu.objects.get(name=item.product.name) food_name = OrderDetail.objects.get(product=menu_food) cart.append(food_name.product.name) cart.append(food_name.unit_price) cart.append(food_name.quantity) cart.append(food_name.total_price) print(cart) cartlist_update.append(item) print(cartlist_update) context = {'order':order,'food':food} return render(request,'customer/update_order.html',context) def update_item_qty(request,item_id): global cartlist_update menu = OrderDetail.objects.get(id=item_id) print(menu.id) qty_id = 'qty'+str(menu.id) print(qty_id) new_quantity = request.POST.get(qty_id,'') print(new_quantity) order_id = menu.order.id ## original_food = menu.product.name price = menu.unit_price return redirect('update_order',order_id=order_id) models.py class Order(models.Model): PAYMENT_OPTIONS = ( ('VISA','VISA'), ('Master','Master'), ('Octopus','Octopus'), ('Cash','Cash'), ) STATUS = ( ('Pending','Pending'), ('Approved','Approved'), ('On the way','On the way'), ('Delivered','Delivered'), ('Completed','Completed'), ) METHODS = ( ('外賣自取','外賣自取'), ('送遞','送遞'), ) … -
File transfer link V.ht
Please let me know how we can shorten the large link into the short link (Example v.ht) As we know if we upload a file through WETransfer and then short their share link we use v.ht please let me know the basic working of this? -
How to return both total numbers and newly increased yesterday in Django rest framework(models or serializers or views?)
How to return both total numbers and newly increased yesterday in Django rest framework(models or serializers or views?), I have ten models same as below Project need to return the same data, so I really need an easy and simple way to solve it, I pasted the SQL as below to let me be clear just in case, I need the output as below in Django rest framework, thanks so much for any help. SELECT t2.total,t1.yesterday_newly_increased FROM (SELECT count(1) AS yesterday_newly_increased FROM transfer_results_info WHERE DATE(create_time) = DATE(NOW() - INTERVAL 1 DAY) ) AS t1, (SELECT count(1) AS total From transfer_results_info) AS t2 # models.py class Project(models.Model): idx = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=100, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) create_time = models.DateTimeField(auto_now_add=True) class Meta: managed = False db_table = 'project' # serializers.py class Project(serializers.ModelSerializer): create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True) class Meta: model = Porject fields = "__all__" # views.py class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by( "-idx") serializer_class = ProjectSerializer def list(self, request, *args, **kwargs): serializer = self.get_serializer(queryset, many=True) return self.get_paginated_response(serializer.data) -
How to limit displayed django form choices depending on the url a user is at?
I have users arrive at /drug_assess/?p=drugtype1 or /drug_assess/?p=drugtype2 The view for the page : class CaseView(LoginRequiredMixin, TemplateView): model = Case template_name = "se_balance/se_balance.html" def get(self, *args, **kwargs): p = self.request.GET.get("p", None) sideeffect_formset = SideeffectFormSet(queryset=SideEffect.objects.none(),) return self.render_to_response( { "page_title": p.capitalize(), "sideeffect_formset": sideeffect_formset, "sideeffect_formsethelper": SideEffectFormSetSetHelper, } ) renders a formset: SideeffectFormSet = inlineformset_factory( Case, SideEffect, fields=("se_name", "concern"), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) That is based on this model: class SideEffect(TimeStampedModel): SE_CHOICES = [ ("weight_gain", "Weight Gain"), ("parkinsonism", "Parkinsonism"), ("dystonia", "Dystonia"), ("tardive_dyskinesia", "Tardive Dyskinesia"), ("akathisia", "Akathisia"), ("prolactin", "Hyperprolactinaemia"), ("qtc", "QT Prolongation"), ("cholinergic", "Anticholinergic Side Effects"), ("sedation", "Sedation"), ("none", "None"), ] se_name = models.CharField("",max_length=200, choices=SE_CHOICES, default="none") concern = models.IntegerField("",default=50) case = models.ForeignKey(Case, on_delete=models.CASCADE) The user sees a dropdown that has all the options from SE_CHOICES available but I want to only show a subset of these depending on whether the user is at /drug_assess/?p=drugtype1 or /drug_assess/?p=drugtype2 -
django.db.utils.IntegrityError: duplicate key value violates unique constraint "auth_group_name_key" DETAIL: Key (name) already exists
I have a Custome User model defined in the models.py class User(AbstractUser): is_verified = models.BooleanField(default=False) phone_number = models.CharField(max_length=14, null=True) role = models.CharField(max_length=30, choices=ROLE_TYPE, default=ROLE_TYPE[0][0]) district = models.ForeignKey(District, on_delete=models.CASCADE, null=True) facility = models.ForeignKey(Facility, on_delete=models.CASCADE, null=True) REQUIRED_FIELDS = ["email", "first_name"] I have already set the customer user model in the app. Now I'm trying to create some groups and assign them some permission based on the group. admin_user = Group(name='special_user') admin_user.save() user_ct = ContentType.objects.get(app_label='users', model=User) can_create = Permission(name='Can create user', content_type=user_ct, codename='can_create_users') can_create.save() admin_user.permissions.add(can_create) But now I'm getting the following error:- Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "auth_group_name_key" DETAIL: Key (name)=(Special users) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Rahul Tiwari\Desktop\My_Projects\GDC\GDC-Level-10-Milestone-master\env\lib\site-packages\django\__init__.py", line … -
Django API that receives informaion [closed]
I have a problem at work, can anyone suggest training in this regard? Implement an django API that receives a person's general LinkedIn information (in linkedin) as GET and stores it in a sqlite database. -
python 3.7-compatible versions of azure-storage-blob
I'm running very simple django test server that just uploads and downloads files from and to azure-storage-blob. It works with one very old python virtual environment, that cannot be created any more due to some "deprecated errors". When letting pip choose the version of azure-storage-blob I get the following error when uploading with my simple django server: Environment: Request Method: POST Request URL: http://ramen.stat.fi:8037/uploads/form/ Django Version: 2.2 Python Version: 3.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploads.core'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/packages/urllib3/util.py" in _validate_timeout 148. float(value) During handling of the above exception (float() argument must be a string or a number, not 'tuple'), another exception occurred: File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/azure/storage/common/storageclient.py" in _perform_request 333. response = self._httpclient.perform_request(request) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/azure/storage/common/_http/httpclient.py" in perform_request 92. proxies=self.proxies) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/sessions.py" in request 361. resp = self.send(prep, **send_kwargs) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/sessions.py" in send 464. r = adapter.send(request, **kwargs) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/adapters.py" in send 307. timeout = TimeoutSauce(connect=timeout, read=timeout) File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/packages/urllib3/util.py" in __init__ 120. self._connect = self._validate_timeout(connect, 'connect') File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/requests/packages/urllib3/util.py" in _validate_timeout 151. "int or float." % (name, value)) During handling of the above exception (Timeout value connect was (20, 2000), but it must be an int or float.), another exception occurred: File "/srv/work/miettinj/simple-upload2/test-env/lib/python3.7/site-packages/django/core/handlers/exception.py" in … -
chat application is working on simple consumers.py and room.html but not working in customized consumers.py and room.html
I am developing a chat app using vscode. The problem is, when i am running the application it is opening in browser but not sending or receiving messages and also it doesn't show any error message. I am new here and so not understanding what I will do now? The fact is, when I am using simple chat template and simple consumers.py, it is working fine but not working when I am using a customized chat template and customized consumers.py. Yet click is not taking any effect on send message but is is sending and receiving messages on shel(i.e; channel is working fine). I think the problem is in customized consumers.py and romm.html. Any help will be accepted coordially... Here is the not working consumers.py from django.contrib.auth import get_user_model from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json from .models import Message User = get_user_model() class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Message.last_10_messages() content = { # 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): author = data['from'] author_user = User.objects.filter(username=author)[0] message = Message.objects.create( author=author_user, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return … -
Django project needs to run with 3 major work concerns (scheduling processes, ansible jobs, and API server). But Nginx keeps killing my workers
I use a Django backend which has 2 main workloads: API server for the Angular UI Frontend and Django Admin Screens Scheduler, which kick off about 8 difference scheduled services Metric collection: API calls against a fleet of servers for regular status updates, then stores the responses in the PostgreSQL database. Runner: Runs Ansible jobs against our fleet of servers Everything is tied to the same PostgreSQL database and often crossed referenced. So don't think of these as logical different applications, it's not. The problem all stems around Gunicorn webserver and Timeouts. Gunicorn has 6 workers. With the default settings Gunicorn loves to kill processes that have not been used in the last ~30 seconds by default. Which works great if your workload is just HTTP calls and not background processes. But since I clearly have both I have issues with gunicorn killing or not killing my processes. I had the gunicorn timeout really high at 21600 secs(6 hours) for years. With this setting it would let my Ansible jobs finish and my scheduler jobs finish. But database would have a large number of inactive (2000~4000) and active (1~20) sessions. The database would be sluggish and connections would be slow … -
Error al hacer un proceso en manage.py Intel M1
Queria saber si me podias ayudar, la cuestión es que al momento de hacer un makemigrations en Django o Python me arroja este error y no he podido solucionarlo, y no he podido en si arrancar el servidor para trabajar, no se si les ha pasado algo parecido y me puedan decir que hacer, es en una MacBook M1 > "Traceback (most recent call last): File > "/Users/jesusochoagonzalez/Documents/GitHub/cip_django/manage.py", > line 22, in <module> > main() File "/Users/jesusochoagonzalez/Documents/GitHub/cip_django/manage.py", > line 18, in main > execute_from_command_line(sys.argv) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/__init__.py", > line 401, in execute_from_command_line > utility.execute() File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/__init__.py", > line 395, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/base.py", > line 330, in run_from_argv > self.execute(*args, **cmd_options) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/base.py", > line 368, in execute > self.check() File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/management/base.py", > line 392, in check > all_issues = checks.run_checks( File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/checks/registry.py", > line 70, in run_checks > new_errors = check(app_configs=app_configs, databases=databases) File > "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/checks/urls.py", > line 13, in check_url_config > return check_resolver(resolver) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/core/checks/urls.py", > line 23, in check_resolver > return check_method() File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/urls/resolvers.py", > line 408, in check > for pattern in self.url_patterns: File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/utils/functional.py", > line 48, in __get__ > res = instance.__dict__[self.name] = self.func(instance) File "/Users/jesusochoagonzalez/env/lib/python3.9/site-packages/django/urls/resolvers.py", > line 589, in url_patterns > patterns = … -
Django shell bad scope for script files
Problem: Given the following python script script.py import time class Test: def __init__(self): print("time class", time) # In class scope def testing(): print("time method", time) # In method scope #Test() print("time top", time) # In file scope testing() When i try to execute this file in django's shell python3 manage.py shell < script.py I get the following error: time top <module 'time' (built-in)> Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/kailen/.local/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 93, in handle exec(sys.stdin.read()) File "<string>", line 12, in <module> File "<string>", line 8, in testing NameError: name 'time' is not defined This same error will happen when using any imported function/class/module inside the scope of a method/class. I have tried asigning an alias, importing the whole module and importing only the required function, nothing seems to work. Context: I was trying to code a daemon for using selenium and some of my django's models, i ended up coding it as a class … -
Deploying python Django project to Heroku error: ModuleNotFoundError: No module named 'core'
I am attempting to deploy a django project to Heroku and I'm stumped with this error right at the bottom: 2022-03-04T03:32:53.360457+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath backend.core backend.core.wsgi --log-file -` 2022-03-04T03:32:55.579764+00:00 heroku[web.1]: State changed from starting to crashed 2022-03-04T03:32:54.908542+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-03-04T03:32:54.908855+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [4] [INFO] Listening at: http://0.0.0.0:39265 (4) 2022-03-04T03:32:54.908899+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [4] [INFO] Using worker: sync 2022-03-04T03:32:54.912389+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [9] [INFO] Booting worker with pid: 9 2022-03-04T03:32:54.974193+00:00 app[web.1]: [2022-03-04 03:32:54 +0000] [10] [INFO] Booting worker with pid: 10 2022-03-04T03:32:55.113641+00:00 app[web.1]: [2022-03-04 03:32:55 +0000] [9] [ERROR] Exception in worker process 2022-03-04T03:32:55.113643+00:00 app[web.1]: Traceback (most recent call last): 2022-03-04T03:32:55.113660+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-03-04T03:32:55.113661+00:00 app[web.1]: worker.init_process() 2022-03-04T03:32:55.113661+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-03-04T03:32:55.113661+00:00 app[web.1]: self.load_wsgi() 2022-03-04T03:32:55.113662+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-03-04T03:32:55.113662+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-03-04T03:32:55.113662+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-03-04T03:32:55.113663+00:00 app[web.1]: self.callable = self.load() 2022-03-04T03:32:55.113663+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-03-04T03:32:55.113663+00:00 app[web.1]: return self.load_wsgiapp() 2022-03-04T03:32:55.113663+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-03-04T03:32:55.113664+00:00 app[web.1]: return util.import_app(self.app_uri) 2022-03-04T03:32:55.113664+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/util.py", line 359, in import_app 2022-03-04T03:32:55.113664+00:00 app[web.1]: mod = importlib.import_module(module) 2022-03-04T03:32:55.113665+00:00 app[web.1]: … -
Is there anyway I can run colab notebook from my local computer?
I am writing my Django web application locally using VScode but as part of my work is done using deep learning to create 3D reconstruction for the face and can not be done locally because I need powerful gpu. What I am trying to do is connect a function to use this notebook... so can anyone tell me if It's applicable? -
django runserver failed but gunicorn works
I am refactoring my django app, but I find that if I import an unexisted module in my urls.py, I will fail when I run python manage.py runserver, but I can still succeed if I run the gunicorn xxx.wsgi:application, I feel sucked, can anyone tell me what happend? Here is the output of runserver: /home/qspace/mmpaytestWepayImageServer # python bin/manage.py runserver Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib64/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/qspace/mmpaytestWepayImageServer/lib/python3.6/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], …