Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework logging different levels on different files
I am working on Django REST framework and I want to have separate files for logging data. I want to have a file for the simple transactions e.g. GET, PUT, POST etc. and one file with the errors that I will collect in case of an error. I have been reading the Django Logging Documentation and I came up with some configurations on how to log the info data. Sample of configurations bellow: settings.py STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') LOGGING_ROOT = os.path.join(STATIC_ROOT, 'logging') LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/info.log", }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } It works as expected sample of data in file: "PUT /upload/dat.txt HTTP/1.1" 204 14 "OPTIONS / HTTP/1.1" 200 10020 "GET / HTTP/1.1" 200 9916 I tried to apply another handler in the settings.py file e.g.: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'fileInfo': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/info.log", }, 'fileDebug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/debbug.log", }, }, 'loggers': { 'django': { 'handlers': ['fileInfo'], 'level': 'INFO', 'propagate': True, }, … -
Authenticate AWS Lambda in Django
Issue: I want to authenticate the response from lambda to Django Summary: My Django app invokes an AWS Lambda with some url, lambda does the processing and a couple of seconds later should return the result to Django. Now, how do I ensure that the response from lambda is valid, and it's not someone trying to call my django endpoint? Setup: Django running on an EC2 machine behind nginx + uwsgi Lambda called from Django using boto3.client('lambda').invoke(...) Lambda code: def handler(event, context): data = event['data'] result = get_my_result(data) requests.post('https://www.example.com/foo/bar', data=json.dumps(result)) I was considering Django REST framework, but it's not like I have a specific user calling the lambda, so I think it doesn't quite suite the purpose. I have never done this kind of 3rd party service authentication in Django, not sure what the most elegant (+secure and efficient) approach would be. Thanks for help! -
Django Foreign Key class not showing
The goal is to have a dashboard show a list of users in your area. The list of users works and it shows the Username. The only issue is I can't get the users images (ideally just have 1st image) to show. There are no error messages currently. Just nothing appearing. models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, null=True) birth_date = models.DateField(null=True, blank=True) ... views.py class DashboardView(TemplateView): template_name = 've/cp/dashboard.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DashboardView, self).dispatch(*args, **kwargs) def get(self, request, pk=None): users = User.objects.exclude(id=request.user.id) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { # 'users': users, 'favorites':favorites, 'images': images, } return render(request, self.template_name, args) dashboard.html <div class="col-12"> <h2>People near you</h2> {% for user in users %} <a href="{% url 've:view_profile_with_pk' pk=user.pk %}"> <!--THIS WORKS--> <h4>{{ user.username }}</h4> <p>{{ user.profile.bio }}</p> <!--But not this... why..--> <p>{{ user.images.image.url }}</p> ''' Or this.. However it does work on view_profile page where there is a pk. Seem like it's not finding images for users, as this results in a "No images message on localhost ''' {% if images %} {% … -
Auto Fake Django Migration
I need to auto fake a Django 1.9 migration. Is there a flag that can put in the migration file that will auto fake, rather than having to log onto multiple servers and run. The migrations layout is like this migtarions |-- 0001_initial.py |-- 0002.py |-- 0003.py I know I can do ./manage.py my_app migrate 0002 --fake, but can migration 0002 be auto faked ? and all I need to run is ./manage.py my_app migrate -
What IP do I use to send data from Android to Django Server?
I need to send a JSON from my Mobile Application to a Django server on Ubuntu (which I'm using on Virtualbox). My primary OS is Windows. What IP should I use? Sequence: Android -> Windows -> Ubuntu -> Django Server -
Django - field missing from cleaned data
I am using model form and I'm trying to bypass validation of one particular field. I have ascertained that I need use the clean() method to bypass the field. however when im printing out the cleaned data the assigned_subnets field is not in the dictionary, it is missing output from print: {'site_data': None, 'switches': None, 'hostname': 'STR--RTR-01', 'template': <ConfigTemplates: STR-RTR-01>, 'model': <DeviceModel: Cisco - 4431>, 'install_date': datetime.date(2016, 5, 26), 'ospf_area': None, 'snmp_data': <SNMPData: XXXX>, 'available_subnets': <QuerySet []>} forms.py class DeviceForm(forms.ModelForm): class Meta: model = DeviceData fields = ['site_data', 'switches', 'hostname', 'template', 'model', 'install_date','ospf_area','snmp_data'] def clean(self): super(DeviceForm, self).clean() print(self.cleaned_data) if self.cleaned_data.get('assigned_subnets') in self._errors: del self._errors['assigned_subnets'] return self.cleaned_data def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) device_id = kwargs.pop('device_id', None) self.is_add = kwargs.pop("is_add", False) super(DeviceForm, self).__init__(*args, **kwargs) devicesubnet = Subnets.objects.filter(devicesubnets__device_id=device_id) sitesubnet = Subnets.objects.filter(sitesubnets__site_id=site_id) common_subnets = list(set(devicesubnet) & set(sitesubnet)) subnet_id_list = [] for s in common_subnets: subnet_id_list.append(s.id) available_subnet_data = sitesubnet.exclude(id__in=subnet_id_list) assigned_choices = [] devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id) for choice in devicesubnet_data: assigned_choices.append((choice.subnet.id,choice.subnet.subnet)) self.fields['available_subnets'] = forms.ModelMultipleChoiceField( label='Available Subnets', queryset=available_subnet_data, widget = forms.SelectMultiple( attrs = {'class': 'form-control', 'size' : '15'} ) ) self.fields['assigned_subnets'] = forms.MultipleChoiceField( label='Assigned Subnets', choices=assigned_choices, widget = forms.SelectMultiple( attrs = {'class': 'form-control', 'size' : '15'} ) ) self.fields['available_subnets'].required = False self.fields['assigned_subnets'].required = False … -
Django JSON serializer use lowercase for the model
My problem is that Django serializers convert the models names to lowercase. Client side, I get this : { "fields": {"key":"val", "key2":"val2"}, "pk" : 12, "model" : "MyApp.mymodelnametolowercase" } In the documentation is is said : Each such object has two attributes: « pk » and « model », the latter being represented by the name of the app (« sessions ») and the lowercase name of the model (« session ») separated by a dot. This is my code : def list(): lDataList = Book.objects.all() oData = serializers.serialize('json', lDataList) return oData Sorry for not respecting pep8, you'll have to talk to my boss about that though... Anyway, is there a way to tell the serializer not to convert the model name to lowercase ? -
Multiprocessing function in python3 starts throwing several Keyerrors while processing a large pandas dataframe after 1200 lines of processing
I'm processing pandas dataframes from a csv file having more than 10,000 lines of data and after processing 1200 lines properly, my code randomly starts throwing keyerrors for a few entries and at the same indexes every time, regardless of which entry falls under those indexes. Here's my code: p = multiprocessing.Process(target = calc, args = (i, c, df, a, b, file_id, user.pk)) db.connections.close_all() p.start() p.join() That's where the keyerror occurs in calc(): df = df.append([[ i, t_data.loc[c.index(i), 'Asset Description'], t_data.loc[c.index(i), 'Asset Value'], (str(key.loc[j, 'Keyword_1']) + ' ' + str(key.loc[j, 'Keyword_2'])), t_data.loc[c.index(i), 'Current Asset Category'], t_data.loc[c.index(i), 'Current Depreciation'], '%.2f' % float((int(t_data.loc[c.index(i), 'Current Depreciation']) * float(t_data.loc[c.index(i), 'Asset Value'])) / 100), key.loc[j, 'Suggested Asset Category'], key.loc[j, 'Depreciation Rate'], '%.2f' % float((int(key.loc[c.index(i), 'Depreciation Rate']) * float(t_data.loc[c.index(i), 'Asset Value'])) / 100), key.loc[j, 'Probability']]]) df[1:].to_csv('media/' + '%s_%s.csv' % (user_pk, file_id), sep='\t', mode = 'a', header = False, index = False) The error says: enter image description here "Process Process-9623: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1506, in _has_valid_type error() File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1501, in error axis=self.obj._get_axis_name(axis))) KeyError: 'the label [9622] is not in the [index]' In the final result, I get 98 keyerrors in 10,000 lines. How do I get rid of it? -
openPyxl does not append values when used in for loop
for users in user_ids: user_detail_obj = Users.objects.filter(id=users).first() benchmark_data = get_data_point(users, user_ids) headers = ['User ID', 'Name', 'Email', 'Parameter Name', 'Pre-Assess-Score', 'Current-Score', 'Org-Score'] ws = book.create_sheet(str(user_detail_obj.name) + "-" +str(users)) ws.append(headers) ws.cell(row=2, column=1).value = user_detail_obj.id ws.cell(row=2, column=2).value = user_detail_obj.name ws.cell(row=2, column=3).value = user_detail_obj.email ws.cell(row=4, column=4).value = "hi" i = 3 column = 4 for obj in benchmark_data: ws.cell(row=i, column=4).value = obj['parameter_name'] i = i +1 This code fails in inner for loop, it doesnt throw any error, excel file is properly generated with headers and their data. What I want to do is to create sheet for every user and inside that sheet we get single(User ID , name , email) multiple( parameter,name , preassess-score, curr-score, org-score) Function get_data_point gives list of dictionaries. I tried with xlsxwriter but same issue. Please suggest correct and alternative way to do this. Sample below { "result": [ { "preassess_score": 0, "current_score": 0, "current_org_score": 0, "parameter_name": "Influencing Skills", "parameter_id": 18 }, { "preassess_score": 0, "current_score": 0, "current_org_score": 0, "parameter_name": "Influence without authority", "parameter_id": 97 }, ] } -
Dockerize Django App and Apache2 with Docker
I'm trying to Dockerize my Django Web App with Docker in order to migrate it to my production server. This server is based to Linux Ubuntu 16.04 and I would like to install Apache2 into my container. I found different way to use Docker, particulary to this github repository : https://github.com/ramkulkarni1/django-apache2-docker ------------------------------------------------------------------------------------------------------------------------------------ FIRST PART - My tree project : ------------------------------------------------------------------------------------------------------------------------------------ DatasystemsCORE ├── API_GED ├── Authentification ├── Configurations ├── DatasystemsCORE ├── App1 ├── App2 ├── App3 ├── App4 ├── lib ├── static ├── templates ├── wsgi.conf ├── docker-compose.yml ├── Dockerfile ├── manage.py ├── requirements.txt ├── start.sh ------------------------------------------------------------------------------------------------------------------------------------ SECOND PART - Files according to Docker : ------------------------------------------------------------------------------------------------------------------------------------ So I created a Dockerfile : FROM ubuntu RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 3500 CMD ["apache2ctl", "-D", "FOREGROUND"] FROM python:3.6 ENV PYTHONUNBUFFERED 1 ADD ./requirements.txt /requirements.txt RUN pip install -U pip && LIBRARY_PATH=/lib:/usr/lib /bin/sh -c "pip install -r /requirements.txt --no-cache-dir" RUN mkdir /code WORKDIR /code ADD ./src . EXPOSE 8000 ADD ./start.sh /start.sh RUN … -
from common.decorators import ajax_required throws error: ModuleNotFoundError: No module named 'common'
I have a view in Django that requires @ajax_required decorator So i try to import it in my app views: from common.decorators import ajax_required Server throws an error while trying to import the module: from common.decorators import ajax_required ModuleNotFoundError: No module named 'common' Is there any good workaround on this - import the decorators module to python? Any help much appreciated! Regards, Lukasz -
access current user in django model manager
I am making a CRUD application, and I have the current piece of code in my view: def dashboard(request): template = 'dashboard/index.html' form = CustomerForm() if request.user.groups.filter(name__in=['West']).exists(): customers = Customer.objects.filter(Q(department='630') | Q(department='635')).all() elif request.user.groups.filter(name__in=['North']).exists(): customers = Customer.objects.filter(Q(department='610') | Q(department='615') | Q(department='620')).all() elif request.user.groups.filter(name__in=['East']).exists(): customers = Customer.objects.filter(Q(department='660') | Q(department='655') | Q(department='650')).all() elif request.user.groups.filter(name__in=['South']).exists(): customers = Customer.objects.filter(Q(department='640') | Q(department='645')).all() elif request.user.groups.filter(name__in=['North-West']).exists(): customers = Customer.objects.filter(Q(department='625')).all() else: customers = Customer.objects.all() context = { "customers": customers, "form": form, } return render(request, template, context) I have separate create, update and delete functions that also need to use the same if-statement. I learned about model-manages and created the following: class CustomerQueryset(models.query.QuerySet): def customer_department_query(self): if request.user.groups.filter(name__in=['West']).exists(): customers = Customer.objects.filter(Q(department='630') | Q(department='635')).all() elif request.user.groups.filter(name__in=['North']).exists(): customers = Customer.objects.filter(Q(department='610') | Q(department='615') | Q(department='620')).all() elif request.user.groups.filter(name__in=['East']).exists(): customers = Customer.objects.filter(Q(department='660') | Q(department='655') | Q(department='650')).all() elif request.user.groups.filter(name__in=['South']).exists(): customers = Customer.objects.filter(Q(department='640') | Q(department='645')).all() elif request.user.groups.filter(name__in=['North-West']).exists(): customers = Customer.objects.filter(Q(department='625')).all() else: customers = Customer.objects.all() class CustomerManager(models.Manager): def get_queryset(self): return CustomerQueryset(self.model, using=self.db) def get_customer_group(self): return self.get_queryset().customer_department_query() I of course found out that the model-manager can't access the request so I created the following middleware: class GetUser(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = (request.user) request.current_user = user user_group = request.user.groups.all() print(user) print(user_group) response = … -
Django not show tzinfo=<UTC>
I am using three different database and when I run a query the tzinfo= not appear despite in my settings the UTC timezone was set. In my developer environment the tzinfo appear, although I use just one databse there. That is why the main problem is that the databse show 1 hour minus from UTC. Here is my timezone setting: TIME_ZONE = 'UTC' My databseses: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db2_database': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db2_name', 'USER': 'db2', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'db3_database': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db3_name', 'USER': 'db3', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } My result: 'time_stamp': datetime.datetime(2018, 3, 7, 7, 50, 44)} My result in my developer environment: 'time_stamp': datetime.datetime(2018, 3, 7, 7, 50, 44, tzinfo=<UTC>)} In my databse | time_stamp | +------------------------+ | 2018-03-07 07:50:44+01 | -
Python: RegisterUserView not saving to DB (or returning HttpResponse)
So I have a simple user registration form using: RegisterUserForm ModelForm and User Model Needs to: it is suppose to create an instance of the modelform and validate the form and save the user data to db. - return HttpResponse('User Registered') Issue: Register form displays, upon clicking submit button, doesn't do anything! Stays there (it should show a HttpResponse('User Registered') View.py from django.shortcuts import render from django.views.generic import CreateView from website.forms import RegisterUserForm # Create your views here. class RegisterUserView(CreateView): form_class = RegisterUserForm template_name = "account/register.html" # Overide dispatch func - check if the user is authenticated or return forbidden def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): retVurn HttpResponseForbidden() return super(RegisterUserView, self).dispatch(request, *args, **kwargs) # Overide form valid method behaviour def form_valid(self, form): # False commit - don't save to db, locally cleaning users password first user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save(); # Change to redirect - later one! return HttpResponse('User Registered') forms.py from django import forms from django.contrib.auth.models import User class RegisterUserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: # Connect to the user model and select which fields we want input for user model model = User fields = ['username', 'email'] # Validate password matched / and clean … -
django redis - i didn't call execute at pipeline but connect pipeline
REDIS 4.0.8 django 2.0.2 mac os 10.13 class redis_input(): r=[] def __init__(self): r= redis.Redis(connection_pool=REDIS_CONNECTION_POOL) def redis_multi_set(self,list): MyList = list (set to 1,2,3,4,5,6,7,8,9,10) p = self.r.pipeline() p.watch('count') p.multi() for value in MyList: result = redis_set(value,p) if result == False : return False p.execute() return True def redis_set(self,value,pipeline): if value >= 5: return False p = pipeline p.hset('setcount:'+value,'@@@@','####') p.incr('count') return True i call redis_input().redis_multi_set([1,2,3,4,5,6,7,8,9,10]) got returned False but already setcount:1 ~ 4 in REDIS i'm not call pipeline.execute why this data in REDIS?? -
Why is my url not changing to my render template name?
I'm new in django and I just follow a tutorials. I noticed that my url is not correct after login. Can someone help me and explain how to properly do it? login.html: <form class="form-horizontal" role="form" action="{% url 'ksvt:login_user'%}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label class="control-label col-sm-2" for="id_username"> Username: </label> <div class="col-sm-10"> <input id="id_username" maxlength="30" name="username" type="text"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="id_password"> Password: </label> <div class="col-sm-10"> <input id="id_password" maxlength="30" name="password" type="password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> urls.py from django.conf.urls import url from . import views app_name = 'ksvt' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.LoginView.as_view(), name='login_user'), url(r'^logout_user/$', views.LogoutView.as_view(), name='logout_user'), ] views.py class LoginView(TemplateView): template_name = 'ksvt/index.html' def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) locations = Location.objects.all() return render(request, self.template_name, {'locations': locations}) else: return render(request, self.template_name, {'error_message': 'Your account has been disabled'}) else: return render(request, 'ksvt/login.html', {'error_message': 'Invalid login'}) Output url: http://127.0.0.1:8000/login_user/ It must be: http://127.0.0.1:8000/ Please teach mo the proper way to do this. Thank you! -
How does the modify operator work in Django?
First of all, here is an example for a typical modify operation in Django: # import class and constants from ldap3 import Server, Connection, ALL, MODIFY_REPLACE # define the server s = Server('servername', get_info=ALL) # define an unsecure LDAP server, requesting info on DSE and schema # define the connection c = Connection(s, user='user_dn', password='user_password') c.bind() # perform the Modify operation c.modify('cn=user1,ou=users,o=company', {'givenName': [(MODIFY_REPLACE, ['givenname-1-replaced'])], 'sn': [(MODIFY_REPLACE, ['sn-replaced'])]}) print(c.result) # close the connection c.unbind() I pasted this in a "modify.py"-file and ran "python modify.py runserver". The connection and operater worked perfectly. But my question is: Is it possible to make this a general function for all users? My webapp is GUI-based and I do not want to run "python modify.py runserver" for every single user. If yes, how do I bind it to my programm? For my setting.py I used the python-auth-ldap library. If you have any idea or questions to me, do not hesitate to post it. Thanks in advance. -
How to give multiple parameters to django's url in various patterns
I use Django 1.11. I'm thinking about url design like this I want to use the part surrounded by {} as a parameter. v1/ v1/{param1} v1/{param1}/category/{param2} v1/category/{param2} I tried to make the url pattern as below url(r'^v1/?$', some_view.SomeClass.as_view()), url(r'^v1/(?P<param1>.*)/?', some_view.SomeClass.as_view()), url(r'^v1/(?P<param1>.*)/category/(?P<param2>.*)/?', some_view.SomeClass.as_view()), url(r'^v1/category/(?P<param2>.*)/?', some_view.SomeClass.as_view()), After accessing v1/param1/category/param2. Then param1/category/param2 will come in the argument {param1} How do I get it done? -
The current path, login, didn't match any of these
Using the URLconf defined in project10.urls, Django tried these URL patterns, in this order: ^admin/ ^regandloginapp The current path, login, didn't match any of these. Using the URLconf defined in project10.urls, Django tried these URL patterns, in this order: ^admin/ ^regandloginapp The current path, login, didn't match any of these. Using the URLconf defined in project10.urls, Django tried these URL patterns, in this order: ^admin/ ^regandloginapp The current path, login, didn't match any of these. myproj10\urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^regandloginapp',include('regandloginapp.urls')), ] regandloginapp\urls.py from django.conf.urls import url from . import views app_name = 'regandloginapp' urlpatterns = [ url(r'^$',views.home,name='home'), url(r'^reg$', views.reg,name='reg'), url(r'^login$',views.login,name='login') ] models.py from __future__ import unicode_literals from django.db import models class Reg(models.Model): user = models.CharField(primary_key=True,max_length=20) pwd = models.CharField(max_length=20) fname=models.CharField(max_length=10) lname=models.CharField(max_length=10) dob=models.DateField() mobno=models.IntegerField() views.py from django.shortcuts import render from django.http import HttpResponse from .models import Reg from .forms import LoginForm from .forms import RegForm def reg(request): if request.method == 'POST': form = RegForm(request.POST) if form.is_valid(): form.save(commit=True) return HttpResponse('reg success') else: print(form.errors) return HttpResponse("error") else: form = RegForm() return render(request,'reg.html', {'form': form}) def login(request): if request.method == "POST": MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): un =MyLoginForm.cleaned_data['user'] pw=MyLoginForm.cleaned_data['pwd'] dbuser = Reg.objects.filter(user=un,pwd=pw) if not dbuser: … -
Connection aborted., error(104, 'Connection reset by peer') in Django
I have created an API in Django and inside that calling a third party API which accepts XML data. With 30 rows of XML it is working fine, for more rows throwing the error "Connection aborted.', error(104, 'Connection reset by peer')". The third party also provided a UI so I can test that up to 5000 rows they are accepting and returning proper result. The connection is not getting closed from either of the APIs. What issue can it be? Expected Result The post request should work properly for more data in the request as it is working fine for fewer data. Actual Result ConnectionError at /v1/send-sms/ ('Connection aborted.', error(104, 'Connection reset by peer')) Request Method: POST Request URL: http://example.com/v1/send-sms/ Django Version: 1.11 Exception Type: ConnectionError Exception Value: ('Connection aborted.', error(104, 'Connection reset by peer')) Exception Location: /home/user-135/sandbox/venv/local/lib/python2.7/site-packages/requests/adapters.py in send, line 490 Python Executable: /home/user-135/sandbox/venv/bin/python Python Version: 2.7.12 Python Path: ['/home/user-135/public_html/MyProject', '/home/user-135/sandbox/venv/lib/python2.7', '/home/user-135/sandbox/venv/lib/python2.7/plat-x86_64-linux-gnu', '/home/user-135/sandbox/venv/lib/python2.7/lib-tk', '/home/user-135/sandbox/venv/lib/python2.7/lib-old', '/home/user-135/sandbox/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/user-135/sandbox/venv/local/lib/python2.7/site-packages', '/home/user-135/public_html/MyProject', '/home/user-135/public_html/MyProject'] Server time: Wed, 7 Mar 2018 10:55:19 +0530 Reproduction Steps import requests recievers = '' url = 'https://example.com/sms/' for x in xrange(0, len(users)): y = x + 1 body_content = body phone = mobile_no recievers = recievers + … -
How can I create 'not_analyzed' index on string field using django-haystack
I am trying to index a table with employee details and I need to index employee names as it is (including the spaces and special characters in the name). Is there a way to do that using django-haystack?. -
Python Django. How can I build correct DataTable with two querysets?
I want to create DataTable with sort and some features. I tried to do this task like 8 hours in a row, but still don't know how to do it and how to do it better. Seems i have 2 queries, buy i don't know how to concate or work with them. Im trying to loop throw each, but first for loop is looping my second one. I cant use zip(), i tried. Finally i wanna get the table i can sort with fields from two different tables. How can I rewrite SQL to Django to get id, fio and sum of total_price from different model? SELECT site_users_db.id, fio, sum(total_price) total_price FROM site_users_db, buh_order WHERE buh_order.customer_id = site_users_db.id GROUP BY site_users_db.id; I have views.py @group_required('buhgalter') def index(request): qs = request.GET or dict() flag = True if (u'' in set(qs.values()) and len(set(qs.values())) == 1) or (len(set(qs.values())) < 1): flag = False if flag: f = ClientFilter(qs, queryset=Client.objects.all()) o = OrderFilter(qs, queryset=OrderItem.objects.all()) else: o = OrderFilter(qs, queryset=OrderItem.objects.none()) f = ClientFilter(qs, queryset=Client.objects.none()) message = request.session.pop('message', None) query = request.GET.get('query', None) context = {'query': query, 'message': message, 'filter': f, 'ordfilt': o} return render(request, 'buhgalt/clients.html', context) Models: class OrderItem(models.Model): ... customer_id = models.ForeignKey('Client', models.PROTECT, db_column='customer_id', … -
Django: one variable has different values in template
Like the title says, I'm passing a variable to a django template called 'old_link' as such: {% if type_disp == 'charts' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='charts' %}?{{old_link}}" class="text-primary"><i class="fa fa-fw fa-bolt"></i>Charts</a></li> {% if type_disp == 'tables' %}<li class="active">{% endif %}<a href="{% url 'matching:analytics' action=action type_disp='tables' %}?{{old_link}}" class="text-primary"><i class="fa fa-fw fa-calendar"></i>Table</a></li> The 'old_link' variable is supposed to get added to the end of the url, but it keeps giving me the wrong link. To test it I also posted the variable in another part of the template to see what it returns. You can see the correct value above the 'number of companies' section in the picture below. The value where it's posted in the sheet and the value where it's posted in the url are completely different and I'm not sure why. In the picture below you can see the url portion where the variable is supposed to be applied, it shows 'http://127.0.0.1...' instead of the 'year_min...' value that it should. Here's the full template code: <div class="item col-md-8 col-xs-12"> <div class="panel panel-default"> <div class="panel-body"> <div class="row"> <div class="col-xs-6"> <h4 class="text-headline margin-none">{{company_amount}}</h4> <p class="text-light"> <i class="fa fa-circle-o text-success fa-fw"></i> Total Funding </p> </div> <div class="col-xs-6"> <h4 … -
How do I give permission for wsgi to operate in my directory?
Apache and wsgi now have permissions problems accessing the directory in which my Django project is stored. I think I need to get back to having wsgi run as user (or maybe just group) kevin. I had this working, and I don't know what I did to stop it working, but now I get an permissions error as soon as I get past logging into my app. Unfortunately, I don't have the apache config under version control. I'm pretty sure that's where the problem is because restoring a backup of the project from when it was working didn't change anything, but tweaking permissions on the database and the root directory of the project has altered the particulars of the error message. I wasn't going to give o+w to the whole works, nor did I feel like giving an ACL to every single file or directory. Background: apache 2 as delivered with Ubuntu 16.04 LTS. Django 1.11. Python 3.5. libsqlite3.0 3.11.0 I thought that what I had in the tail of /etc/apache2/apache2.conf took care of this, in particular the line WSGIProcessGroup kevin because all the files and directories are owned by kevin.kevin, and my evidence seems to indicate that when it … -
uWSGI will not run in mixed Python environment in order to operate correctly with nginx and run Django app
Environment: Ubuntu 16.04 (with system Python at 2.7.12) running in Vagrant/Virtualbox on Windows 10 host Python Setup: System python verified by doing python -V with no virtualenv's activated. Python 3.5 is also installed, and I've done pipenv --three to create the virtualenv for this project. Doing python -V within the activated virtualenv (pipenv shell to activate) shows Python 3.5.2. Additional Background: I'm developing a Wagtail 2 app. Wagtail 2 requires Django 2 which, of course, requires Python 3. I have other Django apps on this machine that were developed in Django 1.11/Python 2.7 and are served by Apache. We are moving to Django 2/Python 3 for development going forward and are moving to nginx/uWSGI for serving the apps. I have gone through many tutorials/many iterations. All Vagrant port mapping is set up fine with nginx serving media/static files and passing requests upstream to the Django app on a unix socket, but this is giving a 502 Gateway not found error because uWSGI will not run correctly. Therefore, right now I'm simply running the following from the command line to try to get uWSGI to run: uwsgi --ini /etc/uwsgi/sites/my_site.com.ini. This file contains: [uwsgi] uid = www-data gid = www-data plugin = …