Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Discard inline form value
I've created a simple form Django Admin Form with a select field and a inline sub form. I would like that the fields of inline form were loaded only if the select field takes a value "example: 1". It's possible? I've already overwrite the functions save_model and save_formset but without effect def save_model(self, request, obj, form, change): if form.fields['my_field']!="1": # discard inline super(TaskAdmin, self).save_model(request, obj, form, change) Can someone help me? -
Celery does not registering tasks
Hello! I just started to use Celery with Django. I've a task that i need to be periodic. In admin interface I can see my task in dropdown list named "Task (registered):". But when Celery Beat tries to execute it NotRegistered exception is thrown. Python 3.5.2, Django 1.11.4, Celery 4.1, django-celery-beat 1.1.0, django-celery-results 1.0.1 Part of settings.py related to celery: CELERY_BROKER_URL = 'amqp://user:*****@192.168.X.X/proj' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Moscow' celery.py and proj/__init__.py are identical to documentation examples. proj/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object(settings, namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) proj/__init__.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] tasks.py: from celery import shared_task from core.backend.files import SFTP @shared_task def load_files_from_sftp(): ftp = SFTP() ftp.get_files() I get the following json result: {"exc_message": "'core.tasks.load_files_from_sftp'", "exc_type": "NotRegistered"} If I try to use celery.task.control.inspect() from shell, it is only debug_task() there. Just stuck! ( I'll be grateful for any help. -
Integrate flask with legacy Database
I am new with flask, I am trying to create model classes from existing database tables ,in Django to achieve that we can use python manage.py inspectdb it will create a model classes. Is there any slimier option in flask ? I searched it and found some options like SQLAlchemy's autoload, it does not creates models classes on the fly. Please suggest.. -
django NOT NULL constraint failed error
I am having an error in the form :NOT NULL constraint failed: website_team_members.myuser_id in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team. I am getting that error when trying to assign an existing user in the data base here is my code : def TeamRegister2(request): #import pdb; pdb.set_trace() InviteFormSet = formset_factory(InviteForm2) if request.method == 'POST': formset = InviteFormSet(request.POST) if(formset.is_valid()): for i in formset: mail = i.cleaned_data['Email'] if MyUser.objects.filter(email = mail).exists(): user = MyUser(email = mail) u1 = user.id # get user ID a1 = MyUser.objects.get(email = request.user.email) #get user email a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user a3 = a2.latest('id') # extract the last project a4 = a3.team_id # extract the team linked to the project a4.members.add(u1) # add the member to the team invited_user = MyUser.objects.get(email = mail) current_site = get_current_site(request) message = … -
Using the reserved word "class" as field name in Django and Django REST Framework
Description of the problem Taxonomy is the science of defining and naming groups of biological organisms on the basis of shared characteristics. Organisms are grouped together into taxa (singular: taxon) and these groups are given a taxonomic rank. The principal ranks in modern use are domain, kingdom, phylum, class, order, family, genus and species. More information on Taxonomy and Taxonomic ranks in Wikipedia. Following the example for the red fox in the article Taxonomic rank in Wikipedia I need to create a JSON output like this: { "species": "vulpes", "genus": "Vulpes", "family": "Canidae", "order": "Carnivora", "class": "Mammalia", "phylum": "Chordata", "kingdom": "Animalia", "domain": "Eukarya" } Since Django REST Framework creates the keys based on the field names, the problem arises with the taxonomic rank class (bold in the example) as it is a reserved word in Python and can't be used as a variable name. What I have tried A model class created in Django would look like this: class Species(models.Model): species = models.CharField() genus = models.CharField() family = models.CharField() # class = models.CharField() - class is reserved word in Python # class_ = models.CharField() - Django doesn't allow field names # ending with underscore. That wouldn't be either a satisfying … -
django rest framework syntax error in exceptions.py
I am getting syntax error in exceptions.py which is in rest_framework package of site_packages. I have tried to correct those lines but as such there is no error. -
My Django website not showing any forms when I edit
I'm building a website using Django. And for somereason, the dictionary using all the forms is not showing at all.. When I click my Edit button the modal is showing without the forms... forms.server_id needs to contain all the forms using server_id... the server_id I use to show the previous data when I edit. But for some reason, it doesn't show any form at all... index.html - <div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Edit Server <strong>{{ server.ServerName }}</strong> </h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% with server.id as server_id %} <form action="{% url 'edit_post' server_id %}" method="post"> {% csrf_token %} <!--<center> {{ forms.server_id.as_p }} </center> --> {% for field in forms.server_id %} <div class="fieldWrapper"> {{ field.errors }} <!-- {{ field.label_tag }} --> <small><strong>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </strong> {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> <div class="wrapper"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>&nbsp;&nbsp;&nbsp; <h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2> </div> </form> {% endwith %} </div> </td> </tr> {% endfor %} </tbody> </h5> </table> views.py - # Create your views here. from … -
cursor.execute doesn't return anything in django but it works on mysql
So I have a query I want to run in Django using cursor.execute: def get_user_history(user_id): with connection.cursor() as cursor: cursor.execute(""" SET @user_id = %s; SELECT * FROM ( SELECT channel_id, NULL as article_id, NULL as comment_id, NULL as friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM channel WHERE user_id = @user_id UNION ALL SELECT channel_id, article_id, NULL as comment_id, NULL as friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM article WHERE channel_id in (SELECT channel_id from channel where user_id = @user_id) UNION ALL SELECT NULL as channel_id, article_id, comment_id, NULL as friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM comment WHERE user_id = @user_id UNION ALL SELECT NULL as channel_id, NULL as article_id, NULL as comment_id, friend_id, NULL as followed_channel_id, NULL as liked_article_id, created_at FROM user_friends WHERE user_id = @user_id UNION ALL SELECT NULL as channel_id, NULL as article_id, NULL as comment_id, NULL as friend_id, channel_id as followed_channel_id, NULL as liked_article_id, created_at FROM user_follows_channel WHERE user_id = @user_id UNION ALL SELECT NULL as channel_id, NULL as article_id, NULL as comment_id, NULL as friend_id, NULL as followed_channel_id, article_id as liked_article_id, created_at FROM user_likes_article WHERE user_id = @user_id ) T1 ORDER BY created_at; """, [user_id]) if cursor.fetchall(): return dictfetchall(cursor) … -
Setting points for an object in pinax-points
I want to set points or upvote or downvote for an object using pinax-points But there is no documentation. I'm adding docs but I'm unable to figure out how to add upvotes or downvotes. I can get the points using this documentation I have added, but can't set them {% load pinax_points_tags %} {% points_for_object user as points %} <div class="user-points">{{ points }}</div> -
Add filter and export to excel in django app without using django tables-2
i need to add an option to filter data according to some column categories earlier i was using django tables_2 to display my table but that i was not able to filter data using that and decided tow rite my own view my home.html looks like this <thead> <tr> <th>Customer Name</th> <th>Status</th> <th>Product</th> <th>Operating System</th> <th>Server Type (PHY/VM/LPAR)</th> <th>Version</th> </tr> </thead> <tbody> <tr> {% if custom %} {% for item in custom %} <tr> <td>{{ item.name }}</td> <td>{{ item.Status}} </td> <td>{{ item.Product}}</td> <td>{{ item.Operating_System}}</td> <td>{{ item.Server_Type}}</td> <td>{{ item.Version}}</td> </tr> {% endfor %} {% else %} there are no records {% endif %} </tbody> Now my table is displayed but I would like to give an option to filter data and also an option to export that to excel sheet after filtering how should i go about it ? -
Host Not Allowed 192...224 even though it is already in my django project
I have a django project that I have puhsed to docker and then a digital ocean server for live testing in a working environment. In the settings file, I have an ip address from my digital ocean server added to the allowed host portion of the settings file, but I am getting the following error: DisallowedHost at / Invalid HTTP_HOST header: '192...244:8000'. You may need to add '192...244' to ALLOWED_HOSTS. Here is the code I have ALLOWED_HOSTS = ['192...244', 'localhost', '127.0.0.1'] I didnt add the full Ip even though I have the fill ip in my files. -
How do I set django generic foreign key from my views?
I have 4 forms that the user submits by clicking one Submit button. The forms are: Person Form - Will Save to Person Model Address Form - Will Save to Address Model Email Form - Will save to Email Model Phone Form - Will save to Phone Model. So, a Person can have multiple Addresses, Emails and Phone Numbers. So, I did this in the Person Model: class Person(models.Model): first_name = models.CharField(max_length=99) middle_name = models.CharField(max_length=99, blank=True, null=True) last_name = models.CharField(max_length=99, blank=True, null=True) address = GenericRelation('Address') phone = GenericRelation('Phone') email = GenericRelation('Email') I have these 3 lines along with their respective model fields for Address, Phone and Email content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Now, how do I save data to these models properly in my views when I receive the form from the user? This what I have so far. if request.method == 'POST': if person_form.is_valid() and address_form.is_valid() and email_form.is_valid() \ and phone_form.is_valid(): address = address_form.save() email = email_form.save() phone = phone_form.save() person = person_form.save(commit=False) #This person model has a generic foreign key relation with Address, Email and Phone person.address = (address) #This is where I need help. Am I thinking right? Is this the … -
How can I avoid inline styling, yet take advantage of the templating language?
For each instantiation of an object in the template, I'd like to extract it's associated ImageField's url in order to show the photo. But I'm having trouble finding a way to do this without inline styling: {% for entry in entries %} <div class="row"> <div class="col s4"> <div class="card-panel" style="background-image: url('{{entry.image.url}}');"> <h1>{{entry.title}}</h1> </div></div></div> {% endfor %} This works in bringing each individual image to the template, but I wonder if I can abstract away the css just to keep my css in a separate file. -
Django matching query does not exist - about encoding
I've got a Error: "User does not exist" when I'm querying in Django by Chinese name of users. related codes: reload(sys) sys.setdefaultencoding('utf-8') user_name = sheet.cell_value(r, 7).replace(' ', '') equipment.eq_receiver = User.objects.get(user_name=user_name) class User(AbstractUser): user_id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=20) Traceback: Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "F:/repositories/ITIMS\eqp_mgt\views.py", line 652, in import_excel equipment.eq_receiver = User.objects.get(user_name=user_name) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 380, in get self.model._meta.object_name DoesNotExist: User matching query does not exist. In Debugger,I got the value of user_name: user_name={unicode}u"邵阳" Then in Watches view of Pycharm,I tried some other queries,but the result confused me: User.objects.get(user_name=u'\u90b5\u9633')={User}邵阳 #unicode of '邵阳' User.objects.get(user_name=u'邵阳')={DoesNotExist}User matching query does not exist. User.objects.get(user_name='邵阳')={User}邵阳 User.objects.get(user_name=user_name)={DoesNotExist}User matching query does not exist. -
When will a Django model instance with multi relations (ForeignKey with CASCADE) be deleted?
Having class C with relation to A & B and on_delete is set to CASCADE: class A(models.Model): pass class B(models.Model): pass class C(models.Model): palette_operation = models.ForeignKey(A, on_delete=models.CASCADE, blank=True, null=True) palette_operation = models.ForeignKey(B, on_delete=models.CASCADE, blank=True, null=True) If delete A while B is null, will C be deleted? If delete A while B is not null, will C be deleted? -
How to create a serializer class to return json of such a view?
I'm beginning to learn django and I did the polls app first and an extended version of it, now I'm trying to create a JSON-api for the same app using the REST framework. Models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') total_votes = models.IntegerField(default=0) pop_response = models.CharField(max_length=200, default='No responses yet') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now # used the following functions to order choices differently def choices_by_votes(self): return self.choice_set.order_by('-votes') def choices_by_text(self): return self.choice_set.order_by(Lower('choice_text')) # admin page config was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text View: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now() - datetime.timedelta(days=1)).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' Serializer view for the list of question @csrf_exempt def question_list(request): """ List all questions """ if request.method == 'GET': questions = Question.objects.all() serializer = QuestionSerializer(questions, many=True) return JsonResponse(serializer.data, safe=False) Serializer for the same question list class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('id', 'question_text', 'pub_date', 'total_votes', 'pop_response') Now this works fine, this gives me an equivalent json response to … -
Django join multiple models using django ORM
I googled and read many articles but got confused in multiple table join. My models looks like- class ProductCategory(models.Model): category_name = models.CharField(max_length=200,blank=True, null=True, unique=True) category_image = models.ImageField(upload_to='category', null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.category_name) class ProductSubCategory(models.Model): category = models.ForeignKey(ProductCategory) sub_category_name = models.CharField(max_length=200,blank=True, null=True, unique=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) sub_category_image = models.ImageField(upload_to='subcategory', null=True, blank=True) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.sub_category_name) class Product(models.Model): category = models.ForeignKey(ProductCategory) sub_category = models.ForeignKey(ProductSubCategory) product_name = models.CharField(max_length=200,blank=True, null=True) product_price = models.FloatField(default=0) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) # is_discountable = models.CharField(max_length=3, default='Yes', choices=option) status = models.CharField(max_length=10, default='Active', choices=status) def __unicode__(self): return '%s' % ( self.product_name) class ProductColor(models.Model): product = models.ForeignKey(Product) product_color = models.ForeignKey(Color, related_name='product_color_id', blank=True, null=True) product_size = models.ForeignKey(Size, related_name='product_size_id', blank=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) product_image = models.ImageField(upload_to='images', null=True, blank=True) Now in views, I want to get the product filters according to category and sub-category having all the images and colors. -
Django IntegrityError null value in column "author_id" violates not-null constraint
I am trying to save a form where I take user inputs. I am getting Integrity error. Can anyone please help me out here? I see that people have used request.user.username but I don't see how to use this in my forms. Please don't mind the code as I am still trying to figure out things in Django. Below are my files: models.py class CommonModel(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=400) comments = models.TextField(blank=True) requirements = JSONField(default = {}) specs = JSONField(default= {}) created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(blank=True, null=True) class Meta: abstract = True def update(self): self.updated_date = timezone.now() self.save() def __str__(self): return self.title class Item(CommonModel): HW = 'HW' NW = 'NW' SW = 'SW' VM = 'VM' WI = 'WI' SI = 'SI' ITEM_TYPES = ( (HW, 'Hardware'), (NW, 'Network'), (SW, 'Software'), (VM, 'Virtual Machine'), (WI, 'Work Item'), (SI, 'Support Item'), ) UNIT_LOE = 'LOE' UNIT_USD = 'USD' UNIT_TYPES = ( (UNIT_LOE, 'LOE,MD'), (UNIT_USD, 'USD'), ) item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES) unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES) otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2) annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2) gp_code = models.TextField(default='Unknown') class Meta: abstract = True class ItemTemplate(Item): pass # Need ID here to relate to estimate class ItemObject(Item): pass … -
Grabing first object for each item related to items in an array - DJango
I have a django project I am working on. I have two tables which are groups and group activities. Groups store information about the group that is created. GroupActivity stores all of the activities that are related to a group. for instance a group called Welcome would be stored in the group table with info about the group. if a member is added to the group there would be a record of the activity in the group activity table. I want to create a system that allows me to grab all of the groups someone is a part of and for each group, grab the last activity that happened for each of the groups that the user is a member of. I tried using two different queries and use two for loops but it is not working at all. Can anyone help me with this.. here is the code I have Here are the tables: class Group(models.Model): name = models.CharField(max_length = 25) description = models.CharField(max_length = 250, null=True) created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) class GroupActivity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE) bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True) description = models.CharField(max_length=200, default='some … -
python/django logging with decorators
I want to place a decorator on every function to log everything happening in the function. i have made a wrapper function and decorator to log the function with decorator. views.py def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): r = func(*args, **kwargs) logging.getLogger(__name__) logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) return r return func_wrapper class UsersViewSet(viewsets.ViewSet): @func_detail def list(self, request): queryset = Mytable.objects.all() if request.GET.get('name'): queryset = queryset.filter(name=request.GET.get('name')) serializer = CheckSerializer(queryset, many=True) logging.info("GET request and returned response") return Response(serializer.data) The problem is log file is not created in this code. Also, it got created on a different project but didnot print anything in log file(empty log file). I want to print a message in log file for everything that is happening, but this doesn't seem to work. Plz help. -
django rest framework nested filter
I want to get all the "Registro_Entrada" and filter them by "Entrante" when "fk_tipo_entrante" is equal to "2". On VIEWS.py I have: class GetPersonalEntranteRegistro_EntradaAPIView(generics.ListAPIView): serializer_class = Registro_EntradaNestedSerializer def get_queryset(self): entrante = Entrante.objects.all().filter(fk_tipo_entrante=2) registro = Registro_Entrada.objects.filter(fk_entrante = entrante.pk) return registro On SERIALIZERS.py I have: class Registro_EntradaNestedSerializer(serializers.ModelSerializer): fk_tarifa = TarifaSerializer(many=False) fk_entrante = EntranteNestedSerializer(many=False) class Meta: model = Registro_Entrada fields = ('_all_') On MODELS.py I have: class Entrante(models.Model): fk_credencial = models.ForeignKey(Credencial,related_name='credencial_entrada',on_delete=models.CASCADE) fk_placa = models.ForeignKey(Placa, related_name='credencial_placa',on_delete=models.CASCADE) fk_tipo_entrante = models.ForeignKey(Tipo_Entrante,related_name='entrante_tipo',on_delete=models.CASCADE) fk_persona = models.ForeignKey(Persona,related_name='entrante_persona',on_delete=models.CASCADE) estatus = models.IntegerField(default=1) class Registro_Entrada(models.Model): fecha_entrada = models.DateTimeField(auto_now_add=True) fecha_salida = models.DateTimeField(null=True) fk_tarifa = models.ForeignKey(Tarifa,related_name='registro_tarifa',on_delete=models.CASCADE) fk_entrante = models.ForeignKey(Entrante,related_name='regitro_entrante',on_delete=models.CASCADE) costo = models.DecimalField(decimal_places=2, max_digits=50) saldo = models.DecimalField(decimal_places=2,max_digits=50) estatus = models.IntegerField(default=1) It shows the following error: 'QuerySet' object has no attribute 'pk' -
Django apps on Heroku: how to access a shared database
On Heroku, it is possible to share a database among apps using the following command: $ heroku addons:attach <databaseName> -a <appName> where <databaseName> is the shared database (belonging to another app) and it is attached to the app <appName> (a Django application). I googled around for a long time but couldn't find anything describing how to access the attached database in the app. Do I need to add or modify something to Django's settings.py and what? How do I access the attached database in Django's views.py? The following is the setting for Heroku databases and database accessing is just via ORM. # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES = {'default':dj_database_url.config()} # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Thanks. -
Angular unexpected token return
I'm trying to integrate easyformgenerator in my django project, but when I attempt to create the controller, I get an error saying 'Uncaught SyntaxError: Unexpected token return' this is how I'm doing it // forms var formApp = angular.module('formApp', ['eda.easyFormViewer']); formApp.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; }]) formApp.controller('formCtrl', ['$scope', '$http', function ($scope, $http) { $scope.forms = form; $scope.viewHistory = function(element) { $http({ method: 'GET', url : '{% url "employee:ajax-view-responses" %}' + "?fid="+element+"&eid="+employee, headers: {'Content-Type': 'applicant/x-www-form-urlencoded'}, }).then(function success(response) { console.log(response); $('#ResponseList').html(response.data); }) }; }]); formApp.controller('demoController', ['$scope', '$http', function ($scope, $http) { var demoCtrl = this; demoCtrl.showDataModel = false; demoCtrl.fieldsModel = testACompleteForm(); demoCtrl.submitFormEvent = submitFormEvent; function submitFormEvent(dataModelSubmitted){ debugger $http({ method: 'POST', url : '{% url "employee:ajax-fresponse-save" %}', data: JSON.stringify(dataModelSubmitted), headers: {'Content-Type': 'applicant/x-www-form-urlencoded'}, }).then(function(){ location.reload() }) } function testACompleteForm(){ var data = {{ fbuilder.fjson|safe }} return data } }]); -
Heroku App Not Compatible with Python Buildpack
I'm trying to deploy a Django/Python application that runs locally, but will not deploy to Heroku. When trying to deploy, I receive the error: App not compatible with buildpack: https://codon- buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz I've tried multiple solutions to this issue. Currently my build pack is set to the Python build pack. (heroic build packs returns heroku/python). I have a Procfile, requirements.txt, runtime.txt, and Pipfile.lock, all of which usually resolve this issue. Procfile: web: gunicorn foodForThought.wsgi:application --log-file - requirements.txt: Django==1.11.8 pytz==2017.3 runtime.txt: python-3.6.0 Pipfile.lock: [requires] python_full_version = "3.6.0" All the aforementioned files are located in my home directory, and I'm also working in a virtual environment. Why is this error occurring? -
Retrieve multiple values via SELECT Option in Django Templates
I'm using Python(3.6) & Django(1.10) and need multiple values from a drop-down option selection. Here's what I have tried: From template: <select id="slc" name="cluster"> <option value="{{cluster.name}}#{{cluster.zone}}"> {{ cluster.name }}</option> </select> From views.py: blocks = request.POST.get('cluster').split('#') print(blocks) How can i get the values for name & zone.I already take a deep look at the existing questions but couldn't solve my issue.So, don't mark this question as a duplicate, please! Help me, Please! Thanks in advance!