Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form model alter the data before stored in database
I want to alter thedata in form_valid What I want to do is The model has the column action in database. form has the two field model_child_0 model_child_1 Now I want to add these two and store in action These are my source code, but in vain. Where am I wrong? class MyModelUpdateView(LoginRequiredMixin, UpdateView): model = MyModel template_name = 'mymodel_edit.html' form_class = MyModelForm def form_valid(self, form): print(form.cleaned_data['model_child_0']) print(form.cleaned_data['model_child_1']) form.cleaned_data['action'] = form.cleaned_data['model_child_0'] + form.cleaned_data['model_child_1'] return super().form_valid(form) -
Python: writing file and using buffer
I'm using django to generate personalized file, but while doing so a file is generated, and in terms of space using it is quite a poor thing to do. this is how i do it right now: with open(filename, 'wb') as f: pdf.write(f) #pdf is an object of pyPDF2 library with open(filename, 'rb') as f: return send_file(data=f, filename=filename) #send_file is a HTTPResponse parametted to download file data So in the code above a file is generated. The easy fix would be to deleted the file after downloading it, but i remember in java using stream object to handle this case. Is it possible to do so in Python? -
Submit the data from dynamically genereted form
I have simple model view class template, It makes input field for name and I can get the data after submit. <form method="post" name="uploadForm" role="form" action="{% url 'mymodel-list' object.id %}" enctype="multipart/form-data" > <div class="col-md-12"> <label>name</label> <div class="detailed-info"> {% render_field form.name class="form-control" %} {% for error in form.name.errors %} <div class="text-alert"> {{ error }} </div> {% endfor %} </div> </div> <div id="additional"></div> <button type="submit" class="btn btn-info">change</button> </form> After submit I can get the data here and store in database. class MyModelUpdateView(LoginRequiredMixin, UpdateView): model = MyModel template_name = 'mymodel_edit.html' form_class = MyModelForm def form_valid(self, form): d = form.cleaned_data['name'] return super().form_valid(form) Then, I want to add the form fields which is not in model, also dynamically added by jquery. <script> $(function(){ $("#additional").html(` <input type="text" id="name2"> <input type="text" id="name3">`); }) How can I send this data (name2,name3) together with name and how can I get this data in MyModelUpdateView? -
Get value from form in template
in Django template. Model data is passed in form And I can use {{form.my_data}} in template to get the data like <textarea name="pre_action" cols="40" rows="10" id="id_my_data">this is mydata</texstarea> However, I want to get the raw data this is mydata. Because I want to use this variable in jquery. Is it possible ? or its not good way to pass the data from django to jquery? -
Django nested transacation in two databases Errored with ProgramError
I have want to have nested transaction across different databases. (I know this does not guarantee transactional commit in two databases). One layer of nexsted transaction seems ok, however if I have outer layer transaction nested in inner layer again, sometimes I see error django.db.utils.ProgrammingError: relation "xxx" does not exist (Not 100% of time, but error occurs almost every 1 out of 2 runs). Following is the code to reproduce it: with transaction.atomic(using="db1"): with transaction.atomic(using="db2"): qs = ExampleModel.objects.all() #.select_for_update() for obj in qs: obj.type = "new_value" ExampleModel.objects.bulk_update(qs, ["type"]) with transaction.atomic(using="db1"): ExampleModel.objects.using("default").bulk_update(qs, ["type"]) What could have caused this? Is there a way to get around this? (I understand the innermost transaction is not necessary, but if there are nested function calls, I'd rather wrap each call in nested transaction rather than worry about checking upper layer caller) -
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 …