Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - building a filter for real estate project
In order to practice what I learnt I started a django project about an real estate website. The next step is to build the search page where the user can select multiple filters, for exemple, number of rooms, baths, area, city ... At the book I read I used a search engines (Sorl with django haystack), so I am wondering if I should use it to filter the user conditions on the DB, or if I should keep it simple using only djando queries with many "ifs". What do you suggest me? -
Django access a queryset attribute in RawSQL extra/annotate query
I am trying to use Django admin's LogEntry model as a tracking system across my whole site. It is easy enough to store an entry in the LogEntry table when I save an object, but now I need an efficient way to retrieve that information for large sets of objects. Ideally I want to create a method that adds two fields to any QuerySet that I pass it: 'added_on' which comes from LogEntry.action_time, and 'added_by' which comes from LogEntry.user_id. For the sake of efficiency I only want to retrieve the tracking fields for a query after I have done the other filtering. Because of this I'm stuck working with querysets. I have tried using RawSQL with extra and annotate. The issue that I keep running in to is that I can't access the id field of the QuerySet within the RawSQL query. The method below is an example of what I am trying to do with just the added_on field using the queryset.extra() def add_tracking_info(self, qs): ct = ContentType.objects.get_for_model(qs.model).id return qs.extra(select={'added_on': 'SELECT django_admin_log.action_time FROM django_admin_log WHERE django_admin_log.content_type_id=%s AND django_admin_log.action_flag=1 AND django_admin_log.object_id=%s'}, select_params=(ct,'id')) The problem is at the end of the line: 'id', I need some way of getting the id … -
Questionnaire Form - Django
I am trying to build questionnaire-like app. I have already build the models.py which look like this: # models.py class QuestionSet(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return "{} Question Form".format(self.name) class Question(models.Model): q_set = models.ForeignKey(QuestionSet, on_delete=models.CASCADE, related_name='questions') text = models.CharField(max_length=100) def __str__(self): return self.text class Answer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='answers') question = models.ForeignKey(Question) text = models.CharField(max_length=100) def __str__(self): return "Answer to {}".format(self.question) However I am struggling to come up with the form which would correctly display this on the front-end and then validate the input data. I've tried displaying question's text from my Question Model and adding input fields beneath, all of this without using Django Forms. While this might look like it works, it raises raises the problem of data validation and associating data with particular question(hidden field with question id value). Is there any way where I can create form, with multiple Questions (all belonging to the same QuestionSet), which would display read-only field(Question Model's text field) and associated input field beneath(Answer Model text field)? -
Django Signals weird behaviour | Not getting content on observer
I'm using django's built in Signals for the first time. It's working 50-50 for a reason I don't understand. For our model we have Comment For my observer(s), I have them in signals.py from django.db.models.signals import post_save from django.dispatch import receiver from CustomApp.models import Comment @receiver(post_save, sender=Comment) def save_comment(sender, instance, created, **kwargs): print isntance.message If we create a comment through the django's admin panel, it prints out message just fine. But if we do it on the front end, form is submitted through AJAX using the usual object creation, I get nothing on the print. The code for creating comment object is c = Comment() c.message = request.POST.get('message') c.save() So, what went wrong? What is the difference? Would other method in object creation makes difference? Like Comment.objects.create(message=request.POST.get('message')) -
Django Urls with a dot
I'm trying to match a url like: /api/1.0/page/1 I've got my main urls.py file: urlpatterns = [ url(r'^api/1.0/', include('api_v1.urls')), ] and then in my api_v1/urls.py file: urlpatterns = [ url(r'^page/(?P<page_id>[0-9]{4})/', views.page), ] I feel like it should be simple but I can't get it to work. -
python decimal precision and django DecimalField
Why I get wrong precision here? I've asked 3 decimal digits after the floaing point. >>> from decimal import Decimal >>> from decimal import getcontext >>> getcontext().prec = 3 >>> Decimal(1.111) + Decimal(2.222) Decimal('3.33') # Why not 3.333? And second question, for django DecimalField, I define my field like this: value = models.DecimalField(max_digits=10, decimal_places=3) does it gives the same result as setting getcontext().prec = 3 for Decimal? -
Securing Django OAuth Toolkit Views
We're looking to implement Django OAuth on our backend in order to integrate Alexa and other 3rd party APIs. We've been following the tutorials on their site (http://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial.html), but have run into a security question that has so far escaped us: Is there a security concern that any user can access https://<oursite.com>/o/applications? If so, what steps need to be taken to prevent users from accessing these views? The only relevant questions on SO weren't particularly helpful: Secure creation of new applications in Django OAuth Toolkit Disable or restrict /o/applications (django rest framework, oauth2) -
Creating related objects in a TestCase is not reflected in Model method
I am in the middle of writing tests and must be missing something basic, because it appears that objects that I create remain isolated. I have Customers that can hold a number of Items. Inside the test, after creating Items (with a price) belonging to a Customer, I want to sum the prices of the items for a Customer (using a Customer method), but keep getting 0. The actual code is more complex, so I simplified the details while keeping the structure and logic the same. The version with the "production" database works fine, so there must be something about the way tests and their databases are run that I am missing. ### models.py class Customer(models.Model): name = models.CharField(max_length=20) def compute_total(self): total = 0 items = self.item_set.all() for item in items: total += item.price return total def __str__(self): return self.name class Item(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) name = models.CharField(max_length=20) price = models.IntegerField() def __str__(self): return "%s %s (%s)" % (self.customer, self.name, self.price) ### tests.py class CustomerTests(TestCase): def test_add_two_items(self): ken = Customer(name="Ken") apple = Item(customer=ken, name="apple", price=10) banana = Item(customer=ken, name="banana", price=2) print(apple) # make sure apple is created, and it is. self.assertEquals(ken.compute_total(), 12) For the "production" version, I manually add … -
Django ManyToMany Field in Both Tables
The Django docs say you can put a many to many field in either side's model, but not both. Example showing Pizzas and Toppings says it's more "normal" to think of the toppings on a pizza than think of which pizzas a topping is on, so put the field in the pizza model. OK... However, in my application which tracks permissions and groups, this is not necessarily true. The application has a many-to-many in the permissions table showing which groups have that permission. It also seems like you should be able to look at a group and see what permissions it has. This would theoretically use the same join table. Couldn't I add a many-to-many-through field in the groups model and specify the existing permission_group join table? Would this cause problems, as it directly violates the recommendation in the ManyToMany documentation? Thanks... -
Django Inline for ManyToMany generate duplicate queries
I'm experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have. models.py class Setting(models.Model): name = models.CharField(max_length=50, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class DisplayedGroup(models.Model): name = models.CharField(max_length=30, unique=True) position = models.PositiveSmallIntegerField(default=100) class Meta: ordering = ('priority',) def __str__(self): return self.name class Machine(models.Model): name = models.CharField(max_length=20, unique=True) settings = models.ManyToManyField( Setting, through='Arrangement', blank=True ) class Meta: ordering = ('name',) def __str__(self): return self.name class Arrangement(models.Model): machine = models.ForeignKey(Machine, on_delete=models.CASCADE) setting = models.ForeignKey(Setting, on_delete=models.CASCADE) displayed_group = models.ForeignKey( DisplayedGroup, on_delete=models.PROTECT, default=1) priority = models.PositiveSmallIntegerField( default=100, help_text='Smallest number will be displayed first' ) class Meta: ordering = ('priority',) unique_together = (("machine", "setting"),) admin.py class ArrangementInline(admin.TabularInline): model = Arrangement extra = 1 class MachineAdmin(admin.ModelAdmin): inlines = (ArrangementInline,) If I have 3 settings added on inline form and 1 extra, I have about 10 duplicate queries SELECT "corps_setting"."id", "corps_setting"."name", "corps_setting"."user_id", "corps_setting"."tagged", "corps_setting"."created", "corps_setting"."modified" FROM "corps_setting" ORDER BY "corps_setting"."name" ASC - Duplicated 5 times SELECT "corps_displayedgroup"."id", "corps_displayedgroup"."name", "corps_displayedgroup"."color", "corps_displayedgroup"."priority", "corps_displayedgroup"."created", "corps_displayedgroup"."modified" FROM "corps_displayedgroup" ORDER BY "corps_displayedgroup"."priority" ASC - Duplicated 5 times. Could someone please tell me what I'm doing wrong right here? I've spent 3 days trying to figure the problem … -
What is type is Site.objects.get_current() in django ; it returns <SIte: example.com>. I need to serializer it
I am try to send an email with celery. I need to pass the send_email function the django site object, as obtained by Site.objects.get_current() (I am modifying django-registration-redux.) I am unable to serializer the object or know what type it is to work with it. Any Ideas? Thank you -
Issues getting Python 2.7 to work with my django project
For a while now I have been trying to get my django project install of badgr (badgr-server on github) working with mod_wsgi. I am pretty way in over my head but I do believe I have made some progress. Here is the error message I am currently getting: [Thu Nov 17 12:48:48.182772 2016] [core:notice] [pid 24556] AH00094: Command line: '/opt/rh/httpd24/root/usr/sbin/httpd' [Thu Nov 17 12:48:50.421089 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] mod_wsgi (pid=24558): Target WSGI script '/opt/badgr/code/apps/mainsite/wsgi.py' cannot be loaded as Python module. [Thu Nov 17 12:48:50.421165 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] mod_wsgi (pid=24558): Exception occurred processing WSGI script '/opt/badgr/code/apps/mainsite/wsgi.py'. [Thu Nov 17 12:48:50.421200 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] Traceback (most recent call last): [Thu Nov 17 12:48:50.421228 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] File "/opt/badgr/code/apps/mainsite/wsgi.py", line 27, in <module> [Thu Nov 17 12:48:50.421348 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] application = get_wsgi_application() [Thu Nov 17 12:48:50.421374 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] File "/opt/badgr/env/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application [Thu Nov 17 12:48:50.421450 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] django.setup() [Thu Nov 17 12:48:50.421472 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] File "/opt/badgr/env/lib/python2.7/site-packages/django/__init__.py", line 20, in setup [Thu Nov 17 12:48:50.421558 2016] [:error] [pid 24558] [remote 140.225.0.153:60440] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Thu … -
Django Rest - Create method, returns error 405 Method Not Allowed
I created a view to create a new object. In the DRF default page everything works fine, but when I try to create an simple HTML page as a user interface (by adding renderer_classes and template_name to the view), the following error occurs: 405 Method Not Allowed. I created an html page to retrieve/update a client detail information, and it works fine. However, I was unable to do so to create a new client. models.py class Client(models.Model): client_rut = models.CharField(max_length=12, unique=True, verbose_name="RUT") client_name = models.CharField(max_length=250, verbose_name="Nombre Cliente") client_region = models.CharField(max_length=50, verbose_name="Region") client_tel = models.CharField(max_length=20, blank=True, verbose_name="Telefono") client_email = models.EmailField(blank=True, verbose_name="E-mail") is_active = models.BooleanField(default=True, verbose_name="Activo") class Meta: ordering = ['client_rut'] def __str__(self): return self.client_rut + ' - ' + self.client_name urls.py urlpatterns = [ # /clients/ url(r'^$', views.ClientView.as_view(), name='clients'), url(r'^(?P<pk>[0-9]+)/$', views.ClientDetailView.as_view(), name='clientdetail'), url(r'^create/$', views.ClientCreateView.as_view(), name='clientcreate') ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html', 'xml']) serializers.py class ClientListSerializer(ModelSerializer): url = HyperlinkedIdentityField(view_name='clients:clientdetail',) class Meta: model = Client fields = '__all__' class ClientDetailSerializer(ModelSerializer): class Meta: model = Client fields = '__all__' views.py #this view works fine class ClientDetailView(views.APIView): queryset = Client.objects.all() serializer_class = ClientDetailSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'clientdetail.html' def get(self, request, pk): client = get_object_or_404(Client, pk=pk) serializer = ClientDetailSerializer(client) return Response({'serializer': serializer, 'client': client}) … -
Django Development Server Page not loading
I am trying to follow this tutorial for django https://docs.djangoproject.com/en/1.10/intro/tutorial01/ I did the set up and I am trying to create a new page. After starting the django server. python manage.py runserver I cant view the page in the browser. It says this page cant be displayed. But no error is shown at the djando command line terminal. -
How I fix erro in gunicorn when I deploy django app in Heroku?
When I run git push heroku masterthe build works with success, but, the app doen't works... Looking for some problems I open logs heroku logsand have it: > heroku logs 2016-11-17T16:53:48.005794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-11-17T16:53:48.005794+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-11-17T16:53:48.005794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/util.py", line 357, in import_app 2016-11-17T16:53:48.005795+00:00 app[web.1]: __import__(module) 2016-11-17T16:53:48.005795+00:00 app[web.1]: File "/app/myapp/wsgi.py", line 22, in <module> 2016-11-17T16:53:48.005796+00:00 app[web.1]: application = get_wsgi_application() 2016-11-17T16:53:48.005796+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2016-11-17T16:53:48.005797+00:00 app[web.1]: django.setup() 2016-11-17T16:53:48.005797+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/__init__.py", line 18, in setup 2016-11-17T16:53:48.005798+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2016-11-17T16:53:48.005798+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate 2016-11-17T16:53:48.005798+00:00 app[web.1]: app_config = AppConfig.create(entry) 2016-11-17T16:53:48.005799+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/django/apps/config.py", line 90, in create 2016-11-17T16:53:48.005799+00:00 app[web.1]: module = import_module(entry) 2016-11-17T16:53:48.005800+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/importlib/__init__.py", line 126, in import_module 2016-11-17T16:53:48.005800+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2016-11-17T16:53:48.005803+00:00 app[web.1]: ImportError: No module named 'base' 2016-11-17T16:53:48.006060+00:00 app[web.1]: [2016-11-17 13:53:48 -0300] [8] [INFO] Worker exiting (pid: 8) 2016-11-17T16:53:48.121161+00:00 app[web.1]: [2016-11-17 13:53:48 -0300] [9] [ERROR] Exception in worker process 2016-11-17T16:53:48.121165+00:00 app[web.1]: Traceback (most recent call last): 2016-11-17T16:53:48.121166+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/arbiter.py", line 557, in spawn_worker 2016-11-17T16:53:48.121167+00:00 app[web.1]: worker.init_process() 2016-11-17T16:53:48.121168+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 126, in init_process 2016-11-17T16:53:48.121169+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/base.py", line 136, in load_wsgi 2016-11-17T16:53:48.121168+00:00 app[web.1]: self.load_wsgi() 2016-11-17T16:53:48.121176+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2016-11-17T16:53:48.121177+00:00 … -
Get all rows where field matches another field in another table in django
Say that I have a table called watchlist, this contains a list of entities that I'm really concerned about: class Watchlist(models.Model): entity = models.ForeignKey(Entity) objects = WatchlistManager() def __str__(self): return str(self.entity) And say I have a list of alerts: class DistinctAlert(models.Model): alert_type = models.ForeignKey(AlertType, db_index=True, on_delete=models.CASCADE) entities = models.ManyToManyField(to='Entity', db_index=True, through='EntityToAlertMap') has_unattended = models.BooleanField(default=True) latest_datetime = models.DateTimeField() Disregarding what alert type is I'm trying to get all DistinctAlerts as long as the entity exists in the watchlist. Something like this: DistinctAlert.objects.filter(entities__in=Watchlist.objects.all()).all() But of ocurse this doesn't work since they require entity objects instead of watchlist objects. What's the best approach for this? Should I do: DistinctAlert.objects.filter(entities__in=[element.entity for element in self.all()]).all() Not sure if iterating over every element and constructing the list outside is the right way to do it, or if it's possible to pass a queryset like so: DistinctAlert.objects.filter(entities__in=Watchlist.objects.all()).all() (the above example wouldn't work for me since they're watchlist objects and not entity objects) -
Removing a superfluous INNER JOIN from a Django query
I have models like this describing music albums, tracks on them, and individual listens to particular tracks: class Album(models.Model): name = models.CharField(max_length=255) class Track(models.Model): name = models.CharField(max_length=255) class Listen(models.Model): track = models.ForeignKey('Track', related_name='listens', db_index=True) album = models.ForeignKey('Album', related_name='listens', db_index=True, blank=True) To get all the Tracks on an Album, ordered by the number of times they've been heard, I can do: Track.objects \ .annotate( listen_count=models.Count('listens', distinct=True) ) \ .filter(listens__album=1294) \ .order_by('-listen_count') This gets the results correctly but it seems inefficient. A simplified version of the resulting query is: SELECT track.id, track.name, COUNT(DISTINCT listen.id) AS listen_count FROM track LEFT OUTER JOIN listen ON (track.id = listen.track_id) INNER JOIN listen T3 ON (track.id = T3.track_id) WHERE T3.album_id = 1294 GROUP BY track.id, track.name ORDER BY listen_count DESC I can get the same results by losing that INNER JOIN: SELECT track.id, track.name, COUNT(DISTINCT listen.id) AS listen_count FROM track LEFT OUTER JOIN listen ON (track.id = listen.track_id) WHERE listen.album_id = 1294 GROUP BY track.id, track.name ORDER BY listen_count DESC That uses one less index and is about half the speed. But I can't work out how to get the Django ORM to do this. (I'm currently using SQLite, if that makes a difference, although will … -
Call method once to set multiple fields in Django Rest Framework serializer
How can I call the same method one time to set multiple fields with a Django Rest Framework serializer? This is what I do now but this clearly calls the method two times. How can I limit it to only be called once? class MyModel(models.Model): def GetTwoValues(self): foo = [] bar = [] # expensive operation return foo, bar class MyModelSerializer(serializers.HyperlinkedModelSerializer): foo = serializers.SerializerMethodField() bar = serializers.SerializerMethodField() def get_foo(self, obj): foo, _ = obj.GetTwoValues() return foo def get_bar(self, obj): _, bar = obj.GetTwoValues() return bar class Meta: model = MyModel fields = ('FirstValue', 'SecondValue',) -
Jquery .each not working on JSON response
This is coming from a request to get all objects of a Django apps, it is not getting a plain object, as the print says it is just a string Javascript : $.getJSON("/cadastro/getAllPessoas/", function(data){ console.log(data); console.log(typeof(data)); console.log($.isPlainObject(data)); //Raises error on isArrayLike(): $.each(data,function(){ arrayValues.push([this["pk"],this["fields"]["nome"]]); }) }); Console output : [{"model": "cadastroapp.djangotestpessoa", "pk": 1, "fields": {"nome": "Gabriel"}}] string false views.py : from django.core import serializers def getAllPessoas(request): data = serializers.serialize('json', Pessoa.objects.all(), fields=('objectid','nome')) return JsonResponse(data, safe=False) -
django-supervisor connection refused
I am using supervisor to run celery with a django 1.8.8. setup. also using django-supervisor==0.3.4 supervisor==3.2.0 but when i restart all proecsses, i get unix:///tmp/supervisor.sock refused connection not able to restart any processes, python manage.py supervisor --config-file=setting/staging_supervisor.conf --settings=setting.staging_settings restart all supervisor config file [supervisord] logfile_maxbytes=10MB logfile_backups=3 loglevel=warn nodaemon=false minfds=1024 minprocs=200 [program:celeryd_staging] environment=PATH="{{ PROJECT_DIR }}/../../bin" command={{ PYTHON }} {{ PROJECT_DIR }}/manage.py celeryd -l info -c 1 --logfile=/logs/staging-celeryd.log --settings=setting.staging_celery_settings redirect_stderr=false stdout_logfile=/logs/staging-celeryd-stdout.log stderr_logfile=/logs/staging-celeryd-stderr.log [program:celerybeat_staging] environment=PATH="{{ PROJECT_DIR }}/../../bin" command=/{{ PYTHON }} {{ PROJECT_DIR }}/manage.py celerybeat --loglevel=INFO --logfile=/logs/staging-celerybeat.log --settings=setting.staging_celery_settings redirect_stderr=false stdout_logfile=/logs/staging-celerybeat-stdout.log stderr_logfile=/logs/staging-celerybeat-stderr.log [group:tasks] environment=PATH="{{ PROJECT_DIR}}/../../bin" programs=celeryd_staging,celerybeat_staging [program:autoreload] exclude=true [program:runserver] exclude=true -
Accessing a django model in middleware (django>1.7)
I'm upgrading from django 1.6.5 to django 1.9, and in the process upgrading several middleware classes. Some of those middleware classes use models during the process_request or process_response phases. However, I'm getting a AppRegistryNotReady: Apps aren't loaded yet. error attempting to use them. Is there a way to import models during middleware? Should I move my import statements into the process_request / process_response methods? Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/newrelic-2.50.0.39/newrelic/api/web_transaction.py", line 1329, in _nr_wsgi_application_wrapper_ result = wrapped(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/newrelic-2.50.0.39/newrelic/api/web_transaction.py", line 1329, in _nr_wsgi_application_wrapper_ result = wrapped(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 158, in __call__ self.load_middleware() File "/usr/local/lib/python2.7/dist-packages/newrelic-2.50.0.39/newrelic/common/object_wrapper.py", line 302, in _wrapper result = wrapped(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 51, in load_middleware mw_class = import_string(middleware_path) File "/usr/local/lib/python2.7/dist-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/web/MyJobs/MyJobs/apache/../middleware.py", line 9, in <module> from django.contrib.sites.models import Site File "/usr/local/lib/python2.7/dist-packages/django/contrib/sites/models.py", line 83, in <module> class Site(models.Model): File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 94, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 239, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") AppRegistryNotReady: Apps aren't loaded yet. -
Django reverse OneToOneField lookup in unicode method
I have schedule and event models like this. class Schedule(models.Model): jan = models.FloatField(default=2.0) feb = models.FloatField(default=2.0) def __str__(self): return 'Some boring value' class Event(models.Model): name = models.CharField(max_length=20) schedule = models.OneToOneField(schedule, null=True, on_delete=models.CASCADE) def __str__(self): return self.name In my admin view, I want to add the schedule in an EventAdmin class in a collapsed fashion like this. class ScheduleAdmin(admin.ModelAdmin): fieldsets = [ ('Schedule', {'fields': ['jan','feb']}), ] class EventAdmin(admin.ModelAdmin): fieldsets = [ ('Event', {'fields': ['name',]}), ('Add schedule', {'fields': ['jan','feb'], 'classes': ['collapse']}), ] So when I add a schedule to an event, I want the schedule str method to return the related Event.name field in the admin form, instead of just 'Some boring value' as it does now. I also really only want to assign a schedule object once to an Event, instead of the form in admin showing a list - I want to disable the add if a schedule is assigned. -
Invalid unicode while sending a POST request to django with libcurl and jsoncpp
I've created a REST endpoint in Django using the rest-framework module; the simple code goes as below: models.py class Data(models.Model): name = models.CharField(max_length=256) description = models.TextField() def __str__(self): return self.name serializers.py class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('name', 'description') views.py def data_list(request): """ List all data. """ if request.method == 'GET': categories = Data.objects.all() serializer = DataSerializer(categories, many=True) return JSONResponse(serializer.data) elif request.method == 'POST': data = JSONParser().parse(request) serializer = DataSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400) I've tried sending POST requests using the RESTClient plugin for Firefox, and can validate that it works as-is. However, my use-case is that I'd like to write to the database using libcurl in a C++ application. If I use jsoncpp to create a JSON object, and then use libcurl to make a POST request, as below: void main() { Json::Value submitted_data; submitted_data["name"] = "data id"; submitted_data["description"] = "data description"; Json::StyledWriter writer; CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8000/data/"); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json; charset=UTF-8"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, writer.write(submitted_data).c_str()); res = curl_easy_perform(curl); if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); … -
change name of domain in admin Django CMS
always that I create a new project in django-CMS, when I go to the admin I see that It is posible to change the example.com for other name? How to do that? Thanks in advance -
Is there a way to have custom content with mezzanie/Django
I'm new using Mezzanine and figured out how to set-up pages where I can manage content from Admin page. But I have static pages, where I want to store some content and being able to control that content from Admin page. Is this something I can do with Mezzanine? I imagine that I need to create a model with richtext field add that model to admin interface and than somehow access to that model through templatage. But any exact example would greatly appreciated. Thanks!