Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to validate a field on update in DRF?
I have a serializer for a model with a foreign key. The requirement is that on create, foreign key can be set to any existing object from the related model, but on update the related object cannot be changed. I can check this in the custom update(), but it would be more elegant to use serializer validation to check for this? But I am not sure how. Example code: class Person(models.Model): name = models.CharField(max_length=256) spouse = models.ForeignKey(Person) class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person # this is how I know how to do this def create(self, validated_data): try: spouse = Person.objects.get(pk=int(validated_data.pop('spouse'))) except Person.DoesNotExist: raise ValidationError('Imaginary spouses not allowed!') return Person.objects.create(spouse=spouse, **validation_data) def update(self, person, validated_data): if person.spouse.pk != int(validated_data['spouse']): raise ValidationError('Till death do us part!') person.name = validation_data.get('name', person.name) person.save() return person # the way I want to do this def validate_spouse(self, value): # do validation magic -
Django 1.10 AppRegistryNotReady: Apps aren't loaded yet. I can't use django.setup
I'm facing an issue since I upgraded my django from 1.7.10 to 1.10.1. Indeed, I had the django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Error and in order to solve that I figured out that I had to remove django.setup() in order to solve the circular dependency (I assume). But then, I'm facing the error from the title: ``` Traceback (most recent call last): File "/var/www/webapps/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/var/www/webapps/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/var/www/webapps/lib/python3.4/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/var/www/webapps/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/var/www/webapps/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/var/www/webapps/lib/python3.4/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/webapps/lib/python3.4/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/var/www/webapps/lib/python3.4/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/var/www/webapps/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2231, in _gcd_import File "<frozen importlib._bootstrap>", line 2214, in _find_and_load File "<frozen importlib._bootstrap>", line 2203, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1448, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/var/www/webapps/lib/python3.4/site-packages/easy_select2/__init__.py", line 7, in <module> from easy_select2.utils import ( File "/var/www/webapps/lib/python3.4/site-packages/easy_select2/utils.py", line … -
Django Aggregation: Sum of Multiplication of two fields that are not in same model
I have three models (Django 1.6.5): class Vote(models.Model): voter = models.ForeignKey(UserSettings) answer = models.ForeignKey(Answer) rating = models.IntegerField() class Answer(models.Model): content = models.CharField(max_length=255) class UserSettings(models.Model): user = models.OneToOneField(User, related_name='settings') weight = models.FloatField(default=1.0) Basically, a user (voter) can vote for an answer by giving a rating. I know how to sum the ratings by answer: Vote.objects.all().values('answer').annotate(score=Sum('rating')) The only subtlety is that each voter has a weight (all voters are not equal!) and I want to sum each product rating*weight. I know (from here) that something like that can be done: Sum('id',field="field1*field2") and it would work well if my 2 fields are in the same model but it doesn't work if they are not. In other words, command: Vote.objects.all().values('answer').annotate(score=Sum('id',field="rating*voter__weight")) does not work. Any help greatly appreciated! -
Display objects related current user django admin
I'm trying to display only objects related to the current user. Users can upload a file and then they can only see their files in the admin. Here is my models : class Share(models.Model): owner = models.ForeignKey(User, default='') title = models.CharField("File's title", max_length=100, unique=True, default='File') zip_file = models.FileField('Shared File', upload_to=content_zip_name, validators= [validation_zip]) and my admin.py from django.contrib import admin from share.models import Share class ShareAdmin(admin.ModelAdmin): list_display = ('title',) save_as = True def queryset(self, request): qs = super(ShareAdmin, self).queryset(request) if request.user.is_superuser: return qs return qs.filter(owner=request.user) admin.site.register(Share, ShareAdmin) I tried with overriding the queryset function but doesn't work..any idea? -
python import MySQLdb
in python, import MySQLdb Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-intel.egg/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-intel.egg/_mysql.so, 2): Library not loaded: /usr/local/mysql/lib/libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-intel.egg/_mysql.so Reason: image not found I try ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib and other soultions but nothing help. My computer is OS X EI Capitan, python2.7.9 django1.8.2 mysql-5-7-15 -
Distinct values with Q objects
I have this query on my Django project 1.10.1 on Py3: Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id)) How can I prevent to get two identical Event records? Thank you in advance. -
Why got type error :takes 1 position argument but 2 were given?
I have faced a problem with my django project. It is as following: Get Result: __init__() takes 1 positional argument but 2 were given My code: urls.py url(r'^_get_weather', views._get_weather, name='_get_weather') views.py def _get_weather(request): r = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?APPID=$API&q=Hongkong') s = r.read().decode('utf-8') j = json.loads(s) temp='Current tempearture: {:.2f}'.format(j['main']['temp'] - 273.15) return HttpRequest(temp) -
How to simply change Django logging level to INFO?
I have noticed that my Django configurations seems to be set to not log at INFO level (logging.warn("Running: " + argsString) works but not logging.info("Running: " + argsString)). In order to change this, do I really have to write a complete logging configuration? And if so, I have googled a bit and started a bit here: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console':{ 'level':'INFO', 'class':'logging.StreamHandler', 'formatter': 'simple' }, }, 'loggers': { 'root': { 'level': 'INFO', 'handlers': ['console'] } } } But even after this I can still not get the logging call on INFO level to work. How do I do this? -
Why do I have so many Celery messages with CloudAMQP on Heroku?
My Django site running on Heroku is using CloudAMQP to handle its scheduled Celery tasks. CloudAMQP is registering many more messages than I have tasks, and I don't understand why. e.g., in the past couple of hours I'll have run around 150 scheduled tasks (two that run once a minute, another that runs once every five minutes), but the CloudAMQP console's Messages count increased by around 1,300. My relevant Django settings: BROKER_URL = os.environ.get("CLOUDAMQP_URL", "") BROKER_POOL_LIMIT = 1 BROKER_HEARTBEAT = None BROKER_CONNECTION_TIMEOUT = 30 CELERY_ACCEPT_CONTENT = ['json',] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_RESULT_EXPIRES = 7 * 86400 CELERY_SEND_EVENTS = False CELERY_EVENT_QUEUE_EXPIRES = 60 CELERY_RESULT_BACKEND = None CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' My Procfile: web: gunicorn myproject.wsgi --log-file - main_worker: python manage.py celery worker --beat --without-gossip --without-mingle --without-heartbeat --loglevel=info Looking at the Heroku logs I only see the number of scheduled tasks running that I'd expect. The RabbitMQ overview graphs tend to look like this most of the time: I don't understand RabbitMQ enough to know if other panels shed light on the problem. I don't think they show anything obvious that would account for all these messages. I'd like to at least understand what the extra messages are, and then whether … -
Two Django projects using same database
I have a database that is being used by my django project and a php project. So now i am about to add another separate django project which will use the same database. After setting up the project i wrote models.py and when i tried to run server it is giving error: - System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7fcedb0338c0> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check_migrations() File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 163, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 299, in build_graph parent = self.check_key(parent, key[0]) File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/loader.py", line 160, in check_key raise ValueError("Dependency on app with no migrations: %s" % key[0]) ValueError: Dependency on app with no migrations: apiapp It is not allowing me to run python manage.py migrate. How to cope up with this type of problem. -
django get default model field value
I want to write a view to reset some model field values to their default. How can I get default model field values? class Foo(models.Model): bar_field = models.CharField(blank=True, default='bar') so what I want is: def reset(request, id): obj = get_object_or_404(Foo, id=id) obj.bar_field = # logic to get default from model field obj.save() ... -
Django sum values of a column after 'group by' in another column
I found some solutions here and in the django documentation, but I could not manage to make one query work the way I wanted. I have the following model: class Inventory(models.Model): blindid = models.CharField(max_length=20) massug = models.IntegerField() I want to count the number of Blind_ID and then sum the massug after they were grouped. My currently Django ORM samples = Inventory.objects.annotate(aliquots=Count('blindid'), total=Sum('massug')) It's not counting correctly (it shows only one), thus it 's not summing correctly. It seems it is only getting the first result... I tried to use Count('blindid', distinct=True) and Count('blindid', distinct=False) as well. -
Django custom field with 2 fields
I found a markdown editor that I'm adapting to make it work well with Django. I would like to have a field to store the raw markdown and one for the compiled HTML for optimization purposes. I want to create a custom field and widget to hide the complexity and make it reusable everywhere on my website. In this custom field, I would like to have two textfields but I didn't find if it was possible. My other solutions are : to have a model with those two fields and my custom field is actually a foreign key to this model. I like this one because doing some migration for everything is really easy, maybe the implementation will be somewhat tricky. to create a abstract model with those two fields. I override the save method to fill the html entry -
Django conditional query by matching boolean values
I know there is a few ways this can be achieved, i.e. if/else query sets, conditional query sets, Q, aggregate etc. I have come up with a few options based on these but want to know best approach and suggestions. Sudo code is below on what I am trying to achieve. App would pass in query string for boolean values as below i.e. either True or False, if one user has more matches based on the query string values and database data they would be ordered higher than other users. SELECT * from userdetails if sun_morn is true then match_count++ if sun_day is true then match_count++ if sun_afternoon is true then match_count++ if sun_afternoon is true then match_count++ order_by match_count LIMIT by 10; Result is to show all users that match any one of the booleans then order the user with the most matches at the top of the queryset. -
TinyMCE submitting raw text with HTML tags
I'm using a TinyMCE text area in a form to create a new blog post; when I hit "Submit" I should get redirected to a new blog page with the formatted content I typed into the text area. What I actually get is raw content complete with <p>, <strong>, etc. tags. Is something not configured properly? Here is the code: TinyMCE config in my template <head>: <script src="//cdn.tinymce.com/4/tinymce.min.js"></script> <script type="text/javascript"> tinymce.init({ selector:'textarea' }); </script> Form with TinyMCE text area: <h1>New post</h1> <form method="POST" class="progresstracker-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> View with relevant code to process the new blog post: def pt_detail(request, slug): ptpost = get_object_or_404(Post, slug=slug) return render(request, 'blog/pt_detail.html', {'ptpost': ptpost}) def progresstracker(request): posts = Post.objects.order_by('published_date') return render(request, 'blog/progresstracker.html', {'posts': posts}) def progresstracker_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): ptpost = form.save(commit=False) ptpost.author = request.user ptpost.published_date = timezone.now() ptpost.save() return redirect('pt_detail', slug=ptpost.slug) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) def post_edit(request, slug): ptpost = get_object_or_404(Post, slug=slug) if request.method == "POST": form = PostForm(request.POST, instance=ptpost) if form.is_valid(): ptpost = form.save(commit=False) ptpost.author = request.user ptpost.published_date = timezone.now() ptpost.save() return redirect('pt_detail', slug=ptpost.slug) else: form = PostForm(instance=ptpost) return render(request, 'blog/post_edit.html', {'form': form}) -
Facebook comment ussing ajax/django site
I have just one troubble adding fb comments box in my site. I use kust one url and read de cont3nt of the site using js. I put in the head the init of my fb app but i have three post in the main page and i want one comment box for every post. To load the comments of my post i use ((myurl)){{post.id}} to make unique thw comment box. This url dosent exist. But show me up differwnts comment for every. But dont let me moderate.. i mean dont show the moderation tool. But if i change the href of the post to my url real. Sow me the noderstion tool but the same comments in every posts. Any idea??? -
Events not registering after replaceWith - Ajax
I send request to server to update data, and when I got response use replaceWith. Problem is with click event, they don't want update. In first load page it's all good. Update data script: widget[nr_widget]["content"] = widget_data[0].widgets; $("div[name='"+ widget[nr_widget].type+"']").replaceWith(widget[nr_widget]["content"]); _onClickEventListener(widget[nr_widget]); //Create new event for new content _onClickEventListener: var $obi = object.object; var $id = object.id; //Add field config $obi.find(".settings").on("click","button[name='cadd']", function(){ _addFieldConfig($obi); }); //Remove field config //.off('click') - doesn't work $obi.find(".settings").off('click').on("click","button[name='cremove']", function(){ _removeFieldConfig($(this).closest("tr",$(this)),$id); }); Function onClickEventListener is perform, and in console I check elements and they exist. All code: var ManagerWidget =(function(){ //Przechowuje widgety var widget = []; var _load_widget_by_id = function(id) { $.post("/AJAX/",{"rq":4,"id":id},function(data) { widget_data = JSON.parse(data); }).done(function() { //Sprawdza czy taki widget jest juz //zaladowany, jesli tak nadpisze tylko content //jesli nie doda go do managera i wyswietli for(var nr_widget=0; nr_widget<widget.length; nr_widget++) { if(widget[nr_widget]["id"] == widget_data[0].data[0].id) { widget[nr_widget]["content"] = widget_data[0].widgets; $("div[name='"+ widget[nr_widget].type+"']").replaceWith(widget[nr_widget]["content"]); _onClickEventListener(widget[nr_widget]); } else { widget.push({ //Pobrane dane "id": widget_data[0].data[0].id, "type": widget_data[0].data[0].name, "content" : widget_data[0].widgets, "object": $("div[data-id='"+widget_data[0].data[0].id+"']") }); $("#dashboard").append(widget[nr_widget]["content"]); //Dodawanie click eventu _onClickEventListener(widget[0]); } } icon_weather(); }); } /** * Funkjca load_widget wczyta widget po typie * @param type pozwala zidentyfikować widget **/ var _load_widgets = function(type) { //Zapytanie, które pobiera widget $.post("/AJAX/",{"rq":1},function(dataa){ widget_data=JSON.parse(dataa); }).done(function(){ //Dodanie widgetu do … -
Input text field do not show on browser - Django
I following a book to learn Django, but now I am stuck because I cant render the text field that I should. I am using Django version 1.9 and usually rendering on Firefox. I have these two html files: base.html and profile.html <!DOCTYPE html> {% load static from staticfiles %} <html> <head> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'js/bootstrap.min.js' %}" rel="stylesheet"> </head> <body> <nav class="navbar navbar-fixed-static navbar-default" role="navigation"> <a class="navbar-brand" href="#">MyTweets</a> <p class="navbar-text navbar-right container-fluid">User Profile Page</p> </nav> <div class="container"> {% block content %} {% endblock %} </div> <nav class="navbar navbar-default navbar-fixed-bottom" role="navigation"> <p class="navbar-text navbar-right">Footer </p> </nav> <script src="{% static 'js/bootstrap.min.js' %}"></script> </body> </html> <!DOCTYPE html> <!--esse extends significa que ele vai entrar no bloco definido no arquivo base.html--> <!-- primeiro esse profile era apenas pra mostrar os twitters, mas depopis adicionamos o campo de adicionar um novo twitter, utilizando form, que foi feito no aqquivo <forms class="py"></forms>--> {% extends "tweets/base.html" %} <!--definicao dos blocos, ou seja, tera o mesmo header, body ..., o que muda eh o content--> {% block content %} <div class="container" class="row clearfix"> <div class="col-md-12 column"> <!--Form para um novo twitter--> <form method="post" action="post/">{% csrf_token %} <div class="col-md-8 col-md-offset-2 fieldWrapper"> {{ form.text.errors … -
Append data to Hidden django form
This is a quite simple and straightforward question. I have a Django form with a specific field as: permissions_json = forms.CharField(max_length=500) In my template I use jquery to append data on this form. My question is how to append data to the same field if it is hidden as: permissions_json = forms.CharField(max_length=500, widget=forms.HiddenInput()) I dont want the field to be visible on the page but I still need to append data and fetch them later in my view function. -
How to get instance of entity in limit_choices_to (Django)?
For instance: class Foo(models.Model): bar = models.OneToOneField( 'app.Bar', limit_choices_to=Q(type=1) & Q(foo=None) | Q(foo=instance) ) class Bar(models.Model): TYPE_CHOICE = ( (0, 'hello'), (1, 'world') ) type = models.SmallIntegerField( choices=TYPE_CHOICE, default=0 ) I wanna show in Django admin only these Bars that have type = 1, that haven't relations with Foo's, and show linked Bar of edited entity (if it is). Of course, we can do it via overriding formfield_for_foreignkey method of admin.ModelAdmin, but we want do this via limit_choices_to. How to get instance of edited entity? -
how to avoid db query with django fragment cache
I wonder what is fragment cache intended for. How can it help to avoid database query. For example: {% cache cache_key param1 param2 %} ... {% endcache %} The param1 and param2 are passed from client, I need to do some query from database before rendering the template. How can I avoid querying db with the help of the cache? It only helps to accelerate the rendering phase? DB searching is much more costing that rendering, right? If the query is inevitable here, the cache is useless I think. -
Save data in associative model using one query in django
I am working on registration module in django project. for registering user i am using auth_user table for extending this table i have created one more model Profile from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) start_date = models.DateField() phone_number = models.CharField(max_length=12) address = models.CharField(max_length=225) subscription = models.BooleanField(default=False) Profile table has been created successfully. Now what i want to do is when i submit the registration form, the fields related to Profile model within registration form should be inserted automatically after inserting fields related to auth_user model. Means i don't want to first insert data in auth_user model and then after getting it's id again insert data in Profile table. I want to insert complete record in one query. Is it possible ? -
Celery - No module named 'celery.datastructures'
i am using Django 1.10 + celery==4.0.0rc3 + django-celery with commit @79d9689b62db3d54ebd0346e00287f91785f6355 . My settings are: CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE # http://docs.celeryproject.org/en/latest/getting-started/brokers/redis.html#visibility-timeout BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 259200} # 3 days my tasks.py i have @task(queue='assign_rnal_id') def assign_rnal_id_to_mongo(rnal_id, mongo_id): print ("something") return False In my django model i am overriding the save method to send a task to celery: def save(self, *args, **kwargs): super(Suggested, self).save(*args, **kwargs) assign_rnal_id_to_mongo.delay(rnal_id=self.id, mongo_id=self.raw_data['_id']) When i save my model object i get a No module named 'celery.datastructures' Any ideas?? I have similar code working for older versions of django and celery, did something change? Thanks -
How to create thumbnails for videos using django?
I am displaying my videos in my django site. I want to display those video like thumbnails, but I don't know how to create thumbnails for my videos. I have stored my videos through admin module. here is my code models.py class Video(models.Model): title = models.CharField(max_length=200, null=True, blank=True) video = models.FileField(upload_to='static/gallery/videos', null=False, help_text=_("video file") ) admin.py from django.contrib import admin from .models import Video admin.site.register(Video) Any one help me for how to store my video thumbnails format in db or how to display my retrieved videos in thumbnail format. Thanks in advance -
How to change from http to https in django project?
I have a project with all HTTP requests and responses(url). I need to convert it to HTTPS. Is there any way to achieve this in django ?