Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to update field to add value to existing value in sqlalchemy in python?
I need help with sqlalchemy using expression. Example: update test set count = (count+1) where col=1; I need this query in sqlalchemy sqlalchemy Example: db = session_postgres.query(TestAlc).filter(StockMovementReport.col==1) #db.update({"count":(count+1)}); Table: Col | count 1 | 10 1 | 20 1 | 31 2 | 35 After update query output Col | count 1 | 11 1 | 21 1 | 32 2 | 35 -
GeoDjango and Mixer. 'PointField' has no attribute '_meta'
I have a Location model that defined (roughly) like this: from django.contrib.gis.db import models class Location(models.Model): address = models.CharField(max_length=255) gis = models.PointField(null=True) name = models.CharField(max_length=255) Whenever I try to mixer.blend('app.Location') I get: AttributeError: Mixer (app.Location): type object 'PointField' has no attribute '_meta' It works when I blend it with the field set to None or Point, but I wonder if there is a way to set it up so it can do it on its own, especially since faker can generate this data. -
Displaying the actual objects for generic foreign keys in admin page
Say I have the following models: class Car(models.Model): name = models.CharField(max_length=30) class Bike(models.Model): name = models.CharField(max_length=30) class Favorite(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') where either a Car or a Bike object can be favorited. Now in the admin page, the "new Favorite object" page will look like this. But this isn't very user-friendly since I'd have to know the object_id for the object I want to favorite. Isn't there a way where after selecting the content_type, the objects will be displayed by name, like how a regular ForeignKey works. I think GenericTabularInline might be helpful, but I'm not sure and I wouldn't know how to use it. I need an expert's opinion. -
Django Forbidden CSRF token missing or incorrect when jQuery POST
I'm stumbling over the integration of jQuery POST with Django. I have Python 3.6, Django 1.10.5 without changes. The view works if @csrf_exempt and the form is valid. I'm not creating a session prior. I assume that Session management is decoupled from CSRF enforcement. urls.py urlpatterns = [ url(r'^parent$', views.create_parent, name='create_parent'), forms.py class ParentForm(forms.ModelForm): class Meta: model = Parent fields = ['first_name', 'last_name'] views.py def create_parent(request): if request.method not in ['POST', 'GET']: return Error.http405() elif request.method == 'GET': form = ParentForm() return render(request, 'parent_form.htm', {'form': form}) elif request.method == 'POST': form = ParentForm(request.POST) if form.is_valid(): try: p = Parent(first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) p.save() return HttpResponseRedirect(reverse('schedule:thanks', args=[p.id])) except Parent.DoesNotExist: raise Http404("Parent does not exist") except Exception as e: return HttpResponse('Form valid but: ' + str(request.POST) + ': ' + str(e)) else: return HttpResponse('Form invalid: ' + str(request.POST) + ': ' + str(form.errors)) parent_form.htm <form id="parent" action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"/> </form> parent.js function submitParentForm(event) { event.preventDefault(); url = "/schedule/parent"; var values = $(this).serialize(); // update cookie document.cookie = "csrftoken=;expired=Thu, 01 Jan 1970 00:00:00 UTC';path=/;"; var form = $("form")[0]; document.cookie = "csrftoken=" + form.csrfmiddlewaretoken.value; // add X header $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { … -
Cannot import models from another app in Django
so I have 2 apps running in the same project. My files are structured as follows: /project_codebase /project __init.py settings.py urls.py wsgi.py ... /app1 ... /app2 ... manage.py So, I for some weird reason have a different name for my base directory (that is, it ends with codebase). Hopefully, that is not an issue. In my settings.py, I have this: INSTALLED_APPS = [ ... 'app1', 'app2', ] Ok, so in my models.py (from app2), I can easily import models from app1 with from app1.models import *, however, when I use from app2.models import * in my models.py (from app1), I get an ImportError. Any solutions to this? -
is it posible to insert value in a model conatining two foreign key?
I have a model with two foreign key and I want to insert the values in one row. The model for example is :- from __future__ import unicode_literals from django.db import models from cms.models.authUser import AuthUser from cms.models.masterCmsUserTypes import MasterCmsUserTypes class MasterCmsUser(models.Model): userId = models.ForeignKey(AuthUser,db_column='userId') userTypeId = models.ForeignKey(MasterCmsUserTypes, db_column='userTypeId') status = models.BooleanField(db_column="status", default=False, help_text="") isDelete = models.BooleanField(db_column="isDelete", default=False, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="") idv2 = models.IntegerField(db_column='idV2') class Meta: managed = False db_table = 'master_cms_user' THis is my views:- @login_required def admin_user_add(request): try: master_cms_user_type_list =MasterCmsUserTypes.objects.all() first_name = request.POST.get('firstName') last_name = request.POST.get('lastName') password = request.POST.get('password') username = request.POST.get('username') confirmPassword = request.POST.get('confirmPassword') email = request.POST.get('email') status = request.POST.get('status') userTypeId = request.POST.get('userType') if status is None or status == '': status = False else: status = True staff=False superUser=False if password != confirmPassword: messages.error(request,'Password and Confirm Password must be same') if request.method =='POST': authUser = AuthUser(firstName=first_name,lastName=last_name,password=password,username=username,email=email, isActive=status,isStaff=staff,isSuperuser=superUser) authUser.save() messages.success(request, 'Successfully added to the university list') print authUser.id authid = int(authUser.id) # ci= get_object_or_404(AuthUser, id=authUser.id) # print authid # myu_admin_user = AuthUser.objects.get(id=authid) # print myu_admin_user cmsStatus=True cmsDelete=False masterCmsUser = MasterCmsUser(userId=authid,userTypeId=userTypeId,status=cmsStatus,isDelete=cmsDelete) masterCmsUser.save() return render(request, 'templates/admin_user_management/admin_user_add.html',{ 'master_cms_user_type_list':master_cms_user_type_list }) except Exception as e: print e raise Http404 now when i removed my … -
global search Django rest framework
I have a question regarding search_filter in djangorestframework, after reading the docs, I didn't come up with a solution to my problem, and it is that I currently on the page I'm displaying some user data for today, also I have some date about users which is set to occur in the future, now when I search I'm only seeing users for today and I want to be able to see all of them but I don't want to interfere my current view integrity. I've google up a bit, and only thing I found is this example of how to make a Global Search, and it's fine but, I was wondering if I can do this manipulation in my current view so I don't build another view, etc, so is there a way to make my search show me all my data? My current apiview: from rest_framework import viewsets, permissions, filters from cms.restapi.pagination import StandardResultsOffsetPagination from cms_sales.models import LeadContact from cms_sales.restapi.permissions.lead_contact_permissions import LeadContactPermissions from cms_sales.restapi.serializers.lead_contact_serializer import LeadContactSerializer class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('vinclucms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('vinclucms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) filter_date = self.request.query_params.get('filter_date', None) if filter_date is not None: queryset = queryset.filter(next_action_date=filter_date) return … -
Django Tutorial Page not found 404
This problem is well documented on Stack, but no answers have solved it for me. Earlier today I successfully got past this step as a complete beginner, but have since started over and cannot understand why I keep getting this error. I have double checked so many times and see no difference at all between my code and the folders they are in compared to as instructed in the tutorial Error: Page not found (404) Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^admin/ The empty path didn't match any of these. My directories and code: urls.py located: outerMysite/mysite from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] urls.py located: outerMysite/polls from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py located: outerMysite/polls from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") settings.py located: outerMysite/mysite DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] … -
efficient sort on combined django querysets
I am trying to achieve very complex kind of sort using django queryset.Its more like how your comments and your friends and family comments appears on top in facebook and youtube comment. to breakdown, i am combining different queryset to same model achieve a result. my_assinged_tasks = Tasks.objects.filter(to=request.user) non_assigned_tasks = Tasks.objects.filter(to__isnull=True) tasks_created_by_my_direct_supervisor = Tasks.objects.filter(to=request.user) suggested_todo_task = ##Some Complex Logic to detect what task are similar to my completed tasks uncompleted_tasks = ## Criteria tasks = my_assinged_tasks | non_assigned_tasks | tasks_created_by_my_direct_supervisor | suggested_todo_task | uncompleted_tasks I want to sort it in order of 1 - tasks_created_by_my_direct_supervisor 2 - my_assinged_tasks 3 - uncompleted_tasks ...... the only solution i have in my mind is to create a dict and loop through each query set result individually and populate that dict accordingly which is very in efficient that way. Is there a more efficient way of achieving this? -
Use of ._meta Django
I want to ask about the use of ._meta in this code ? I didn't find a documentation that explains the use of .meta def resend_activation_email(self, request, queryset): """ Re-sends activation emails for the selected users. Note that this will *only* send activation emails for users who are eligible to activate; emails will not be sent to users whose activation keys have expired or who have already activated. """ if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) for profile in queryset: if not profile.activation_key_expired(): profile.send_activation_email(site) resend_activation_email.short_description = _("Re-send activation emails") -
set variable into queryset of forms.py from my generic view or url
i want to set a dynamic variable into queryset of forms.py , i used __init__ to pass the dynamic variable , i think the code in forms.py is correct , the problems is how to pass tha variable in views code of forms.py : class ContainerForm(forms.ModelForm): vehicle=forms.ModelChoiceField(required=False,queryset=Vehicle.objects.all(),widget=forms.Select(attrs={'class':'form-control'})) code of views.py class ContainerCreate(CreateView): form_class = ContainerForm(id= vehicle_id) template_name = 'vehicule_app/container_form.html' the error said : Exception Value:'ContainerForm' object is not callable -
How to configure static files in Django app for Heroku?
I deployed a django app to heroku, using "git push heroku master". It works fine but i have problem with static files. I can't configure it. What i have to do to get it started? Can you help me guys? settings.py DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") base.html <link rel='stylesheet' href='{% static "css/base.css" %}' /> urls.py from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from accounts.views import (login_view, register_view, logout_view) from timetable.views import home urlpatterns = [ url(r'^timetable/', include("timetable.urls", namespace='timetable')), url(r'^admin/', admin.site.urls), url(r'^home/', register_view, name='register'), url(r'^login/', login_view, name='login'), url(r'^logout/', logout_view, name='logout'), url(r'^$', home, name='controler'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Can't access .env file from python
I have django settings.py file and .env in same folder. .env file: DEBUG=True SECRET_KEY=123456678910 In settings.py i call theese variables as SECRET_KEY = os.environ.get('SECRET_KEY'). Django says me django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. What am I doing wrong? -
null value in column "wins" violates not-null constraint
When i'm trying to create a user in django with admin or by my register function in views, it gives me this error: by register function: IntegrityError at /register_user/ null value in column "wins" violates not-null constraint DETAIL: Failing row contains (3, pbkdf2_sha256$36000$3SoR8l6dEXRD$CkFB+RRKeJPUPeux4EByqkYFkGLgkhI..., null, f, Ion, , , ion@pidginhost.com, f, t, 2017-05-08 10:47:39.860612+00, f, null). by add user in admin IntegrityError at /admin/football_app/customuser/add/ null value in column "wins" violates not-null constraint DETAIL: Failing row contains (7, pbkdf2_sha256$36000$o6UGPqAw72hi$qfbgoRAoJn4WmlK010VbfCzeu3+Fo0w..., null, f, Ion, , , , f, t, 2017-05-08 11:02:54.725688+00, f, null). models.py class CustomUser(AbstractUser): selected = models.BooleanField(default=False) wins = models.IntegerField() REQUIRED_FIELDS = ['email', 'selected', 'wins'] def __str__(self): return self.username class Score(models.Model): VALUE = ( (1, "Score 1"), (2, "Score 2"), (3, "Score 3"), (4, "Score 4"), (5, "Score 5"), (6, "Score 6"), (7, "Score 7"), (8, "Score 8"), (9, "Score 9"), (10, "Score 10"), ) granted_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=0) granted_to = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name='granted_to') grade = models.PositiveSmallIntegerField(default=0, choices=VALUE) def __str__(self): return str(self.granted_to) views.py def register_user(request): data = dict() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(user.password) user.save() return redirect('/login/') else: data['form'] = UserForm() return render(request, 'register_user.html', data) I'm using the wins field to add +1 to Users … -
Fonts on header page "shrinkes" on different pages. Using Django template language
My header element "shrinkes" on pages with detailed view like post page or profile page. (Here's a screenshots). What is the problem? How can I fix header size so it be the same on each page? Sorry for bad English btw. =) Here's code and screenshots. Will be grateful for help. I use Django and it's template language but I can add an output from browser later. main page screenshot; post page screenshot body { margin-top: -5px; margin-left: -5px; margin-right: -5px; background-image: url("http://pattern4site.ru/images/fabric/_rebig/30-svetlaya-besshovnaya-tekstura-tkani.png"); } .header-page { padding: 30px 20px 20px 56px !important; background-color: #ff6666; margin-top: -20px; } .header-page h1 { color: white; padding-left: 280px; line-height: 15px; font-size: 36; font-family: 'Roboto-Slab', serif; } .header-page .user-panel{ padding-left: 800px; } .header-page .user-panel ul{ list-style: none; margin-top: -70px;; padding-left: 0; } .header-page .user-panel a{ font-family: 'Roboto-Slab', serif; font-size: 27; color: white; text-decoration: none; } .header-page .user-panel a:hover{ background: #fc5555; padding: 0 10px; } .header-page .user-panel #username, #admin, #logout, #login, #register{ text-align: center; } .header-page .menu{ padding-left: 515px; margin-top: -60px; } .header-page .menu ul{ list-style: none; margin: 0; padding-left: 0; } .header-page .menu li{ display: inline; } .header-page .menu a{ font-family: 'Roboto-Slab', serif; font-size: 27; color: white; margin: 0 20px; text-decoration: none; padding-top: 53px; padding-bottom: … -
Django 1.7 test error
i am trying to run test on my django app(1.7) but the after running ./manage.py test the error is appearing django.db.utils.ProgrammingError: type "geometry" does not exist.So basically when i searched,it appears that gis extension is missing from postgres.I have installed extension but the error is still the same. -
Pass in data from Django template to React Component
I am using Django, Webpack and a React setup. I have managed to render my component on a div on my template like so: Index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Example</title> </head> <body> {% load render_bundle from webpack_loader %}<h1>Example</h1> <div id="react-app"></div> {% render_bundle 'main' %} </body> </html> My react app, is binded to the root DOM node like so: Index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; const rootElement = document.getElementById('react-app'); ReactDOM.render(<App />, rootElement); How do I pass in data from the HTML to the React component? -
Command ["Wkhtmltopdf"] returned non-zero exit 6
When trying to load a pdf using wkhtml to pdf i get this error CalledProcessError at /Reservations/mybookings/1/pdf Command '['wkhtmltopdf', '--encoding', u'utf8', '--quiet', '/tmp/wkhtmltopdfc3a0GU.html', '-']' returned non-zero exit status -6 It was working on local but then when I deployed it to server and changed static directory it stopped working. -
Angular js efficiency, how does it works, questions
Used jquery for long. I'm a beginner at angular js, and I see a lot of magic that is done by the library. Some questions I ask myself and haven't got and answer yet. On startup, does angular really scan all the HTML to find directives? Because there are so many ways to write them, like ng-something attribute, <!-- directive: --> comment, {{expr}}, and many more. 1. Does it uses regex to find all of these? 2. Isn't that a big overhead to find all of these in HTML, that could be very long (thousands of DOM nodes), suppose that I want to use it in a large SPA. Mobile phones browsers are somewhat slower so that might be an issue? 3. Does angular internally uses the observer pattern? 4. How can I avoid angular {{}} syntax conflict with my server side template, django? -
How to make POST request to my HTTPS server from Chrome Extension?
How can I make a POST to my HTTPS Django server on a Chrome Extension? I always get a 403 No Referer error because the source URL is chrome-extension://..., which is a non-secure source. -
How to do an accent-insensitive TrigramSimilarity search in django?
How can I add accent-insensitive search to following snippet from the django docs: >>> from django.contrib.postgres.search import TrigramSimilarity >>> Author.objects.create(name='Katy Stevens') >>> Author.objects.create(name='Stephen Keats') >>> test = 'Katie Stephens' >>> Author.objects.annotate( ... similarity=TrigramSimilarity('name', test), ... ).filter(similarity__gt=0.3).order_by('-similarity') [<Author: Katy Stevens>, <Author: Stephen Keats>] How could this match test = 'Kâtié Stéphèns'? -
Unkown Import error
When I am try to deploy my django app on gcloud I get ERROR: (gcloud.app.deploy) Error Response: [4] DEADLINE_EXCEEDED On local machine all is work fine, report log: Traceback (most recent call last): File "/env/lib/python3.4/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/env/lib/python3.4/site-packages/django/utils/deprecation.py", line 134, in __call__ response = self.process_request(request) File "/env/lib/python3.4/site-packages/django/middleware/locale.py", line 24, in process_request i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf) File "/env/lib/python3.4/functools.py", line 434, in wrapper result = user_function(*args, **kwds) File "/env/lib/python3.4/site-packages/django/conf/urls/i18n.py", line 29, in is_language_prefix_patterns_used for url_pattern in get_resolver(urlconf).url_patterns: File "/env/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/env/lib/python3.4/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/env/lib/python3.4/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/env/lib/python3.4/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/env/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/vmagent/app/src/main/urls.py", line 24, in <module> It possible can be error of i18n? But in this project i don't … -
How can I stop a django field from displaying Queryset when editing a form?
I have a field that takes in a list of skills. I am parsing on commas and checking if the skill exists, if it doesn't then I add it to my Skills table. My skills are saved correctly when I view them in admin, but when trying to edit the field shows <QuerySet [<Skills: c#>, <Skills: c++>]> with an input of c#,c++. How can I make this field appear blank, ready for fresh input? Here is some code from creation: project = Project() # # Handle desired skills desired = form.cleaned_data.get('desired_skills') if desired: # parse known on ',' skill_array = desired.split(',') for skill in skill_array: stripped_skill = skill.strip() if not (stripped_skill == ""): # check if skill is in Skills table, lower standardizes input if Skills.objects.filter(skill=stripped_skill.lower()): # skill already exists, then pull it up desired_skill = Skills.objects.get( skill=stripped_skill.lower()) print("already have:",desired_skill) else: # we have to add the skill to the table desired_skill = Skills.objects.create( skill=stripped_skill.lower()) # save the new object desired_skill.save() print("saving:",desired_skill) # add the skill to the current profile project.desired_skills.add(desired_skill) project.save() Thanks for any help! -
Django html onclick to open another html page
i am currently facing problem on opening html page using django although i have tried to figure out on the url.py, view.py, and the html page. My code is stated below: batterycurrent.py under views folder from __future__ import absolute_import from __future__ import unicode_literals from django.core.files.storage import default_storage from django.core.urlresolvers import reverse_lazy from django.http import HttpResponseRedirect from django.utils import timezone from django.views.generic import FormView, TemplateView from sendfile import sendfile import os.path from .mixin import AjaxTemplateMixin, PermissionRequiredMixin, PageTitleMixin from ..forms import DiagnosticsForm from ..tasks import dump_diagnostics from django.shortcuts import render class DiagnosticMixin(PageTitleMixin, PermissionRequiredMixin): permission_required = ['system.view_log_files'] page_title = 'Diagnostics' form_class = DiagnosticsForm class BatteryCurrentView(DiagnosticMixin,FormView): template_name = 'system/batterycurrent.html' def batterycurrent(request): return render(request, 'system/batterycurrent.html') url.py from __future__ import absolute_import from __future__ import unicode_literals from collections import OrderedDict from django.conf.urls import url from django.core.urlresolvers import reverse_lazy from .views import BatteryCurrentView sub_urlpatterns['diagnostic'] = [ url(r'^diagnostics$', DiagnosticView.as_view(), name='diagnostic'), url(r'^diagnostics/download', DiagnosticDownloadView.as_view(), name='diagnostic-download'), url(r'^diagnostics/batterycurrent', BatteryCurrentView.as_view(), name='batterycurrent'), ] **the batterycurrent.html is under diagnostic file. batterycurrent.html <li><a href="{% url 'system:batterycurrent' %}">Battery Current Vs Timestamp</a></li> when i started to execute the code, the errors appeared i) importError batterycurrentView couldn't be imported ii)Reverse for 'batterycurrent' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Please guide me on this -
django get data response from specific ip
I am working on an API integration. I am using django==1.10.5 and python34. The app involves sending request from my server to another server which is connected through a VPN. password = "xxxxxxxxxxxxxxxxx" spid = "xxxxxxxxxxxxxxxxx" serviceid = "xxxxxxxxxxxxxxxxx" sendershortcode = "xxxxxxxxxxxxxxxxx" initiator = "xxxxxxxxxxxxxxxxx" initiator_password = "xxxxxxxxxxxxxxxxx" recieveridentifier = "xxxxxxxxxxxxxxxxx" body = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://api-v1.gen.mm.vodafone.com/mminterface/request"> <soapenv:Header> <tns:RequestSOAPHeader xmlns:tns="http://www.huawei.com/schema/osg/common/v2_1"> <tns:spId>"""+spid+"""</tns:spId> <tns:serviceId>"""+serviceid+"""</tns:serviceId> <tns:spPassword>"""+encoded_password+"""</tns:spPassword> <tns:timeStamp>"""+reqTime+"""</tns:timeStamp> </tns:RequestSOAPHeader> </soapenv:Header> <soapenv:Body> <req:RequestMsg> <![CDATA[<?xml version="1.0" encoding="UTF-8"?> <request xmlns="http://api-v1.gen.mm.vodafone.com/mminterface/request"> <Transaction> <CommandID>SalaryPayment</CommandID> <LanguageCode></LanguageCode> <OriginatorConversationID>"""+originator+"""</OriginatorConversationID> <ConversationID></ConversationID> <Remark></Remark> <Parameters> <Parameter> <Key>Amount</Key> <Value>200</Value> </Parameter> </Parameters> <ReferenceData> <ReferenceItem> <Key>QueueTimeoutURL</Key> <Value>http://138.197.41.74:80/user/test/</Value> </ReferenceItem> </ReferenceData> <Timestamp>"""+reqTime+"""</Timestamp> </Transaction> <Identity> <Caller> <CallerType>2</CallerType> <ThirdPartyID>broker_4</ThirdPartyID> <Password>k+JtvqNV3eg=</Password> <CheckSum>CheckSum0</CheckSum> <ResultURL>http://138.197.41.74:80/results/B2C/</ResultURL> </Caller> <Initiator> <IdentifierType>11</IdentifierType> <Identifier>"""+initiator+"""</Identifier> <SecurityCredential>YwBlXbjEFjh/UQ0cZhrk+4X9TxAIc3z8zf4rXZRZRLW32cm+c/lJYQ3ZFVThna+41x8EukAHZhuR44QiF5J1GF/9QaYwK1i1rIX2i/Fa9bRJ4fn/REYd/vE1/pUPn4GnfLib151RYQyO7KsLipLFk8Hr9SYq62MSrOxgyAd1bJXQ4SdEJwk0LtCZSTWBaZySbPJt/P0FBfG71kLkrP0P0pn1cuuuJoA3KJ5+RuX5WpsXR0HFFyyJFEwAlQ9oSmKW5fzCwEKMaKTKgScfyDXmhuiFZvrSmdV3H0o4Hhl17IQR8M1fwIk9JfxrSUqVRBrEqVKJrOOlSF/T7xLJTo0fpQ==</SecurityCredential> <ShortCode>777133</ShortCode> </Initiator> <PrimaryParty> <IdentifierType>4</IdentifierType> <Identifier>777133</Identifier> <ShortCode>777133</ShortCode> </PrimaryParty> <ReceiverParty> <IdentifierType>1</IdentifierType> <Identifier>"""+recieveridentifier+"""</Identifier> <ShortCode>ShortCode1</ShortCode> </ReceiverParty> <AccessDevice> <IdentifierType>1</IdentifierType> <Identifier>Identifier3</Identifier> </AccessDevice> </Identity> <KeyOwner>1</KeyOwner> </request>]]></req:RequestMsg> </soapenv:Body> </soapenv:Envelope>""" headers = {'content-type': 'Content-Type: text/xml; charset=utf-8'} url = "http://xxx.xxx.xxxx.xxx:xxxx/mminterface/request" response = requests.post(url=url, headers = headers, data = body) #print (response.content) respO = xmltodict.parse(response.content) myresponse = json.dumps(respO) This code works fine i am able to get a respose from the other server. My question is the other server is sending some other data which am getting when i tcpdup response i.e. tcpdump -A -s 0 'src xxx.xxx.xxx.xxx and tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - …