Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create invite code only registration app in Django 2.2?
How do i create invite code only registration app in Django 2.2 using "alllauth". Can't find any updated repository -
Avoid non-specified attributes on model creation
I want to create an object in Python but, since I'm using Django, I don't want to save those attributes with None or null value. When I create an object passing a couple of arguments, those attributes passed are assigned correctly; but the rest, which I wish were not created, are assigned the value "None" models.py: from djongo import models from mongoengine import * class MyClass(Document): _id = StringField(max_length=20, primary_key = True) atr1 = StringField() atr2 = StringField(max_length=300) atr3 = EmbeddedDocumentField(AdministrativeOptions) atr4 = EmbeddedDocumentField(CancelationPolicy) atr5 = StringField(max_length=50) atr6 = IntField() views.py: def index(request): a = MyClass( _id = 'TestID', atr1 = 'Xxxx' ) for key in a: print(str(key) + " = " + str(a[key])) a.save() What I get from the print loop is: _id = TestID atr1 = Xxxx atr2 = None atr3 = None atr4 = None atr5 = None atr6 = None Which means I am saving an object full of empty data. I would like to save a MyClass object with just the specified attributes in order to save space in memory. -
How to have another text input in django form in admin user page?
I am trying to add another user input but when I added it in forms.py, it didn't show me anything in admin page. Although it is showing in browser page. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id'] -
Repeat command in while loop or similar until not existing result is found
i need to repeat a cmd which always generated a new random string, after that i need to make sure that this specific string has not been generated before. I never did while loops before and im not able to figure out how to repate the cmd until a result has been found which is not already part of the database. I can't be to specific as this source is closed all this is packed into a celery task tasks.py @app.task def allocate_new_string(user_pk): user = User.objects.get(pk=user_pk) new_string = subprocess.Popen("$get_new_string_cmd", shell=True, stdout=subprocess.PIPE).communicate()[ 0].decode('utf-8').strip() try: while True: if Used_String.objects.filter(string=new_string, atom=0).exists(): new_string << how to repeat the command from above here until a new random string has been found? else: used_string = Used_String.objects.create(user=user, string=new_string, atom=0) used_string.save() logger.info(str("New String has been set) except: logger.info(str("Something went wrong while processing the task")) The function i want to have here is: Search for a none existing sting until one has found that has never been generated before or is at least not part of the database. the cmd im using isn't openSSL or something like that and it's quite likly that i hit two times the same random generated string. Thanks in advance -
duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=(patient1) already exists
On the change password page, when you enter a new password and repeat it, get out such an error, how to fix it? Request Method: POST Request URL: http://0.0.0.0:8010/callcenter/patient/2/password_change Django Version: 2.1.5 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "core_user_username_key" DETAIL: Key (username)=(patient1) already exists. Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/utils.py in _execute, line 85 Python Executable: /usr/local/bin/python Python Version: 3.7.2 Python Path: ['/opt/project', '/opt/project', '/opt/.pycharm_helpers/pycharm_display', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages', '/opt/.pycharm_helpers/pycharm_matplotlib_backend'] I tried to add forms.py class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') but it did not help forms.py class CallcenterPasswordChange(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput(), label='Новый пароль') password2 = forms.CharField(widget=forms.PasswordInput(), label='Повтор нового пароля') def clean(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='Повтор нового пароля не совпадает',) return self.cleaned_data def save(self, commit=True): user = super(CallcenterPasswordChange, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class Meta: model = User fields = ('password1', 'password2') password_cahnge.html {% extends 'callcenter/base.html' %} {% load static %} {% block inside_content %} <h1>Введите новый пароль</h1> <form action="{% url 'callcenter:password_change' patient_pk %}" method="post" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Изменить пароль"></p> </form> {% endblock %} views.py class CallcenterPasswordChangeView(AbsCallcenterView): template_name = 'callcenter/password_change.html' … -
Is it possible to force a website input to be in English?
I'm creating a website in 2 languages - English and Hebrew. I have an input field (the slug/username) which must be in English. When I enter the website from my mobile phone, I can write text in Hebrew. Is it possible to force the keyboard to be in English in this input field? I noticed that for the email address (email input) the keyboard is already in English. -
TypeError: quote_from_bytes() expected bytes after redirect
I wrote a function which after execution returns the user to the anchor page. But I'm getting an error. TypeError: quote_from_bytes() expected bytes view.py class CourseEditView(AuthorizedMixin, UpdateView): """ Edit course instances """ model = Courses form_class = CoursesEditForm template_name = 'additional_info_edit.html' def get_success_url(self): pk = self.object.employee.pk return redirect('{}#education'.format(reverse('profile', kwargs={'pk': pk}))) How to avoid a mistake? -
Based on the side nav load data in the main template
this is img I have a side nav, on selection from side nav that particular html must load in the index.html page. How do I go about implementing in django. views.py class IndexView(TemplateView): template_name = 'index.html' def get(self, request, *args, **kwargs): associate_id = id_to_numeric(request.user.username) user_details = usr_model.objects.using('users').filter(associate_nbr=associate_id) assoc_data = AssocDetailsTb.objects.filter(associate_nbr=associate_id) if assoc_data.exists(): details = AssocDetailsTb.objects.get(associate_nbr=associate_id) return render(request, 'index.html', {'details': details}) else: name ='' nbr ='' client ='' lob='' img ='' for i in user_details: name = i.associate_name nbr = i.associate_nbr client = i.client lob =i.lob img = i.associate_image print(client,lob) cli = ClientTb.objects.get(client_name = client) print(cli.id) lo = LobTb.objects.get(lob_name=lob) data = AssocDetailsTb() data.associate_name = name data.associate_nbr = nbr data.client = cli data.lob = lo data.associate_image = img data.save() return render(request, 'index.html') def page1(request): associate_id = id_to_numeric(request.user.username) details = AssocDetailsTb.objects.get(associate_nbr=associate_id) return render(request,'page1.html',{'details':details}) html <ul class="sub-menu children dropdown-menu"> <li><i class="fa fa-hospital-o"></i><a href="{% url 'qual:page1'%}">Accounts Receivable</a></li> I want to load all the templates in the same page -
how to start a task at a specific time with django & celery
I'm using Celery and it work for async but i need to setup an opertion to a specific datetime for example "the 30 of august 2019 at 11 and 35 min do this" my celery.py is very easy now but it work: import time from datetime import datetime, timedelta from datetime import date from celery import shared_task,current_task, task from celery import Celery app = Celery() @app.task def test(): print ('1') todaynow = datetime.now() print todaynow i call it from view and run print on rabbit any idea for program a task? ty -
If you see valid patterns in the file then the issue is pro bably caused by a circular import
I tried to import pyrebase in my views.py, but I've got an error arisen: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'yerekshe.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is pro bably caused by a circular import. here is my views.py: from django.shortcuts import … -
What is the meaning of detail argument in Django ViewSet?
I create a custom action method in Django ViewSet and I see detail argument. If I set detail=True I can't call this method from URL but if I set detail=False, I can call this method. May I know what is the meaning of detail argument? Here is my method=> @action(methods=['get'], detail=True) def byhello(self, request): return Response({"From Hello":"Got it"}) -
why does super function exactly use in my code?
My problem is about why exactly was super(CommentManager, self) used in code below. couldn't that instance object in filter_by_instance just be used instead? class CommentManager(Models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs Couldn't it be something like this: class CommentManager(Models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = instance.filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs -
Use some Pandas Functions into my Django App
Hi guys I have a problem: I've made my first Django App extensively using pandas in my views.py to load csvs, make some data prep and loading my pickle ML model. The problem is that all this was working fine until I tested on the deployed app (using nginx and uwsgi) where I got an error No Module named pandas which, researching seems to be a very common issue due to the fact that Django doesn't allow importing pandas directly. I saw some Django-pandas frameworks but their documentation is quite cryptic to me. Can you explain me in a simple way How can I execute those functions in pandas using Django (even with the help of a Django-pandas framework): pandas.read_csv() DataFrame.loc[...] DataFrame.sort_values() Series.unique() Series.size Series.iloc[0] DataFrame.from_dict(...) # would pickle function be affected? model = pickle.load(open(...)) model.predict() To make a better example: import pandas as pd df = pd.read_csv('...') df = df.loc[df['...'] == '...'] serie = df['...'].sort_values() serie = pd.Series(serie.unique()) serie.size value1 = int(serie.iloc[0]) df = pd.DataFrame.from_dict(dictionary) model = pickle.load(open(...)) # I don't know if pickle would give problems as well as pandas prediction = model.predict(df) -
Django template check value with URL parameter
I'm trying to create a select in html to list all month and the default value of the select should be equal to the month parameter from the URL My URL : /list-working-session/?month=7&year=2019 month and year are the parameter in My HTML: <select name="month" class="form-control" id="month" required> {% for i in months %} {% if i == request.GET.month %} <option value="{{ i }}" selected="selected">{{ i }}</option> {% else %} <option value="{{ i }}">{{ i }}</option> {% endif %} {% endfor %} </select> months is the context from the view with range(1,13) and i managed to list from 1 to 12 in select option but i can't get the IF condition to work so the default select value equal to the month in the URL. Any help would be appreciate -
Can I call location.reload() from HttpResponseRedirect?
Is it possible to call location.reload() when using HttpResponseRedirect using Django? I have a function that changes the state of an item when a button is clicked. Often the user scrolls down to click this button. The button is hooked up to the view change_state: def change_state(request, item_title, new_state): modify_state(item_title, new_state) return HttpResponseRedirect(reverse('slug-of-prev-page')) When I redirect to slug-of-prev-page the entire page will reload, snapping the page to the top. I know using something that manipulates the DOM, like React.js, would be better for this type of thing. But I'm looking for a quick solution. Or is my best bet to hook up a call to change_state, POST the data, and then call location.reload()? -
How to create another superuser in django?
I have a user created in django and I want to create another user but when I try to create it gives me error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s, %(8)s, %(9)s) Params: ['pbkdf2_sha256$150000$MqcpwdeHoQyA$yXEd56NQb5QfWNwwjZOIS0OJmzVpUizpRsTWoHNPgEw=', None, True, 'bilalkhan', '', '', '', True, True, datetime.datetime(2019, 7, 30, 8, 30, 16, 156047)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: firstapp_db.auth_user index: auth_user_email_1c89df09_uniq dup key: { : "" }', 'op': {'id': 49, 'password': 'pbkdf2_sha256$150000$MqcpwdeHoQyA$yXEd56NQb5QfWNwwjZOIS0OJmzVpUizpRsTWoHNPgEw=', 'last_login': None, 'is_superuser': True, 'username': 'bilalkhan', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 30, 8, 30, 16, 156047), '_id': ObjectId('5d4000187b6675a2aa5457b5')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} Version: 1.2.33 -
Why validate_<field> triggered 3 times? Django Rest Framework
I have following cutsom base Serializer: class CustombBaseSerializer(Serializer): def get_object(self, model, **kwargs): try: return model.objects.get(**kwargs) except model.DoesNotExist: raise ValidationError( f"{model._meta.verbose_name.title()} Does Not Exist." ) and following serializer inherited from CutsomBaseSerializer (above): class TextAnswerSerializer(CustombBaseSerializer): sheet_code = CharField( max_length=11, ) def validate_sheet_code(self, value): return self.get_object(SheetCode, pk=value) def validate(self, attrs): if attrs.get('sheet_code').user_id != attrs.get('user_id'): raise ValidationError("It's not yours!") if attrs.get('sheet_code').kind == 'infinity': # some stuff elif attrs.get('sheet_code').kind == 'feedback': # some more stuff else: # some other stuff return attrs when I send data to this serializer, it raises an exception: myapp.models.SheetCode.MultipleObjectsReturned: get() returned more than one SheetCode -- it returned 3! I find that, the validate_sheet_code triggered 3 times. what's the problem? and how to fix it? -
How to display the custom message with django axes?
I implemented the django-axes to lockout the user if the user tried too many attempts.But the one thing is if the user account locked it displays the messages in the new page with Account locked: too many login attempts. Please try again later which is fine but however i want to modify this message like try again in 1 minutes or something like this.And also i want to display this message along with my login form like the django contrib messages does. settings.py import datetime AXES_COOLOFF_TIME = datetime.timedelta(minutes=2) AXES_FAILURE_LIMIT = 5 views.py if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = form.cleaned_data['remember_me'] user = authenticate(request, username=username, password=password) if user and user.is_active: login(request, user) if not remember_me: request.session.set_expiry(0) redirect_url = request.GET.get('next', 'home') return redirect(redirect_url) elif user and not user.is_active: messages.info(request, 'Your account is not active now.') else: messages.error(request, 'Invalid Username and Password') -
If a client login from a particular centre then that client could see only his centre in foreign key
I have registered a user from a particular centre and after that he logged in .Now I want that he could only see his centre name as foreign key when he fills the cabin form .I have centre model where all the centre details will be there which is foreign key to userprofile model and cabin model has foreign from userprofile .so now i want when user loggin from a particular centre he see his centre name only in dropdown menu of foreign key .since I am new to django kindly help me .Thank you in advance. models.py class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False,blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Centre, self).save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse("index") Roles = ( ('sales', 'SALES'), ('operations', 'OPERATIONS'), ('cashier', 'CASHIER'), ('frontdesk', 'FRONTDESK'), ('client', 'CLIENT'), ) class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='users/', blank=True, default='default/testimonial2.jpg') slug = models.SlugField(unique=False, blank=True) centres … -
How to use registration(signup/login) modal(bootstrap template) with django views?
I am new to programming. I found nice bootstrap modal for registration, so i put it to my html code and it looks nice but nothing can be pressed or post. Before i was using django and UserCreationForm without modals. So help me to concatenate these two things: so this is my bootstrap modal that i found <!-- Modal --> <div class="modal fade" id="elegantModalForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <!--Content--> <div class="modal-content form-elegant"> <!--Header--> <div class="modal-header text-center"> <h3 class="modal-title w-100 dark-grey-text font-weight-bold my-3" id="myModalLabel"><strong>Войти</strong></h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <!--Body--> <form type="post" action="{% url 'common:login' %}"> <div class="modal-body mx-4"> <!--Body--> <div class="md-form mb-5"> <input type="email" name="useremail" id="Form-email1" class="form-control validate"> <label data-error="wrong" data-success="right" for="Form-email1">Ваша почта</label> </div> <div class="md-form pb-3"> <input type="password" id="Form-pass1" class="form-control validate"> <label data-error="wrong" data-success="right" for="Form-pass1">Пароль</label> <p class="font-small blue-text d-flex justify-content-end">Забыли <a href="#" class="blue-text ml-1"> пароль?</a></p> </div> <div class="text-center mb-3"> <button type="button" class="btn blue-gradient btn-block btn-rounded">ок</button> </div> <p class="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2"> или войти с помощью:</p> <div class="row my-3 d-flex justify-content-center"> <!--Facebook--> <button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-facebook-f text-center"></i></button> <!--Twitter--> <button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-twitter"></i></button> <!--Google +--> <button type="button" class="btn btn-white btn-rounded z-depth-1a"><i … -
Django orm left join queries without foreign keys
This is my SQL query: select (case when a.hosting <= b.yr and (a.hosting * 1000) <= b.yo then 1 else 2 end) as status from a left join b on a.phone_user = b.phone_u and a.per = b.lotus_number; I have tried the following modules: from django.db.models.sql.datastructures import Join from django.db.models.fields.related import ForeignObject I've implemented virtual fields but I don't know how to Join with subtable fields without using loops I want to give me a virtual field, but now that I can't implement it, my mind is in a loop -
TypeError: 'datetime.date' object is not subscriptable
I'm trying to create a custom template tag which takes 3 arguments. I'm trying to calculate the number of days between two dates, while excluding the weekends days from that count. And depending on the department, the weekend is different for each user. So I need start_date, end_date, user_id to be passed onto the template tag function. This is what I have done so far: from django import template from datetime import datetime, timedelta, date register = template.Library() @register.filter('date_diff_helper') def date_diff_helper(startdate, enddate): return [startdate, enddate] @register.filter(name='date_diff') def date_diff(dates, user_id): start_date = dates[0] end_date = dates[1] count = 0 weekends = ["Friday", "Saturday"] for days in range((end_date - start_date).days + 1): if start_date.strftime("%A") not in weekends: count += 1 else: start_date += timedelta(days=1) continue if start_date == end_date: break start_date += timedelta(days=1) return count This is how I'm calling these functions in template: {{ leave.start_date|date_diff_helper:leave.end_date|date_diff:leave.emp_id }} When I run the code, it gives me TypeError saying 'datetime.date' object is not subscriptable. When I tried to check the type of dates parameter in date_diff function, it says: < class 'list'> < class 'datetime.date'> But when it tries to assign start_date as the first date object, as in start_date = dates[0], it throws … -
Does 'creating' a new record override existing ones with same key?
The first code below both creates (if it doesn't exist yet) and override (if it exists) record in db. It's convenient. I would like to know if this creates problem in the DB. I reviewed the table records and it doesn't create duplicates. record = Foo(key='123', value='Hello) record.save() or try: foo_q = Foo.objects.get(key='123') foo_q.value = 'Hello' foo_q.save() except: record = Foo(key='123', value='Hello) record.save() It works but is it safe to continue using or should I query if it exists and update the model. -
Django model: TypeError: 'Manager' object is not callable
I'm developing a Rest API with django. I have this model: from django.db import models from devices.models import Device class Command(models.Model): id = models.AutoField(primary_key=True, blank=True) command_name = models.CharField(max_length=70, blank=False, default='') time = models.DateTimeField(auto_now_add=True, blank=True) timeout = models.TimeField(blank=True) command_status= models.IntegerField(blank=False) tracking = models.IntegerField(blank=False) result_description = models.CharField(max_length=200, blank=False, default='') ssid = models.CharField(max_length=31, blank=False, default='') device = models.ForeignKey(Device, on_delete=models.CASCADE) in the views I have this part of code: @csrf_exempt def command_detail(request, rssid): try: print("Heeeeeeeeeeeeeeeeeeeeeeeeelllo 1111 rssid: ", rssid) commands=Command.objects().filter(ssid=rssid) print("Heeeeeeeeeeeeeeeeeeeeeeeeelllo 2222") command=commands[0] except Command.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) If I execute my server it works fine without any error but if I trie to test the corresponding server with curl like that: curl -X POST http://127.0.0.1:8000/api/commands/cmdssid1?command_status=40 I get as curl result a so big html indicating an Internal Error in the server and in the django part I got those traces: July 30, 2019 - 08:00:01 Django version 1.10.1, using settings 'project-name.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ('Heeeeeeeeeeeeeeeeeeeeeeeeelllo 1111 rssid: ', u'cmdssid1') Internal Server Error: /api/commands/cmdssid1 Traceback (most recent call last): File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, … -
Exception in thread django-main-thread: TypeError:__init__() got an unexpected keyword argument 'fileno'
I am trying to perform load tests on a django application with locust. However, when I try to perform these with multiple simulated users, I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 213, in run httpd.serve_forever() File "/usr/lib/python3.6/socketserver.py", line 241, in serve_forever self._handle_request_noblock() File "/usr/lib/python3.6/socketserver.py", line 315, in _handle_request_noblock request, client_address = self.get_request() File "/usr/lib/python3.6/socketserver.py", line 503, in get_request return self.socket.accept() File "/usr/lib/python3.6/socket.py", line 210, in accept sock = socket(self.family, type, self.proto, fileno=fd) TypeError: __init__() got an unexpected keyword argument 'fileno' This error seems very weird to me, because the socket __init__() function is part of a default library in which this error shouldn't occur. I suspect that the error I see here is a red herring, and that the real error is hidden, but I thought that I might as well ask here in case someone knows why this occurs. Some additional information: When I did the load test on django's built-in development server (wsgi) (i.e. started the …