Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having problems with my domain name (Django app)
I have created a template and I wanted to publish it , and I have a problem with my domain name , which I've bought it from namecheap.com && the hosting server is from Digital Ocean.The only problem I have is , when I mange my domain at namecheap.com.I select the "Custom DNS" option , and I enter the 3 servers from DO (ns1.digitalocean.com , ns2.digitalocean.com, ns3.digitalocean.com) and after that I go to digital ocean and create an A record(@)and a CNAME(www.) record. The problem is that I am able to see my website, but anyone who isn't connected tot my router or wifi connexion , isn't able to see it.What did I do wrong? It would help me so much to give me an answer. Have a great day:) -
Information stored in session not saving django
I've been having trouble with storing my data in django. I'm appending a tuple but everytime I do a post request it shows me an empty array. It should be appending every time? Can anyone give me an idea on why this happens? (my forms and data are working fine the information is received in request.POST) views.py The session is started when a user logs in def post(request): username = request.POST["username"] password = request.POST["password"] user = authenticate(username=username, password=password) if user is not None: login(request, user) request.session['cart'] = [] return redirect("/") else: return render(request, 'sign_in.html', { "error": "Invalid Credentials" }) now heres where the problems at get method (class based view) def get(request): stalls = available_stalls() products = Product.objects.all() if 'cart' not in request.session: request.session['cart'] = [] cart_count = 0 else: cart_count = len(request.session['cart']) context = { "stalls": stalls, "products": products, 'cart_count': cart_count } if request.user.is_authenticated: user = request.user customer = Customer.objects.filter(user=user)[0] full_name = customer.full_name context["name"] = full_name return render(request, 'product_catalog.html', context) post method (class based view) def post(request): if "product" not in request.POST or "quantity" not in request.POST: raise Http404("Product or quantity not in POST data") product_id = request.POST["product"] quantity = request.POST["quantity"] try: product = Product.objects.get(id=product_id) except: raise Http404("Product ID β¦ -
Trying to save objects in a many-to-many relationship (multiple inheritance)
I'm doing a django app for an educational school, and I have a two classes (RegularSchoolClass and AdhocSchoolClass) that inherit from a SchoolClass (not abstract). I have another class (LessonSchedule) that records the weekly or daily schedule of a class and has a many to many relationship with SchoolClass. Upon saving of a regularschoolclass, I'm trying to update the relevant lesson schedule (https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/). I'm getting the following error - I assume this is because LessonSchedule is a many-to-many relationship with SchoolClass rather than RegularSchoolClass? Is there a way to make it work though (I don't really want to duplicate the same code for both RegularSchoolClass and AdhocSchoolClass)? ValueError: Cannot add "<RegularSchoolClass: Kindergarten One, Dan, Saturday, 9:00AM - 10:45AM>": the value for field "schoolclass" is None models.py class SchoolClass(TimeStampedModel): pass class RegularSchoolClass(SchoolClass): def save(self, *args, **kwargs): for l in LessonSchedule.objects.filter(lesson_frequency=self.lesson_frequency, start_date=self.start_date): l.schoolclass.add(self) class AdhocSchoolClass(SchoolClass): pass class LessonSchedule(models.Model): school_class = models.ManyToManyField(SchoolClass) -
Django - view didn't return an HttpResponse
I'm new to Django/Python so bare with me. My project is here github Project I'm getting this error. ValueError at /salesapp/add/ashton-aged-maduro/ The view salesapp.views.add_CartItem didn't return an HttpResponse object. It returned None instead. I get this error when I click the 'Add to Cart' button on my singleproduct.html template which calls the ProductAddToCart form. The view is add_CartItem. I also get the error "Field is required" when I don't intially set the form values. I'm just stuck now. This is models.py class Product(models.Model): itemid = models.CharField(max_length=128, unique=True) itemname = models.CharField(max_length=128) brand = models.CharField(max_length=128) image = models.ImageField(upload_to='static/images/') notes = models.CharField(max_length=250) price = models.IntegerField() slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.itemname) super(Product, self).save(*args, **kwargs) def __str__(self): return self.itemname class CartItem(models.Model): cart_id = models.CharField(max_length=50) date_added = models.DateTimeField(auto_now_add=True) quantity = models.IntegerField(default=1) itemid = models.ForeignKey('Product', unique=False) class Meta: db_table = 'cart_items' ordering = ['date_added'] def name(self): return self.product.name My forms.py class ProductAddToCartForm(forms.ModelForm): cart_id = forms.CharField(max_length=50) date_added = forms.DateTimeField() quantity = forms.IntegerField() slug = forms.CharField(widget=forms.HiddenInput(), required=False) #itemid = models.ForeignKey('Product', unique=False) class Meta: model = CartItem fields = ('cart_id', 'date_added', 'quantity', 'slug', 'itemid', ) My views.py def add_CartItem(request, product_name_slug): print('In add_CartItem --------------------') form = ProductAddToCartForm(request.POST) p = Product.objects.get(slug=product_name_slug) form = ProductAddToCartForm(initial={'cart_id': 123, 'date_added':date.date.today(), 'quantity': β¦ -
OneLogin SAML2 module throws an error `lxml.etree.XMLSyntaxError: Start tag expected, '<' not found, line 1, column 1`
I am trying to implement a SAML2 SSO functionality using the OneLogin SAML2 module for this. There is much info in the readme and also in the demo. I have implemented the most of it already and I am testing my ACS endpoint using Samling tool. I am able to receive the SAML response, but I am getting the mentioned above error at this point in my implementation. The XML, which I receive looks fine and the first symbol is <. I do not understand, where the problem lies. Please help. Here is the complete Traceback: Internal Server Error: /auth/sso/saml2/ Traceback (most recent call last): File "/usr/local/lib/python3.4/site-packages/django/core/handlers/base.py", line 140, in get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/usr/local/lib/python3.4/site-packages/debug_toolbar/middleware.py", line 78, in process_view response = panel.process_view(request, view_func, view_args, view_kwargs) File "/usr/local/lib/python3.4/site-packages/debug_toolbar/panels/profiling.py", line 151, in process_view return self.profiler.runcall(view_func, *args, **view_kwargs) File "/usr/local/lib/python3.4/cProfile.py", line 109, in runcall return func(*args, **kw) File "/code/authtoken/views.py", line 63, in sso_handler resp = do_saml2(request) File "/code/authtoken/sso/saml2/saml2.py", line 83, in do_saml2 auth.process_response() File "/usr/local/lib/python3.4/site-packages/onelogin/saml2/auth.py", line 99, in process_response response = OneLogin_Saml2_Response(self.__settings, self.__request_data['post_data']['SAMLResponse']) File "/usr/local/lib/python3.4/site-packages/onelogin/saml2/response.py", line 39, in __init__ self.document = OneLogin_Saml2_XML.to_etree(self.response) File "/usr/local/lib/python3.4/site-packages/onelogin/saml2/xml_utils.py", line 66, in to_etree return OneLogin_Saml2_XML._parse_etree(xml) File "/usr/local/lib/python3.4/site-packages/defusedxml/lxml.py", line 143, in fromstring rootelement = _etree.fromstring(text, β¦ -
where to check session in ClassView in django ?
I have a ListView in my views.py but in this class, I want to check session if the user exit in the session which has been kept in during login class part_list_view(ListView): model = part_list context_object_name = 'part_list' template_name = 'part_list.html' def get_context_data(self, **kwargs): context = super(part_list_view, self).get_context_data(**kwargs) context['my_list'] = populate_nav_bar() return context -
Deployment on Heroku dockerized web application - error code=H14 desc="No web processes running"
I would like to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. In activity I have information that Build succeeded however in logs I get error at=error code=H14 desc="No web processes running" method=GET path="/" host=myapp request_id=fe4c4613-7c39-49c2-a354-ee1f195de922 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https I found information that I should try heroku ps:scale worker=1 but I get Couldn't find that process type. Any suggestions or other ideas how can I smooth out error code=H14? Project tree: βββ Backend β βββ AI β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-36.pyc β β β βββ settings.cpython-36.pyc β β β βββ urls.cpython-36.pyc β β β βββ wsgi.cpython-36.pyc β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ manage.py βββ Dockerfile βββ init.sql βββ Frontend β βββ angularProject βββ Dockerfile β βββ all files in my angular project βββ docker-compose.yml βββ requirements.txt Frontend's Dockerfile: # Create image based on the official Node 6 image from dockerhub FROM node:6 # Create a directory where our app will be placed RUN mkdir -p /usr/src/app # Change directory so that our commands β¦ -
How to embed python console like pythonanywhere in django website?
I want to create a python online console like pythonanywhere in my Django website. Is there any Django-package for it. I have tried all the other 3rd party online consoles but I don't want to use that. I want to create my own console in Django website -
pip (package manager) Django (web framework) not working
pip (package manager) Django (web framework) +3 I have succesfully installed python, pip and Django but when I give command of starting project it shows error why? screenshot from my laptop -
Create migrations for diff between db and model definitions, without using previous migration history
I'd like to create a new instance of my application with a clean migration history from a backup copy of the database. The idea is that I get migrations which cover the difference in model definitions between what's in the database, and the model definitions for the branch of the application repository I'm testing out. To be clear, I don't have an existing set of py migration files that match the database migration history, hence my desire to blow it all away and then just generate migrations for this particular branch. I can drop the various application rows from the django_migrations table and delete the migration py files, but getting manage.py to generate some sort of CREATE TABLE (or column) IF NOT EXISTS is proving harder. Is there an automated way to do this, or must I manually create the migration files? I'm using django 1.11.2, postgres 9.5 -
Django Restful_Api post Json for more than one record in a time
I use Django Restful Api ,I want to post records(more than one record!) in a time ,Models ,serialize,viewset are as follows Does anyone has some advice? thanks advcance! model class Brand(models.Model): Company_Group = models.ManyToManyField(Company) Brand_Group = models.CharField(u'Brand Group',max_length=255, default="") Pref_Brand_Name_Flg = models.CharField(u'Preferred Brand Name Flag',max_length=255, default="") Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, default="") PrimaryContact = models.ForeignKey(UserRole, null=True, blank=True) #primary broker Protect_period = models.CharField(u'Protect period',max_length=255, default="") # Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, default="") Brand_Name = models.CharField(u'Brand Name',max_length=255, default="") Brand_Name_SC = models.CharField(u'Brand Name in Local Language',max_length=255, default="") Year_Enter_Market = models.CharField(u'Entered Market in (Year)',max_length=255, default="") Category_Display = models.CharField(u'Category Display',max_length=255, default="") Category_1_Code = models.CharField(u'Category',max_length=255, default="") Category_2_Code = models.CharField(u'Sub Category',max_length=255, default="") Price_Low = models.CharField(u'Price Range - Low',max_length=255, default="") Price_High = models.CharField(u'Price Range - High',max_length=255, default="") Size_Low = models.CharField(u'Typical Store Size - Low',max_length=255, default="") Size_High = models.CharField(u'Typical Store Size - High',max_length=255, default="") Headerquater = models.CharField(u'Headerquater',max_length=255, default="") Status = models.CharField(u'Status',max_length=255, default="") Created_On = models.DateField(u'Created On',auto_now_add=True) Created_By = models.CharField(u'Created By',max_length=255, default="") Modified_On = models.DateField(u'Modified On', auto_now=True) Modified_By = models.CharField(u'Modified By',max_length=255, default="") Agreement_InPlace_Flg = models.CharField(u'TR Agreement in place?',max_length=20, default="") Web_Site = models.CharField(u'Web Site',max_length=20, default="") Comment = models.CharField(u'Comment',max_length=20, default="") viewset class BrandViewSet(viewsets.ModelViewSet): queryset = Brand.objects.all() serializer_class = BrandSerializer Serializer class BrandSerializer(serializers.HyperlinkedModelSerializer): PrimaryContact_id = serializers.ReadOnlyField(source='PrimaryContact.id', read_only=True) def __init__(self, *args, **kwargs): many = β¦ -
Render view/template accessible by 2 different users
I'm working with my friend on a Django application and we get an issue with our website. In order to resume : We have an Admin user which can access to each part from our website. Our application manages contracts for different companies. Each compagny can access to their homepage and consult interventions, points balance, ... Each compagny have a user account to connect in our website. To access to their homepage after the log process, I wrote in the log application: def connexion(request): error = False if request.method == "POST": form = ConnexionForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user.username == 'Admin': login(request, user) return HttpResponseRedirect(reverse('accueil')) elif user.username == 'Compagny1': login(request, user) return HttpResponseRedirect('http://localhost:8000/Compagny/1/') elif user.username == 'Compagny2': login(request, user) return HttpResponseRedirect('http://localhost:8000/Compagny/2/') else : error = True else: form = ConnexionForm() return render(request, 'connexion.html', locals()) Then, Compagny model looks like : class Compagny(models.Model): Nom = models.CharField(null= False, max_length=70, verbose_name='Nom de SociΓ©tΓ©') ... ... user = models.ForeignKey(settings.AUTH_USER_MODEL, default=" ") The url which let to go to the Homepage is : url(r'^Compagny/(?P<id>\d+)/$', views.Homepage, name="Homepage"), Finally, in my view, I have : @login_required def Homepage(request, id) : compagny = get_object_or_404(Compagny, pk=id, user=request.user) ... # form β¦ -
Jumps between minutes in an audio file
I would like to know how to create jumps between minutes of an audio file on a web system. My system is written in Python / Django but I believe jumps could be done with javascript, but I have no clue how to do this. Thanks for the help! -
How to update records partially in django without specifying whole fields?
I am using save() method to create records in Django. Same save() method along with primary key is used to update the corresponding record. But every time I can't specify values of all fields in the update. This is removing the already existing data, that I added during creation. So what is the best way to perform the partial update by specifying only required fields.? MODEL class ApprenticeUsers(models.Model): uid = models.IntegerField(primary_key = True) apid = models.CharField(max_length=60, blank=False) first_name = models.CharField(max_length=64, blank=False) last_name = models.CharField(max_length=64, blank=False) VIEWS def insert_apprenticeship_data(user_details, table_obj): table_obj = table_obj() for field in user_details: setattr(table_obj,field, user_details[field]) try: table_obj.save() except: return False SAMPLE DATA PASSING TO VIEW ({uid:123, apid:"AP12"}, ApprenticeUsers) Here uid is the primary key -
How to display a dictionary list in django template? (Could not parse the remainder)
I've got a function that is creating a list: import feedparser import ssl def rss(self): if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context rss = 'https://news.google.com/news?q=fashion&output=rss' feed = feedparser.parse(rss) articles = [] for entry in feed.entries: articles.append({ "summary" : str(entry.summary), "link" : str(entry.link), "title" : str(entry.title), }) return articles on return of articles I am then trying to display this in the view My views.py code is: def results(request): rss_feed = RSS() articles = rss_feed.rss() return render(request, 'app/index.html', articles) and then my template code is: <ul> {% for article in articles %} <li>{{ article['title'] }}</li> {% empty %} <li>Sorry, no athletes in this list.</li> {% endfor %} </ul> but I keep getting an error that reads: TemplateSyntaxError at /app/results Could not parse the remainder: '['title']' from 'article['title']' I created a seperate script and just print to console and it prints without issue. But doesn't show in django. Im new to python and django. Not sure what I've missed. -
Get capture parameter in request
I have a url defined like: url(r'^path/(?P<person>\w+)/$', views.Something.as_view()), Can I access that person parameter from within request object? Is there something like request.resolved_path.capture_groups['person']? -
Translating dynamic content in django templates
I have a html template rendered by a view in django. And the template has some dynamic values that the view sends. Example:: {{ text_to_be_translated.brand_name}} The above 'text_to_be_translated.brand_name' is a dictionary with thousands of keys like brand_name, which can hold many values like 'my brand', 'your brand' etc I am not able to get the above dynamic text translated. I tried to manually put msgids for the texts in the po file msgid "my brand" msgstr "γ«γΌγγ€γ³γγ©γ‘γΌγ·γ§γ³" But it doesn't get translated. What am I doing wrong, please help. -
KeyError at /docker/auth/ django 1.11 forms
I'm trying to grab and display a django form data which is comping through POST request, but I'm stuck at KeyError for one go my field name, Here's the error: KeyError at /docker/auth/ 'docker_name' Request Method: POST Request URL: http://127.0.0.1:8000/docker/auth/ Django Version: 1.11.3 Exception Type: KeyError Exception Value: 'docker_name' Exception Location: /Users/abdul/Documents/IGui/dockerDep/views.py in post, line 21 Python Executable: /Users/abdul/IstioVirEnv/bin/python Python Version: 3.6.1 Here's my forms.py: from django.forms import forms from .import models class DockerAuthForm(forms.Form): class Meta: fields = ('docker_name', 'docker_pass') model = models.DockerAuth Here's my views.py: from django.shortcuts import render from django.views.generic import CreateView from . import forms class DockerAuth(CreateView): form_class = forms.DockerAuthForm def get(self, request, *args, **kwargs): return render(request, 'dockerDep/docker_login.html', {}) def post(self, request, *args, **kwargs): lform = forms.DockerAuthForm(request.POST) context = {} if lform.is_valid(): data = lform.cleaned_data name = data['docker_name'] password = data['docker_pass'] context = { "form": lform, "uname": name, "upass": password } return render(request, 'dockerDep/response.html', context) Here's my HTML template form: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DOCKER</title> </head> <body> <form method="post" action="."> {% csrf_token %} <input type="text" name="docker_name" title="Name"> <input type="password" name="docker_pass" title="Password">. <input type="submit" value="Submit"/> </form> </body> </html> -
Tox: InvocationError
I want to use tox to test my django modul. Here my tox.ini file: [tox] envlist = py{34}-django{11} skipsdist = True [testenv] deps= -r{toxinidir}/requirements_dev.txt django11: Django>=1.11,<1.12 commands = python3 -Wdefault manage.py test --settings=mysite.settings_dev But I get the error message: ERROR: InvocationError: '.tox/py34-django11/bin/python3 -Wdefault manage.py test --settings=mysite.settings_dev' But if I run python3 -Wdefault manage.py test --settings=mysite.settings_dev standalone in a shell it works. -
How to get variable from django url
I'm new to Django and would like to know how to get a variable from a url. I have tried this: url(r'^(?P<name>)/$', employeedetail, name='employeedetail'), which goes to this view def employeedetail(request, name): return render(request, 'employee/detail.html') but I get an error: employeedetail() missing 1 required positional argument: 'name' Is the code wrong or do I need to type in the url in a particular way? -
Django + multiprocessing.dummy.Pool + sleep = weird result
In my Django application, I want to do some work in background when a certain view is requested. To that end, I created a multiprocessing.dummy.Pool of workers, and whenever that URL is called, I start a new process on it. The task to be executed in background can have to do some retries with a certain timeout between them. Since this whole thing is executed, so to speak, not on a UI thread, I thought I'd use sleep for timeouts. When I unittest this arrangement, everything works fine, but when this runs in Django, the thread gets to the sleep statement and then never wakes up, but when I restart the Django app, the thread gets past the sleep statement and then is immediately killed by the restart. I know I could schedule retries using Timers, but I wanted a simpler solution. Here's a simplified version of my code: from multiprocessing.dummy import Pool POOL = Pool(settings.POOL_WORKERS) def background_task(arg): refresh = True try: for i in range(settings.GET_RETRY_LIMIT): status, result = (arg, refresh=refresh) refresh = False if status is Statuses.OK: return result if i < settings.GET_RETRY_LIMIT - 1: sleep(settings.GET_SLEEP_TIME) except Exception as e: logging.error(e) return [] def do_background_work(arg): POOL.apply_async( background_task, (arg) ) β¦ -
GET request to Web Server Django
I'm developing a Django application for managing access via magnetic sticker (badge) in a lab. The application must show the present and missing people on an html page. So i'm creating a small python web server where when a person swipes the badge comes a GET request to the server indicating the ID of the person and the time of the access .. But I have never worked with the web servers and I do not know How to develop the GET request. I think I should be like this which I found on the internet which requires an HTML file from the server that uses our client, can anyone help me please? #!/usr/bin/env python from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import os #Create custom HTTPRequestHandler class class KodeFunHTTPRequestHandler(BaseHTTPRequestHandler): #handle GET command def do_GET(self): rootdir = 'c:/xampp/htdocs/' #file location try: if self.path.endswith('.html'): f = open(rootdir + self.path) #open requested file #send code 200 response self.send_response(200) #send header first self.send_header('Content-type','text-html') self.end_headers() #send file content to client self.wfile.write(f.read()) f.close() return except IOError: self.send_error(404, 'file not found') def run(): print('http server is starting...') #ip and port of servr #by default http server port is 80 server_address = ('127.0.0.1', 80) httpd = HTTPServer(server_address, KodeFunHTTPRequestHandler) print('http β¦ -
Filter data in table and hide unfiltered data with their header
I have a table with a list that has the governorate of a country as a table head, and the residential areas in that governorate as rows. This table has alot of "th" tags with "td" for every "th". It looks like this. What I'm trying to do is allow users to search for their location using a search bar (as shown in the image). So if the location exists, I want that location to be displayed with its header (governorate), but hide all other data. I was able to achieve most of that, and other data that were not filtered do get hidden, but their header remains. I don't want anything other than the filtered result and its header to be displayed. This is what I get This is the code I have tried so far (I'm using django framework to get the table values):HTML <table id="locations-table" class="table table-hover"> {% for governorate, governorate_locations in locations %} <th><h2><b>{% trans governorate %}</b></h2></th> <tbody> {% for resedential in governorate_locations %} <tr> <td><h4><i class="fa fa-circle-thin" aria-hidden="true"></i> {% trans resedential.name %}</h4></td> <td hidden style="display: none">{{ resedential.id }}</td> </tr> {% endfor %} </tbody> {% endfor %} </table> js function LocationSearchFunction() { // Declare variables var β¦ -
context must be a dict rather than tuple Django forms
I'm trying to get form data through POST method but got "context must be a dict rather than tuple" error.I have google it much, according to the Django 1.11's docs we Just need to use a regular dictionary instead of a Context instance. I'm stuck here, help me please! Here's the error: TypeError at /docker/auth/ context must be a dict rather than tuple. Request Method: POST Request URL: http://127.0.0.1:8000/docker/auth/ Django Version: 1.11.3 Exception Type: TypeError Exception Value: context must be a dict rather than tuple. Exception Location: /Users/abdul/IstioVirEnv/lib/python3.6/site-packages/django/template/context.py in make_context, line 287 Python Executable: /Users/abdul/IstioVirEnv/bin/python Python Version: 3.6.1 Python Path: ['/Users/abdul/Documents/IGui', '/Users/abdul/IstioVirEnv/lib/python36.zip', '/Users/abdul/IstioVirEnv/lib/python3.6', '/Users/abdul/IstioVirEnv/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/abdul/IstioVirEnv/lib/python3.6/site-packages'] Server time: Mon, 10 Jul 2017 10:12:30 +0000 Here's My views.py: import json from django.shortcuts import render from django.views.generic import CreateView from . import forms from django.http import HttpResponse class DockerAuth(CreateView): form_class = forms.DockerAuthForm def get(self, request, *args, **kwargs): return render(request, 'dockerDep/docker_login.html', {}) def post(self, request, *args, **kwargs): lform = forms.DockerAuthForm(request.POST) if lform.is_valid(): data = lform.cleaned_data() name = data['docker_name'] password = data['docker_pass'] args = { "mname": name, "mpass": password } return render(request, 'dockerDep/response.html', args) Here's my forms.py: from django import forms class DockerAuthForm(forms.Form): name = forms.CharField(label='Your name', max_length=100) Here's my HTML template: <!DOCTYPE html> β¦ -
AngularJS $http push request not calling Django view function
I have a click button which should pass some parameters from the front end to a django view function. However when I use $http.push my code does not go into the django "action" view function. When I use $http.get then the action view function is accessed, however I need to use $http.push to pass front end data - why would it not access the action view def? <tr ng-repeat="Script in Scripts | filter :{timestamp : datefilter} | orderBy:column:reverse "> <td>{{ Script.id }}</td> <td>{{ Script.script }}</td> <td>{{ Script.timestamp }}</td> <td>{{ Script.hostname }}</td> <td>{{ Script.subject }}</td> <td ng-class="{'red':Script.status =='= ISSUE =','green':Script.status == '= OK ='}">{{ Script.status }}</td> <td align="center"><button type="button" class="btn btn-default btn-xs" ng-click="actionFun(Script)"></button></td> </tr> Controller.js function: $scope.actionFun = function(Script){ var data = JSON.stringify(Script); console.log("Output 1: ", data); $http.get("http://127.0.0.1:8000/action/",data).success(function(data, status){ #$http.push("http://127.0.0.1:8000/action/",data).success(function(data, status){ console.log("Output 2: ", data); }) }; Django View Code: @api_view(['GET', 'POST']) def action(request): import paramiko print("Im here") if request.method == 'PUSH': data = request.data print(data.get('location')) *** Do Some Function ***