Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-import-export data import use alias
I installed django-import-export app successfully, and I can import data from admin. let's say if I have some database like: name | system_id id | system a | 1 1 | system_a b | 1 2 | system_b so the system_id is a foreign key. The question is I want to import data from excel: name | system c | system_c d | system_d How can I do to make the data corresponding for each other. So I can use the real name of system in my excel. -
Django: import error in test
I have a new project in django, without any test. I think that it should say that all is ok, because there are not tests when I try python manage.py test. Instead of that, I obtained this exit: shell screen Any one know why? -
Django one to many opposite
I have an API endpoint returning pets and their owners. Each owner has a name and one or more pets Each pet has a name and one owner Example Django models: class Owner(models.Model): name = models.CharField(max_length=200) class Pet(models.Model): owner = models.ForeignKey(Owner, on_delete=models.CASCADE) name = models.CharField(max_length=200) I've configured my API to return JSON data like this: [ { "id": 2, "name": "Scotch", "owner": { "id": 2, "name": "Ben" } }, { "id": 3, "name": "Fluffy", "owner": { "id": 1, "name": "Fred" } }, { "id": 1, "name": "Spot", "owner": { "id": 1, "name": "Fred" } } ] Example DRF serializers: class OwnerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Owner fields = ("id", "name") class PetSerializer(serializers.HyperlinkedModelSerializer): owner = OwnerSerializer() class Meta: model = Pet fields = ("id", "name", "owner") While that's all fine and dandy, I'd actually like to have an endpoint that returns a list of owners and their pets. So I'd get this data instead: [ { "id": 1, "name": "Fred", "pets": [ { "id": 1, "name": "Spot" }, { "id": 3, "name": "Fluffy" } ] }, { "id": 2, "name": "Ben", "pets": [ { "id": 2, "name": "Scotch" } ] } ] How can I achieve that output? -
unbound method save() must be called with MyModel instance as first argument
I'm using setattr() to set attributes of a new object of a Django model. obj = apps.get_model(app_label="theme", model_name="MyModel") setattr(obj,"myCol",100) obj.save() I got this error: TypeError: unbound method save() must be called with DataPopulationTracts2016 instance as first argument (got nothing instead). I want to save the new instance of MyModel to the model, using get_model() and setattr() to make a new instance of the model and set its attributes. How do I make get_model() and setattr() work with save()? -
Running the Django REST framework example with Django 2.0
I'm trying to adapt the example shown on http://www.django-rest-framework.org/ to Django 2.0, but I'm running into an error. Firstly, I created a project using django-admin startproject rest_example. I've added 'rest_framework' to the INSTALLED_APPS list in settings.py and added the REST_FRAMEWORK variable: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } Here is my adapted urls.py: from django.contrib import admin from django.urls import path, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')) ] The problem is that when I python manage.py runserver and navigate to localhost:8000, I get a 404: Similarly, if I navigate to localhost:8000/api-auth/, I get Why is this not working? -
block tag will not show anything
im running two apps. one app is mapped to localhost:8000/blog/ the other is mapped to localhost:8000/email/ everthing works fine so far. BUT when im on my blog (localhost:8000/blog/) it wont show the contact block. when im on my contacts (localhost:8000/email/) it wont show the blog block. my folder structure: ---templates | index.html | +---blog | blog_detail.html | blog_list.html | ---contact email.html success.html -
internal server error: /robots.txt
I am getting an internal 500 server error but the site is not crashing. Below is what comes out on the console and this happens on every route call, both http and api. [23/Jan/2018 16:12:49] "GET /robots.txt HTTP/1.1" 500 58587 [23/Jan/2018 16:12:49] "GET /checkout HTTP/1.1" 200 192777 Internal Server Error: /robots.txt Traceback (most recent call last): File "/usr/local/lib/python2.7/dist- packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/dist- packages/django/utils/deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "/usr/local/lib/python2.7/dist- packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'tuple' object has no attribute 'get' Here is the contents of my robots.txt file: User-agent: ia_archiver Disallow: / User-agent: Googlebot Disallow: / User-agent: Slurp Disallow: / User-agent: MSNBot Disallow: / User-agent: * Disallow: / I am not sure which files I should starting looking into to traceback the error as I am a junior dev working alone. Would you guys be kind to guide me in the right direction? -
possible to add list of selected value together in django?
for example I have this as my list in django [ {'price': Decimal('45.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('45.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('45.00'), 'total': 2L, 'quantity': 1} {'price': Decimal('40.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('40.00'), 'total': 1L, 'quantity': 1} {'price': Decimal('49.00'), 'total': 1L, 'quantity': 1} ] What I want my output to be is that the same price will be added togther but there's another catch which is, same price times the total. For the example above, what I want as my output would be [ {'price': Decimal('180.00'), 'total': 4L, 'quantity': 1} {'price': Decimal('80.00'), 'total': 2L, 'quantity': 1} {'price': Decimal('49.00'), 'total': 1L, 'quantity': 1} ] since price 49 only has total of 1, there is no changes to it. As for price 40 it's total of two, so the output is 80 as for price of 45 it's total of 4 so 45*4=180 I thought of the javascript lodash which this situtation came up and googled there is something called pydash but somehow I couldn't figure out the way to use it though. Is anyone able to give me an idea how this can work with minimum loops? Thanks in advance. -
Django pass bulk values by checkbox
I want to delete multiple rows from a table by checkbox this is my template : {% if mystocks.all %} <table id="example" class='table table-list-search table-responsive table-hover table-striped bordered" width="100%'> <thead class="alert alert-info"> <tr> <th>name</th> <th>brand</th> <th>id</th> <th> suffix</th> <th>command</th> <th>price</th> <th>days </th> <th>situation</th> </tr> </thead> {% for item in myst %} <tr> <td><input type="checkbox" name="todelete" value="{{ item.id }}"></td> <td>{{ item.name }}</td> <td>{{ item.brand }}</td> <td>{{ item.number }}</td> <td>{{ item.suffix }}</td> <td>{{ item.comment }}</td> <td>{{ item.price }}</td> <td>{{ item.date|timesince }}</td> <td>{{ item.confirm }}</td> <td><a href="{{ item.id }}" onclick="return confirm('Are you sre?');">delete</a> </td> <td><a href="/stock/{{ item.id }}">Edit</a> </td> </tr> {% endfor %} </table> {% else %} <p style="margin:2em" > You have no stock</p> {% endif %} <form class="" method="post"> {% csrf_token %} <input type="submit" name="delete" value="Delete Items" /> </form> and this is my view : def mystocks_view(request): if request.method=='POST': todel = request.POST.getlist('todelete') print(todel) Stocks.objects.filter(user=request.user,id__in=todel).delete() But it returns null ! and print(todel) prints [ ] How can i get the value of multiple checkbox in the view? -
Django REST framework not picking up API endpoint
I'm trying to refactor an API to use the Django REST framework. I've changed my urls.py to the following (still in Django 1.11): from django.conf.urls import url from . import views from rest_framework import routers, serializers, viewsets from .serializers import SessionSerializer from .viewsets import SessionViewSet router = routers.DefaultRouter() router.register(r'^api/v1\.0/feedback/$', SessionViewSet) urlpatterns = [ url(r'^$', views.index), url(r'^api/v1\.0/profile/$', views.get_profile), url(r'^api/v1\.0/update_profile/$', views.update_profile), url(r'^api/v1\.0/update_password/$', views.update_password), url(r'^api/v1\.0/sessions/$', views.get_session), url(r'^api/v1\.0/user/$', views.get_user), url(r'^api/v1\.0/sessions/send_schedule_request/$', views.send_schedule_request), url(r'^api/v1\.0/sessions/confirm_session_time/$', views.confirm_session_time), url(r'^api/v1\.0/password_reset/$', views.password_reset), url(r'^api/v1\.0/me/apn/$', views.save_apn), url(r'^api/v1\.0/confirm_activation_code$', views.confirm_activation_code), url(r'^api/v1\.0/update_user_via_activation_code$', views.update_user_via_activation_code), url(r'^api/v1\.0/questions/$', views.get_questions), url(r'^api/v1\.0/answers/$', views.save_answers), # url(r'^api/v1\.0/feedback/$', views.record_feedback), url(r'^session_types/$', views.session_types), url(r'^send_custom_notification/(?P<id>\d+)/$', views.send_custom_notification, name='send_custom_notification'), url(r'^admin/lucy_web/send_session_time_notifications/(?P<user_id>\d+)/(?P<session_id>\d+)/$', views.send_session_time_notifications, name='send_session_time_notifications'), url(r'^admin/lucy_web/app_activate/(?P<id>\d+)/$', views.app_activate, name='app_activate'), url(r'^admin/lucy_web/create_activation_code/(?P<id>\d+)/$', views.create_activation_code, name='create_activation_code'), ] However, if I python manage.py runserver and go to localhost:8000/api/v1.0/feedback/, I get a 404 error response: It seems like the r'^api/v1\.0/feedback/ endpoint is not being picked up, even though it is passed as an argument to router.register(). Any ideas why this is not working? -
django-embed-video wagtail can not display saved videos
I am trying to display the Embed saved videos on my homepage, but for some reason only the object class divs are created,the image itself with its title don't show up. This is my models.py class HomePage(Page): body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), # InlinePanel('home_images', label="Gallery images"), InlinePanel('video') ] class VideoBasedModel(models.Model): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='video') video = models.ForeignKey( 'wagtail_embed_videos.EmbedVideo', verbose_name="Video", null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [ EmbedVideoChooserPanel('video') ] template_name = 'home/homepage.html' and this is my home_page.html {% block list %} <div class="lists"> <div> <!-- List Nunti --> <div class="title"> <hr /> <h3>Nunti</h3> <hr /> </div> {% for item in page.video.all %} <div class = 'object'> {% video item.video 'small' %} </div> {% endfor %} </div> </div> {% endblock %} Am I missing something, does django-embed-video have a default template where the code for the embed videos need to go? -
Create dict based on queryset result
Imagine I get some queryset: my_queryset_result = ...values('my_column').distinct() if I print it it comes out like: <QuerySet[{'my_column':'foo'}{'my_column':'bar'}]> I need to create a dictionary with the result, like this: {'foo':0, 'bar':0} Can it be done? Or should I use a different approach? -
When working with Python 3 and Django do you modify pip packages when debugging?
I am coming from PHP and playing with Python at the moment. In PHP, composer would install dependencies into ./vendor within your project dir and you can modify them in any way when working. This is usually useful when debugging or when you want to try something out or even to look up some function signature quickly. In Python I used pip to install dependencies off a provided requirements.txt file but the packages get installed into a system dir and it doesn't look like they are meant to be modified. What is your workflow for Python apps: do you modify pip packages and if yes, how do you do that? -
how create multiple objects using drf from a single payload
# in views under POST method json_data = json.loads(request.body.decode('utf-8')) display_name = json_data['displayName'] job_url = json_data['url'] start_time = json_data['timestamp'] execution_url = json_data['url'] execution_number = json_data['number'] # #create stage execution # serializer = StageExecutionSerializer(request.data) # if serializer.is_valid(): # serializer.save() # #create platform # serializer = StageExecutionSerializer(request.data) # if serializer.is_valid(): # serializer.save() I am struggling to figure out the most efficient way to take request.data and create objects leveraging DRF from this data. Passing in display_name, job_url, etc. to the serializer doesn't make sense to me because those have already been deserialized by json.loads, however this is the route I might have to take. The ideal scenario would be to pass in request.data to each serializer, and have it automagically know which key/values to take when creating object. Is this possible? -
How can I show my custom user and user in same form and make it work?
I have 2 models: teacher and student. They both extend User class with a OneToOneField and they both have receivers defined for creation and saving. Now, in my forms I can only display the fields from student or teacher only, the other fields that come with user I don't know how to include them. But I want that a student or a teacher won't be able to create account, unless all fields are filled in. Here are my forms and view: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'student_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index') class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'teacher_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return render_to_response('index.html', {'form': form},) class StudentSignUpForm(forms.ModelForm): class Meta: model = Student fields = ('student_ID', 'photo', 'phone') class TeacherSignUpForm(forms.ModelForm): class Meta: model = Teacher fields = ('academic_title', 'photo', 'phone', 'website', 'bio') -
Why won't importlib find my module
I'm trying to programmatically import a module. This works: from dirname.models import modelclass as m But this doesn't: import importlib m = importlib.import_module('models.modelclass', package='dirname') I try running this script from the directory that holds dirname. dirname contains a init.py file. I'm trying to make this work using django. I get an ImportError saying "No module named 'models'" -
How can I stop a daemon thread from a view in Django project?
This is my model: class TicketsDeploymentModel(models.Model, threading.Thread): tickets_in_qeue = models.BooleanField() tickets_sent = models.CharField(max_length=20) deployment_error = models.BooleanField() def _create_stop_event(self): self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() def _deploy_tickets(self): import smtplib, time, random from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage def create_email_service(): s = smtplib.SMTP(host='smtp.gmail.com', port=587) s.starttls() s.login(USERNAME, PASSWORD) return s self.tickets_in_qeue = True self.tickets_sent = 0 self.deployment_error = False self.save() all_tickets = TicketsModel.objects.filter(ticket_status=True) ticket_emails = [] for counter,ticket in enumerate(all_tickets): ticket_emails.append(MIMEMultipart()) ticket_emails[counter]['From']='chinon19@gmail.com' ticket_emails[counter]['To']='germantestingapp@mailinator.com' ticket_emails[counter]['Subject'] = ticket.ticket_subject ticket_emails[counter].attach(MIMEText(ticket.ticket_body, 'plain')) for counter,ticket in enumerate(ticket_emails): if not self.stopped(): try: service = create_email_service() service.send_message(ticket) self.tickets_sent = '{} out of {}'.format(counter + 1, len(all_tickets)) self.save() print(self.tickets_sent + ' tickets have been sent.') time.sleep(random.randint(5,10)) except KeyboardInterrupt: self.tickets_in_qeue = False self.save() return except: self.deployment_error = True self.tickets_in_qeue = False self.save() return print('An exception occurred: most probably an SMTP connection error.') self.tickets_in_qeue = False self.save() # self.delete() return def deploy_as_daemon(self): deployment = threading.Thread(target = self._deploy_tickets) self._create_stop_event() deployment.daemon = True deployment.start() And I want to stop the daemon thread from one of my views: def DeployTicketsView(request): current_deployment = TicketsDeploymentModel() current_deployment.deploy_as_daemon() return render(request, 'tickets/confirm_tickets_deployment.html', {'current_deployment':current_deployment}) def StopDeploymentView(request, pk): current_deployment = TicketsDeploymentModel.objects.get(pk=pk) current_deployment.stop() return render(request,'tickets/deployment_interrupted.html') The error that I'm getting is in the first … -
django-mssql database error, SQL query error
I am using django-mssql to connect to the database. I am doing a raw sql query to the database but I get this error. django.db.utils.DatabaseError: (-2147352567, 'Exception occurred .', (0, 'Microsoft SQL Server Native Client 11.0', 'Error conver ting data type varchar to bigint.', None, 0, -2147217913), None) Command: SELECT Attribute FROM ML.attribute WHERE CompanyID = '1' AND Att ributeID NOT IN (SELECT AttributeID FROM ML.correlatedattribute WHERE ProductID ='AUTO_LOAN')AND (Useless != 1 OR Useless IS NUL L) The body of function calling the database is like this def query(query_string): cursor = connection.cursor() cursor.execute(query_string) rows = cursor.fetchall() cursor.close() return rows The error seems to be something to do with data type but I have no idea how to solve this. -
What are the most user-friendly methods to create interactive graphics/charts on a webpage?
I'm looking to create a webpage with interactive charts that can be updated on the back-end by a MySQL database. IE. A website that hosts a graph that has points which can be clicked on for additional information. I have a background in Python programming and have started looking over Django documentation but am struggling with following the documentation's tutorial as I progress. Are there other languages, methods or perhaps Django tutorials that anyone can recommend for a project like this? Looking for video material myself hasn't reaped much success. -
Invoke a seperate event when I click on a hyperlink on my Django template page
I have an tag on my Django template for an advert that fulfills two functions: When a user clicks it, data is logged about the click (its location on the page, the text of the link, etc.) It is then redirected to an external link on a different website. The way the page template is loaded is that the tag is dynamically filled with the href attribute pointing towards a view function in my views.py : <a href="url arg1&arg2&redirect_url" target="_blank"> <span dir="ltr">Lawyer Education</span> </a> The problem is that in practice, when a user hovers over my hyperlink, on the bottom left of the browser they see the URL pointing towards the view and its DJango url with arguments is displayed as opposed to the URL they are expecting to be redirected to. Is it possible to have the redirect URL be displayed instead in some way? Or to have the view function be fired as an event while the redirect occurs at the same time? Javascript/jQuery/PHP is not my forte so I am not sure how to proceed if that is the way to go to solve my problem... -
Start Scraping Process in Django App
I recently had a developer work on a project with me for a web application that scrapes news articles and allows assesses them uses NLP. I'm new to Python and have never used Django before, but have managed to get the app up and running on a host. Unfortunately the developer is now unavailable and although the project is almost ready, I'm not exactly sure how to execute the scraping process. It uses the following packages: beautifulsoup4==4.6.0 dj-database-url==0.4.1 Django>=1.9.7 django-allauth==0.32.0 django-filter==1.0.4 django-taggit==0.22.1 djangorestframework==3.6.3 django-taggit-serializer==0.1.5 feedfinder2==0.0.4 feedparser==5.2.1 gunicorn==19.6.0 newspaper3k==0.2.2 nltk==3.2.4 parsedatetime==2.1 psycopg2==2.7.1 virtualenv==15.1.0 whitenoise==2.0.6 oauthlib==2.0.2 requests-oauthlib==0.8.0 django-rest-auth==0.9.1 markdown word2number django-cors-headers Does anyone who knows Django and/or the installed packages know where I might find the scripts if they are there? The repository is available here: https://github.com/davemate23/swendle I have the app and database running locally, so understanding how to start the scraping and NLP/data analysis process would be really helpful. Thanks -
Python coverage parse exception
When I try to send python project with sonar-scaner, it throws me the following exception "Caused by: java.lang.IllegalStateException: Unknown report version: 4.4.2. This parser only handles version 1.". Before trying to introduce the cover, the project was run normally, the project is python code and the report is created with django-nose. More information: sonar version: 6.7.1 sonar scanner command: sonar-scanner -Dsonar.projectKey=nanas -Dsonar.host.url=http://192.168.0.**:9001 -Dsonar.login=8c047********************33c3111b5 sonar doesn't run through a proxy I'm attaching sonar project configuration file and coverage xml file generated by django-nose. I have been reviewing several forums but I can't find a solution to my problem, I would need to solve this problem in order to continue with the automatic code analysis in my project. Best regards, Jose Luis Exception: 12:53:31.919 ERROR: Error during SonarQube Scanner execution Error during parsing of the generic coverage report '/home/bamboo-home/xml-data/build-dir/NAN-CI6-JOB1/xmlrunner/coverage.xml'. Look at SonarQube documentation to know the expected XML format. Caused by: java.lang.IllegalStateException: Unknown report version: 4.4.2. This parser only handles version 1. at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parseRootNode(GenericCoverageReportParser.java:72) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.lambda$parse$0(GenericCoverageReportParser.java:64) at org.sonar.api.utils.StaxParser.parse(StaxParser.java:115) at org.sonar.api.utils.StaxParser.parse(StaxParser.java:95) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parse(GenericCoverageReportParser.java:65) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parse(GenericCoverageReportParser.java:54) at org.sonar.scanner.genericcoverage.GenericCoverageSensor.execute(GenericCoverageSensor.java:109) at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53) at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:88) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:82) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:68) at org.sonar.scanner.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:88) at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:180) at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:135) at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:121) at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:288) at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:283) at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:261) at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:135) at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:121) … -
Where is robots.txt coming from (Nginx + Gunicorn + Django)?
I am running a server with Nginx + Gunicorn + Django. I have configured Django to show a robots.txt file, and this works just fine when I test Django on its own, without Nginx+Gunicorn. However, when I run the whole stack, /robots.txt suddenly gets replaced with a different file that I didn't write. Why is this happening? I never wrote anything to tell Nginx or Gunicorn to do such a thing. Is there a default somewhere that I need to overwrite or deactivate? The folder /etc/nginx/sites-enabled contains only my own sites file, and it doesn't mention /robots explicitly. It just has a location block targeting / which gets routed to Gunicorn+Django, and for every site except robots.txt this works just fine. -
Elastic Beanstalk + S3 and easy-thumbnails for django create timeout
I am using the easy-thumbnails module for django. The django app gets deployed on elastic beanstalk and images hosted on S3. When a user uploads an image he gets redirected to a page which shows the thumbnail, generated with easy-thumbnails. This however gives me a 500 Server error. When I wait a little bit and refresh the page, everythings works fine, which leads me to believe that some kind of timeout occurs on thumbnail generation. Of course once the image is generated everything works fine. I could not find any errors in the logs however, even with THUMBNAIL-DEBUG = True. Any leads to a solution would be greatly appreciated. -
While Putting data the through REST API. response is showing {"closingDay":["\"['sunday', 'monday']\" is not a valid choice."]}
I am using Angular JS as frontend. Django as a backend. also using django rest API for CRUD(create,retrieve,update,delete).I am sending data into database through api link. this is my Component.js 'use strict'; angular.module('addshop'). component('addshop',{ templateUrl: 'api/templates/addshop.html', controller : function($scope, $element, $anchorScroll, $location, $mdDialog, $filter, City, Category, SubCategory,Addshop,Map){ $scope.goaddshop = function(shopdata){ Addshop.create({ city : shopdata.city, category : shopdata.category, subCategory : shopdata.subCategory, shopName : shopdata.shopName, tagline : shopdata.tagline, bannerImage : shopdata.bannerImage, email : shopdata.email, mobileNo : shopdata.mobileNo, alternateMobileNo : shopdata.alternateMobileNo, location : shopdata.location, ownerName : shopdata.ownerName, shopAddress : shopdata.shopAddress, shopPinCode : shopdata.shopPinCode, openingTime : shopdata.openingTime, closingTime : shopdata.closingTime, closingDay : shopdata.closingDay, }) } City.query({},function(data){ $scope.cityList = data }); Category.query({},function(data){ $scope.categoryList = data }); SubCategory.query({},function(data){ $scope.subcategoryList = data }); $scope.days = ["sunday","monday" ,"tuesday" ,"thursday" ,"friday", "saturday"]; $scope.states = [ 'Utter Pradesh','Delhi','Jammu & Kashmir','Uttarakhand','Bihar','Rajasthan','Madhya Pradesh','Andaman and Nicobar Islands','Andra Pradesh','Arunachal Pradesh','Assam','Chhattisgarh','Goa','Gujarat','Haryana','Himachal Pradesh','Jharkhand','Karnataka','Kerala','Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Orissa','Punjab','Sikkim','Tamil Nadu','Tripura','West Bengal','Pondicherry','Lakshadeep','Daman and Diu','Dadar and Nagar Haveli','Chandigarh'] $scope.scrollTo = function(id,show) { $location.hash(id); $anchorScroll(); }; } }); this is my template <div class="container"> </div> <div class="content" layout="column" layout-align="center center"> <!-- <span style="font-family:inherit; font-size:45px; padding:25px;">List Your Business With CityAPL</span> --> <!-- <a ng-click="scrollTo()" class="cta">Get Start</a> --> </div> </div> <!--add business Form start--> <div layout=column id="foo"> <div style="font-size:31px ; text-align:center;color:#333c ; margin-top:50px; margin-bottom:15px; font-weight:500">List Your Business …