Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apache WSGI vs. Django Development Server
I recently decided to deploy my Django project using Apache and mod_WSGI. So, whereas my dev server runs on localhost:8000, my "Apache WSGI" server runs on localhost. Everything looked good until I tried to POST to my Django REST API. For whatever reason, I can post perfectly fine to the Django dev server, but I cannot post to the Apache WSGI server. As a matter of fact, I do not even see that a POST attempt was logged when I look at my Apache logs--I can see url errors there (when I purposefully try to go to a page that doesn't exist for example) but no failed POST attempts. What can be causing this problem and how can I troubleshoot it? Could it be that the Django REST Framework is incompatible with WSGI? I am puzzled why everything else: admin page, logins, navigation, update views, forms, etc, work perfectly fine but this one thing is not even showing up in the logs. -
Django server not responding to Android app
I have a django rest framework api server which is currently being used with a react web application, and a chrome extension using react as well. The next step in the process is a react-native mobile application, but I'm having issues connecting to my api server from the mobile app. I've tried 2 libraries, fetch and axios. My web application and chrome extension are using axios, and they work just fine. When I do a simple get request to my server, I just get a "Network request error" with no other information. Requests to other servers work fine, which makes me think there's some configuration issue I have on my API server that is not allowing the android application to communicate with my API. The requests are just basic GET requests such as axios.get("https://example.com/endpoint/") or fetch("https://example.com/endpoint/"). -
Django cache_page doesn't work on production
I can't figure out why cache_page work's on my local Ubuntu 16.04 with redis and doesn't work on remote DigitalOcean droplet with the same configuration except I use daphne asgi as a server instead of Django built in runserver. Development: Ubuntu 16.04withredis, server: Django's runserver Production: DigitalOcean Ubuntu 16.04 with redis, asgi daphne server cache settings CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } view @method_decorator(cache_page(5 * 60), name='dispatch') class AjaxGetAllCities(View): """ returns, serialized, all cities currently being visited by at least one user """ def get(self, request, *args, **kwargs): cities = City.objects.currently_being_visited() return JsonResponse(CityMapSerializer(cities, many=True).data, safe=False) For debugging cache, I use Django-debug-toolbar with history where I see that if I call this url on my development server, it does either 2 or 3 cache calls but 0 cache calls on production server. What am I missing? -
Django Crispy forms - positional argument follows keyword argument error
Im new to crispy forms and am trying to use bootstrap to style some form fields into a bootstrap panel, then I will add some other fields into another panel and so on. Building the first panel I am getting the below error. something is awry but am not sure what? Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/itapp/itapp/sites/views.py" in edit_site 829. from sites.forms import EditSiteForm Exception Type: SyntaxError at /sites/edit/7 Exception Value: positional argument follows keyword argument (forms.py, line 53) this is my forms.py class EditSiteForm(forms.ModelForm): class Meta: model = SiteData fields = ['location', 'site_type', 'bgp_as', 'opening_date','last_hw_refresh_date','is_live', 'tel','address','town','postcode', 'regional_manager','regional_manager_tel','assistant_manager','assistant_manager_tel' ,'duty_manager','duty_manager_tel'] def __init__(self, *args, **kwargs): super(EditSiteForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'edit_site_form' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary')) self.helper.layout = Layout( Div(title='', css_class='panel panel-primary', Div(title='Details', css_class='panel-heading'), Div(css_class='panel-body', Field('location', placeholder='Location'), Div('site_type', title="Site Type") ), ) ) -
How to properly test your models in django
In rails I can easily test my models using rspec. How do you write tests for this example and verify if the choice model has a FK field? from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) -
django-recurrence is displaying a text field in admin instead of the proper field in django 2.0
It works fine in 1.11 but for some reason is not working in 2.0. I'm not sure what the issue is but would appreciate any feedback. I have been stuck with this issue for the past two days unfortunately. Here is the fields.py file from django-recurrence from django.db.models import fields from django.utils.six import string_types import recurrence from recurrence import forms from recurrence.compat import Creator try: from south.modelsinspector import add_introspection_rules add_introspection_rules([], [ "^recurrence\.fields\.RecurrenceField", ]) except ImportError: pass # Do not use SubfieldBase meta class because is removed in Django 1.10 class RecurrenceField(fields.Field): """Field that stores a `recurrence.base.Recurrence` to the database.""" def __init__(self, include_dtstart=True, **kwargs): self.include_dtstart = include_dtstart super(RecurrenceField, self).__init__(**kwargs) def get_internal_type(self): return 'TextField' def to_python(self, value): if value is None or isinstance(value, recurrence.Recurrence): return value value = super(RecurrenceField, self).to_python(value) or u'' return recurrence.deserialize(value, self.include_dtstart) def from_db_value(self, value, *args, **kwargs): return self.to_python(value) def get_prep_value(self, value): if not isinstance(value, string_types): value = recurrence.serialize(value) return value def contribute_to_class(self, cls, *args, **kwargs): super(RecurrenceField, self).contribute_to_class(cls, *args, **kwargs) setattr(cls, self.name, Creator(self)) def value_to_string(self, obj): return self.get_prep_value(self._get_val_from_obj(obj)) def formfield(self, **kwargs): defaults = { 'form_class': forms.RecurrenceField, 'widget': forms.RecurrenceWidget, } defaults.update(kwargs) return super(RecurrenceField, self).formfield(**defaults) -
PyCharm: [08004] The server requested password-based authentication, but no password was provided
Can't figure out why is PyCharm keeping raises this error: I have set everything including Django server configuration. Don't know if it's database problem. Connection works properly. The DB is remote on DigitalOcean droplet. in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'our_db', 'USER': 'django', 'HOST': '<ip>', 'PASSWORD': '<pwd>', 'PORT': 5432, 'ATOMIC_REQUESTS': True, } } I have connection to remote Ubuntu 16.04 where I use ssh key to authenticate. Do you know where is the problem? -
Django filter with Q and Exclude returning incorrect result
I will try and simplify everything to get to my issue. I am using Django==1.11.4 I have 3 models: class Booking(models.Model): provider = models.ForeignKey(Provider, null=True) class Provider(models.Model): title = models.CharField(max_length=100) class BreakHours(models.Model): weekday = models.CharField(max_length=9, choices=WEEKDAY_CHOICES) start_time = models.TimeField() end_time = models.TimeField() provider = models.ForeignKey(Provider) When a user makes a booking, I need to choose a provider such that the booking time chosen wont conflict with the provider's other booking times and break hours. Here is my implementation: Lets assume: total_assessment_time = 30 #in minutes booking_start_time_with_assessment = booking_start_time - timedelta(minutes=total_assessment_time) booking_end_time = booking_start_time + timedelta(minutes=total_assessment_time) st = datetime.strptime(str(booking_start_time.date()), '%Y-%m-%d') booking_weekday = str(calendar.day_name[st.weekday()]) breakhours = BreakHours.objects.filter( Q(provider__store__name=self.cleaned_data['store']) & ( ( Q(weekday=booking_weekday) & Q(start_time__lte=booking_start_time.time()) & Q(end_time__gt=booking_start_time.time()) ) | ( Q(weekday=booking_weekday) & Q(start_time__lt=booking_end_time.time()) & Q(end_time__gt=booking_end_time.time()) ) ) ).values_list('pk', flat=True) provider = Provider.objects.filter( Q(store__name=self.cleaned_data['store']) & Q(services__in=self.cleaned_data['services'])).exclude( ( Q(booking__starts_at__gte=booking_start_time_with_assessment) & Q(booking__starts_at__lte=booking_end_time) ) | ( Q(breakhours__pk__in=breakhours) ) ).distinct() if provider: return provider.first() My issue is that this query works fine, but for some reason the query doesnt return any of the providers even if there are absolutely NO bookings on the day chosen, and he doesnt have any breaks at the time of the booking. Is there any issue with Q or the exclude function in … -
Timezone settings django postgresql linux
I have a django website on linux using Postgre SQL in New Jersey server USA (linode.com) But the users are in a different timezone (Brazil). It is something fool I know, but I do some tests changing settings but nothing positive. Here is some enviroment settings: Linux Server (USA): $cat /etc/timezone Etc/UTC Postgres Console (USA): postgres=# show timezone; UTC Django settings.py (USA): TIME_ZONE = 'America/Sao_Paulo' USE_TZ = True Now the results. Brazil time now: 10:07h Linux Server time(USA): 12:07:52 UTC Here is something wrong! But ok, I don´t use system local time in my website! POSTGRE Console (USA): select now(); 2018-01-16 12:07:36.967415+00 I have a model 'coleta' with a field DATA_LEITURA. data_leitura = models.DateTimeField(null=True) Now I insert a register with 10:07:16h. This is correct time in Brazil! See: br_tz = timezone('America/Sao_Paulo') coleta.data_leitura = datetime(2018, 01, 16, 10, 07, 16, tzinfo=br_tz) In postgre console (USA): SELECT data_leitura FROM coleta; 2018-01-16 15:13:16+00 So incorrect! When the users (Brazil) open the website, they see: 15:13:16 I put this line br_tz = timezone('America/Sao_Paulo') This line solves the NAIVE warning and auto convertion! I am now changing each configuration to see the results... but nothing positive. I think that are two changes to do. My … -
Django ArrayField. How to save nested array of time?
Question is stupid, by i cant find solution. What a valid format for saving nested array of time from simple form text field? I have ArrayField like this: schedule = ArrayField( ArrayField( ArrayField( models.TimeField(null=True), ), size=2, null=True, ), size=7, null=True, blank=True, ) When i am trying to save it from django admin like: ((09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 09:00), (09:00, 9:00), (9:00, 9:00), (9:00, 9:00)) I'm getting errors Item 0 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 1 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 2 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 3 in the array did not validate: Item 0 in the array did not validate: Item 0 in the array did not validate: Enter a valid time. Item 4 in the array did not validate: Item 0 in the array did not validate: Item 0 … -
Operations between django objects
I am trying to perform operations between 2 django objects. Can you suggest on how to proceed on this? I have 2 objects class v_Sale(models.Model): Key_Variable=models.CharField(max_length=255,primary_key=True) Sales = models.CharField(max_length=255) class v_Threshold(models.Model): Key_Variable=models.CharField(max_length=255,primary_key=True) Threshold = models.CharField(max_length=255) I want to calculate (Sales-Threshold) and save it in a new variable. -
is not a valid regular expression: bad character in group name 'int:id' at position 13
from django.conf.urls import url from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name='index'), #path('details/<int:id>/', views.details), #re_path(r'^details/(?P<int:id>\d+)/$', views.details), ] kindly assist me with the URLs patterns above...commented. i am using django 2.0. when i run the browser i get django.core.exceptions.ImproperlyConfigured: "^details/(?P\d+)/$" is not a valid regular expression: bad character in group name 'int:id' at position 13 Performing system checks... my view.py is as below: from django.shortcuts import render from django.http import HttpResponse from .models import Todo # to render todo items def index(request): todos = Todo.objects.all() [:10] # define we want 10 context = { 'todos':todos # pass it onto a template variable todos } return render(request, 'index.html', context) def details(request, id): todo=Todo.objects.get(id=id) context = { 'todo':todo # pass it onto a template variable todos } return render(request, 'details.html', context) and the web address displayed by the browser is: http://127.0.0.1:8000/todo/details// hope this is enough info -
Django Restframework _ object level permission owner booleanfield
I made this custom Permission class that owner is related to django user model.and user model related to UserProfile model with related_name = "user_profile" in UserProfile model I have a BooleanField default is false. ad_ac = models.BooleanField(default=False) Im trying to write a custom permission class that tells if the request.user has ad_ac field True .can create or update from request. this is how get so far : class OwnerAdPermission(permissions.BasePermission): ''' object lvl permission for Ad owner ''' def has_object_permission(self, request, view, obj): if request.user.user_profile.ad_ac == True: return True return obj.owner == request.user -
get errors from client post method in django testing
Is there a quick way to get the errors from a form submission when using Client in a django test? Here's a code snippet: with open(good_path) as fp: data = { 'account': account_id, 'date': date, 'file': fp } response = client.post(reverse('myapp:form-page'), data) The page is not redirecting correctly (response=200) and I can see in response.content that there is an error being returned. Is there a quick way to isolate the error? I was hoping for something like response.errors, similar to a forms instance. -
How sending Context using reverse and http redirect [Django 2.0] [duplicate]
This question already has an answer here: HttpResponseRedirect reverse - passing context variable 1 answer I want to pass a variable using HttpResponseRedirect and reverse Django not as a parameter or argument but as a variable displayed later into my HTML template. To be more clear, I used this snippet without any result. error_msg = 'Wrong credentials' return HttpResponseRedirect(reverse('myapp:user_login', {'error_msg':error_msg})) {% if error_msg %} <p>{{ error_msg }}</p> {% endif %} I read these answers pass argument and passing context variable but they didn't help me a lot. -
How save Foreign relations from a Form Django
... I'm trying to save the data saved with 2 forms in 2 different models, but i don't know how save the relations. And after save the data, I need to show them as a one html form, well when the user typed the info is one html form too. with this view, I saved the info in both models, but I can't save the relation. May be the POST has a different to work in this problem .... I don't know view.py def proposeActivity(request): if request.method == "POST": form_1 = ActivityProposedForm(request.POST, prefix="form_1") form_2 = ActivityUrl_activity(request.POST, prefix="form_2") if form_1.is_valid() and form_2.is_valid(): post_1 = form_1.save(commit=False) post_2 = form_2.save(commit=False) post_1.author = request.user post_2.author = request.user post_1.save() post_2.save() return redirect('proposedActivities') else: form_1 = ActivityProposedForm(prefix="form_1") form_2 = ActivityUrl_activity(prefix="form_2") return render(request, 'registerActivity.html', {'form_1': form_1, 'form_2': form_2}) forms.py class ActivityProposedForm(forms.ModelForm): class Meta: metodologias_choices = [(metodologia.id, metodologia.methodology_name) for metodologia in Methodology.objects.all()] normas_choices = [(normas.id, normas.norm_name) for normas in Norm.objects.all()] # competencias_choices = # CHOICES = {('1', 'Activa'), ('2', 'Tradicional')} model = ActivityProposed fields = [ 'nombre_actividad', 'detalle_de_la_actividad', 'metodologia', 'nombre_de_la_norma', 'nombre_de_la_competencia', 'nombre_del_curso'] labels = { 'nombre_actividad': 'Nombre de la Actividad', 'detalle_de_la_actividad': 'Detalla de la Actividad', 'metodologia': 'Metodologia', 'nombre_de_la_norma': 'Nombre de la Norma', 'nombre_de_la_competencia': 'Nombre de la Competencia', 'nombre_del_curso': … -
Django Unkown Fields()
I've seen a lot of issues similar to mine, but none had exactly the same problem. I have my code running on another machine and it's working perfectly, it's exactly the same code since I'm using github for version control, but when I run on my machine I started to get this error, I use postgres, I already tried give drop in the database and create another but continue with this error. The error started after I imported the database from the machine that is running fine. When I tried to go back to the local database, I started to have an error, I already tried to reinstall all the packages (those installed via pip) and nothing. I'm using Django 1.10 Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x7f7aa3e35ef0> Traceback (most recent call last): File "/home/marco/documentos/pycharm/helpers/pydev/_pydev_bundle/pydev_monkey.py", line 589, in __call__ return self.original_func(*self.args, **self.kwargs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/marco/miniconda2/envs/mrturing2/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern … -
how to decode utf8 in bottle framework
I am a beginner to bottle framework. I am doing my project on the mentioned framework but on MVC structure meaning I have controller, model and view page. my project is admin panel. in part of modifying user information, after inputting new user information when i submit the new information i receive the new one in unreadable language. how I can make bottle read UTF8? -
Check values exists in another table
Sorry about my doubt, i'm a student. I have this scenario class Equipment(): id name ... class Alert(): id ... pin value equipment_id The tables (Equipment - Alert) have no relationship: I need to check if the id of the Equipment table exists in the Alerts table If there is need to return A, if there is no return B, and return th to template -
NoReverseMatch 1 pattern(s) tried: ['(?P<id>\\d+)/(?P<slug>[-\\w]+)/$']
I'm new in Django, using version 2.0. Started building a 'shop' application according to the 'Django by Example' book. But the book uses django version 1.8. The problem is, when I browse http://127.0.0.1:8000/ this error appears: "NoReverseMatch at/ Reverse for 'product_detail' with arguments '(None, 'alpina')' not found. 1 pattern(s) tried: ['(?P\d+)/(?P[-\w]+)/$']". 'alpina' is the product's name which I added from admin site. Here is urls.py of my app: from django.conf.urls import url from . import views app_name='shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'), ] Here is the models.py of my app: from django.urls import reverse from django.db import models class Category(models.Model): name = models.CharField( max_length=200, db_index=True ) slug = models.SlugField( max_length=200, db_index=True, unique=True ) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse( 'shop:product_list_by_category', args=[self.slug] ) class Product(models.Model): category = models.ForeignKey( Category, related_name='products', on_delete=models.CASCADE ) name = models.CharField( max_length=200, db_index=True ) slug = models.SlugField( max_length=200, db_index=True ) image = models.ImageField( upload_to='products/%Y/%m/%d', blank=True ) description = models.TextField( blank=True ) price = models.DecimalField( max_digits=10, decimal_places=2 ) stock = models.PositiveIntegerField() available = models.BooleanField( default=True ) created = models.DateTimeField( auto_now_add=True ) updated = models.DateTimeField( auto_now=True ) class Meta: … -
Django in listening mode on an url
I developed a web app with django: I call a soap service (using suds) and the service requires in input several parameters including a callback url and a push url. On the push url the queried service sends notifications of state change. I would need to put my app in listening mode to the push address to be able to intercept any calls made from soap service to my app on this url to communicate status changes. How can made this? -
Python Django celery periodic task in windows
I am creating a simple Django Celery app that implements periodictasks to execute a function periodically. All I have in this Django project is one app called 'app' The folder structure is sp │ db.sqlite3 │ manage.py │ ├───app │ admin.py │ apps.py │ models.py │ tasks.py │ tests.py │ views.py │ __init__.py │ └───sp celery.py settings.py urls.py wsgi.py __init__.py The celery.py contains from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sp.settings') app = Celery('sp') app.config_from_object('django.conf:settings') app.conf.timezone = 'Asia/Calcutta' app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py contains from celery.decorators import task from celery.decorators import periodic_task from sp.celery import app @app.periodic_task(run_every=(crontab(minute='*/1'))) def task_number_one(): return "1" Celery broker in settings.py is CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672/' In windows I start celery beat and celery worker seperately as celery -A sp beat -l info celery -A sp worker --pool=solo -l info Celery tasks run fine but periodic tasks that runs with celery beat are not executing. When i run them no error are shown in the command prompt Can anyone say what the problem is? Is that because of Windows operating system? or any source code error? -
Django Admin custom list_filter is not called
I've written a custom list filter for my ModelAdmin, using the tutorial at https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter. It works fine when taken out of the project into a test environment and fed directly with the filter value. In the actual project however, it shows the filter options but does not change the results when a filter is selected. What is strange is, the parameter is set to "balance" and the list of lookups defines "positive", "negative", and "settled"; but the respective URL querystring will only ever show ?e=1. Even if I input the querystring directly (e.g. ?balance=positive), I'm redirected to ?e=1 and see all objects. Here's the code: class AccountBalanceFilter(admin.SimpleListFilter): title = "Kontostand" parameter_name = "balance" def lookups(self, request, model_admin): return (("positive", "Positiv"), ("negative", "Negativ"), ("settled", "Ausgeglichen"),) def queryset(self, request, queryset): filter = self.value() if filter is None: return queryset elif filter == "positive": filtered_set = {account for account in queryset if account.get_current_balance() > 0} elif filter == "negative": filtered_set = {account for account in queryset if account.get_current_balance() < 0} elif filter == "settled": filtered_set = {account for account in queryset if account.get_current_balance() == 0} else: raise ValueError(f"The account balance filter only accepts filter values of 'positive', 'negative', or 'settled', but was given … -
Django and Angularjs - Incorrect json property name is send with post to api
I need some guidance here, still new to django and Angularjs. I have the django rest framework setup to display my departments with the below json returned. primary_locations is a foreignkey to my locations model. [ { "id": 52, "department_name": "Technical", "department_description": "Technical", "primary_locations": { "id": 1, "location_name": "ZA", "address": "ZA", "city": "ZA", "province": "ZA", "postal_code": "ZA", "country": "AG" } } ] In Angular I have a dropdown list that displays the available locations to select from. When I post the selected option I receive an error saying the following. Possibly unhandled rejection: {"data":"IntegrityError at /department\n(1048, \"Column 'primary_locations_id' cannot be null But when I scroll further down the page it shows the below was posted to the api {"department_name":"as","department_description":"as","locations":"4"}, Why is Angularjs sending the primary_locations_id name as locations and not primary_locations_id? Here is my controller system.controller('DepartmentCtrl', ['$scope', 'DepartmentsFactory', 'DepartmentFactory', 'LocationFactory', '$location', function ($scope, DepartmentsFactory, DepartmentFactory, LocationFactory, $location) { // Function to reload content on success $scope.reloadDepartments = function () { DepartmentsFactory.query( function( data ) { $scope.departments = data; }); }; // callback for ng-click 'editDepartment': $scope.editDepartment = function (id) { $location.path('/department/' + id); }; // callback for ng-click 'deleteDepartment': $scope.deleteDepartment = function (id) { DepartmentFactory.delete({ id: id }, function() { … -
Unknown command 'worker' in Celery 4.1.0
I'm not able to start celery worker in django application from the console. When I'm running celery worker --app=app1 -l info then Unknown command: 'worker' and if I'm running celery -A app1 worker -l info then Unknown command: '-A'. My celery config is following CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULE = { 'supplier-update': { 'task': 'app1.tasks.task1', 'schedule': 60, } }