Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What should I version while doing an API versioning in Django
Currently, I am doing an API versioning for our project. We have 10 apps and 45 API endpoints. Each app has models, tasks, utils, constants, serializers, views and urls files. Now, I have created an apis app which contains version folder e.g v1, v2 etc. and each version folder contains serializers, views, utils and urls files. Now, I need to know what should I consider for versioning? should I version the tasks, utils and constants also? And how should I do versioning for models? Please guys help me to sort out this. -
django: save a model instance with a non-existent field
I don't know if this is a bug or Django just allows it to happen. I have a Django model: class Author(models.Model): name = models.CharField(max_length=128) I create an instance of it and assign a value to a non-existent field address: author = Author() author.name = 'abce' author.address = 'defg' author.save() The instance is saved successfully and there is no error messages. Is this normal? -
Djago URL conf error
I have the following message when I try to use reverse or reverse_lazy: The included URLconf 'ph.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import When I use the urls (without using reverse or reverse lazy) is working with no issue. I tried different combination of urls the same results What I'm doing wrong ? ph is the project. In the project I include the urls for the application: url(r'^account/', include('accounts.urls', namespace='accounts')), url(r'^companies/', include('companies.urls', namespace='companies')), url(r'^products/', include('products.urls', namespace='products')), url(r'^admin/', admin.site.urls) The app involved: 1)accounts: from django.conf.urls import url from .views import AccountDetailView urlpatterns = [ url(r'$', AccountDetailView.as_view(), name='dashboard'), 2) products: class ProductCreateView(AccountMixin, CreateView): model = Product form_class = ProductModelForm url = reverse_lazy('accounts:dashboard') url2 = reverse_lazy('products:list') #print(url) template_name = 'accounts/product_form.html' #success_url = reverse_lazy('accounts:product_detail') -
Accessing Django MEDIA_URL and MEDIA_ROOT setting.py values from ReactJS frontend
I have a Django web application and am using ReactJS for my frontend. My application wants to retrieve local music files when I'm developing locally (folder containing my music files) and also on production (file system on server) I set MEDIA_ROOT = os.path.join(BASE_DIR, 'music') MEDIA_URL = '/media/' where "music" is my folder containing the files. I added urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urls.py but when ReactJs is rendering the component it's treating that variable as just a string and not getting the value that I set <audio src={"{{ MEDIA_ROOT }}" + props.audio}></audio> where props.audio is the path to the file. I also added django.core.context_processors.media to the TEMPLATES in my settings.py but it still doesn't work Any ideas? -
How to show events in Python calendar using Django?
I am trying to show the attendance of a student. This is the model that I have. class Attendance(Timestamped): date = models.DateField(auto_now_add=True) student = models.ForeignKey(User) def __str__(self): return "%s - %s" % (str(self.date), self.student) class Meta: unique_together = ['student', 'date'] If a student is absent, an object with the date and student is not created, if he is present then it is created. I am trying to create a year calendar and turn the date green if he was present and red if he was absent. I am aware of HTMLCalendar module from Python but I have no clue how to loop through the attendance queryset and integrate it into that module to show the result. How can I do this? -
Migrating session data from custom backend to cache backend (Django)
I'm currently running a Django application with SESSION_ENGINE configured as user_sessions.backends.db (I'm using this external library). Django's own built-in sessions are great, however all the data is hidden away into base64 encoded data. This library makes session objects accessible like other ORM objects. I need to remove my dependency on this library; changing the SESSION ENGINE to cache to boost performance. My challenge is making this change without destroying the current session data, and that's what this question is about. Given its nature, the library naturally doesn't include a backend other than db, so I'll have to extend it. How should I approach this problem? E.g., in my head: i) I ought to look at the contents of the db table(s) this library saves session data to, ii) write functionality that saves this data to cache memory at each write, iii) shift over to reading from cache (with db as a fall-back). Does that sound about right? Would love to know any dont's at this point in time, since this is a rather complex task. Thanks in advance. -
How can I switch django-tables2 template to bootstrap?
How can I switch django-tables2 template to bootstrap? I did not saw this in documentation. -
How hide delete item in django admin TabularInline
I have admin view with tabular inline: class AddressInline(admin.TabularInline): model = Address can_delete = False readonly_fields = ['kind'] max_num = 3 min_num = 3 fields = ( "kind", "country", "city", "post_code", "street", "no_house" ) def has_delete_permission(self, request, obj=None): return False class CustomerAdmin(admin.ModelAdmin): fields = ( "first_name", "last_name", "pesel", "id_number", "birth_date", "photo" ) inlines = [AddressInline] I want form with three other inline form. This inline form always will be tree. I hide add another button. I don't want delete inline item button in form. How can I delete or hide this button? This button can't be show to user. -
Django: order_by working fine in sqlite but on postgres
I have a model with replies and in template the replies with highest upvote should come first. In my local machine its coming correctly however on server replies are filtered based on FK of upvote field. Model: class solution(models.Model): doubt=models.ForeignKey(doubts,related_name='answers') reply=models.TextField() snapshot = models.FileField(upload_to='support',null=True,blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user=models.ForeignKey(settings.AUTH_USER_MODEL,null=True,blank=True) upvote = models.ManyToManyField(User,related_name='upvoteuser') @property def total_upvotes(self): return self.upvote.count() def __str__(self): return str(self.doubt) view def ticketdetails(request,slug,pk): ticketis=doubts.objects.get(pk=pk) replies = ticketis.answers.all().order_by('-upvote') if request.method== 'POST': form=replyform(request.POST) if form.is_valid(): new_form=form.save(commit=False) new_form.user=request.user new_form.doubt=ticketis new_form.save() form=replyform() return HttpResponseRedirect(reverse('ticketdetail',kwargs={'slug':ticketis.slug,'pk':ticketis.id}),messages.add_message(request, messages.SUCCESS,'Response submitted succesfully.')) else: form=replyform() return render(request,'ticketview.html',{'ticketis':ticketis,'replies':replies,'form':form}) -
unable to sync database in python(django)
I am unable to migrate my code. I created a database and a table in mysql but i had to uninstall mysql for some reason and when i installed it again, i changed the user name to root. and now it keeps saying `(1045, **"Access denied for user 'djanu'@'localhost' (using password: NO)"**)' when i try to migrate. I named my user as djanu when i first installed it and i tried granting privileges to user root but the same message keeps popping up. this is my code in settings.py **DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'applics', 'USER': 'root', 'Password': '531010', 'HOST': '', 'PORT': '', } }** and my code when i use python manage.py migrate or even runserver (myproject) C:\Users\home\myproject\collapp>python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\home\myproject\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\home\myproject\lib\site-packages\django\core\management__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\home\myproject\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\home\myproject\lib\site-packages\django\core\management\base.py", line 342, in execute self.check() File "C:\Users\home\myproject\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\home\myproject\lib\site-packages\django\core\management\commands\migrate.py", line 61, in _run_checks issues = run_checks(tags=[Tags.database]) File "C:\Users\home\myproject\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\home\myproject\lib\site-packages\django\core\checks\database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "C:\Users\home\myproject\lib\site-packages\django\db\backends\mysql\validation.py", line 9, … -
Specify initial choice for a form `ModelChoiceField`
I cannot figure out how to specify initial choice for ModelChoiceField. Is there any caveat that I am missing? class QuizUserForm(forms.Form): question = forms.CharField() eq_answer = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super(QuizUserForm, self).__init__(*args, **kwargs) self.fields['mcq_answer_choice'] = forms.ModelChoiceField(queryset=models.MCQChoice.objects.filter( question__prompt=kwargs['initial']['question']), initial=1, widget=forms.RadioSelect, empty_label=None) -
Django not sending JSON response through nginx, instead sends HTML
I set up an API with Django through nginx and I'm trying to hit an endpoint with a Node app but the response that I receive is basically the index.html file instead of JSON. Here's my .conf in sites-available (fake_watson is the api and chat is the node app): server { listen 80; server_name 10.39.40.107; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/fake_watson_frontend/build; } location /fake_watson/ { include proxy_params; proxy_pass http://unix:/home/ubuntu/fake_watson_backend/fake_watson_backend.sock; charset_types application/json; default_type application/json; add_header content_type application/json; proxy_set_header content_type application/json; } location /chat/ { proxy_pass http://localhost:9000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } My code in Django looks like this (probabilities is a dict): import json from .models import Input, Classification from .classifier import Classifier from django.http import JsonResponse # Create your views here. def predict(request, input): probabilities = Classifier.predict(input) return JsonResponse(probabilities) Through my axios call, response.data looks like this: Lastly, application/json is included in my mimetypes. If it helps, my content-type headers are still "text/html; charset=UTF-8". I've been looking all over for a straightforward answer but I haven't seemed to find anything - any help is greatly appreciated! -
Python Django Celery is taking too much memory
I am running a celery server which have 5,6 task to run periodically. Celery is taking too much memory after 5,6 days of continuous execution. Celery documentation is very confusing. I am using following settings. # celeryconfig.py import os os.environ['DJANGO_SETTINGS_MODULE'] = 'xxx.settings' # default RabbitMQ broker BROKER_URL = "amqp://guest:guest@localhost:5672//" from celery.schedules import crontab # default RabbitMQ backend CELERY_RESULT_BACKEND = None #4 CONCURRENT proccesess are running. CELERYD_CONCURRENCY = 4 # specify location of log files CELERYD_LOG_FILE="/var/log/celery/celery.log" CELERY_ALWAYS_EAGER = True CELERY_IMPORTS = ( 'xxx.celerydir.cron_tasks.deprov_cron_script', ) CELERYBEAT_SCHEDULE = { 'deprov_cron_script': { 'task': 'xxx.celerydir.cron_tasks.deprov_cron_script.check_deprovision_vms', 'schedule': crontab(minute=0, hour=17), 'args': '' } } I am running celery service using nohup command(this will run this in background). nohup celery beat -A xxx.celerydir & -
Error reading webpack-stats.json
I know this is probably a long shot but I have been desperately attempting to launch a Django application from the Animal Disease Spread Model simulator located here: https://github.com/NAVADMC/ADSM. I have made a docker file to try to replicate the environment and I have even pushed the image to docker hub. docker run --name adsm-app -p 8000:8000 -d mgahan/adsm:latest open http://0.0.0.0:8000 I get the following error when I navigate to http://0.0.0.0:8000: Any tips to what might be going wrong and possible fixes? Here is the Dockerfile: FROM python:3.4 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app ADD ADSM ADSM RUN pip install -r ./ADSM/Requirements-Nix.txt RUN pip install -r ./ADSM/Requirements.txt WORKDIR /usr/src/app/ADSM # Install node # gpg keys listed at https://github.com/nodejs/node RUN set -ex \ && for key in \ 9554F04D7259F04124DE6B476D5A82AC7E37093B \ 94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \ 0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93 \ FD3A5288F042B6850C66B31F09FE44734EB7990E \ 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \ DD8F2338BAE7501E3DD5AC78C273792F7D83545D \ B9AE9905FFD7803F25714661B63B535A4C206CA9 \ C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \ ; do \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \ done ENV NPM_CONFIG_LOGLEVEL info ENV NODE_VERSION 7.0.0 RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz" \ && curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \ && gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \ && grep " node-v$NODE_VERSION-linux-x64.tar.xz\$" SHASUMS256.txt | sha256sum -c - \ && … -
Override Meta in ModelForm
If I have: class MCQuestionForm(forms.ModelForm): class Meta: model = models.MultipleChoiceQuestion fields = ('prompt',) Can I override class Meta to change model to some other model? For instance: class Meta: model = models.EssayQuestion -
Changing Django session engine without destroying existing sessions
I'm currently running a Django application with SESSION_ENGINE configured as django.contrib.sessions.backends.db. I'd like to change this to django.contrib.sessions.backends.cached_db for a performance boost. Can I make this change without destroying the existing sessions? -
Add class to button of FileField form in Django
I want to change the css of a button of FileField form adding a class of Materializecss: I tried using jQuery with this code: $(":input").addClass("btn"); But it doesnt add the style to the button, it does for the whole input (logic): So how can I access to the button? Is there any way to add the class="btn" in the form model of Django? Form code: class DocumentForm(forms.Form): docfile = forms.FileField(label="Select a file") captcha = CaptchaField() -
Django: sorl-thumbnail doesn't work at production mode(DEBUG=False) in local machine(Mac OS)
I used sorl-thumbnail for creating thumbnail image in my django project. Before I deploy my django application in real AWS server, I ran it in my local machine(Mac OS) When run in development mode(DEBUG = True in settings.py), it works perfectly. Thumbnail image loads well in any pages. When I changed to production mode(DEBUG = False in settings.py), it doesn't work at all! All thumbnail images were not loaded, not even one! It shows error in terminal like this: [30/Nov/2016 13:13:14] "GET /media/cache/37/91/37915dc65a819027b65457f40c25580b.jpg HTTP/1.1" 404 128 When I accessed this image through url directly(http://localhost:8000/media/cache/37/91/37915dc65a819027b65457f40c25580b.jpg), it shows Not Found error. But thumbnail file(37915dc65a819027b65457f40c25580b.jpg) is located in MY_COLLECTSTATIC_FOLDER/media/cache/37/91/. I have no idea why page can not load this cached thumbnail image file. -
Custom method to provide default date for Django date field
I want the default date for my model to be "next Wednesday". I can calculate the proper date (thanks to this question) class Event(models.Model): @staticmethod def default_event_date(): today = date.today() # Wednesday = 3 wednesday = today + datetime.timedelta((3-today.weekday()) % 7) return wednesday title = models.CharField(max_length=120) date = models.DateField(default=default_event_date) However, the resulting "date" from this is the method object <staticmethod object at 0x7ff2eca66630> How do I get it to call the method when new objects are created, similar to how one would use default = date.today or default = timezone.now? -
Why can't these three kinds of Fields in Django be migrated to database successfully?
These Fields including UUIDField, BigIntegerField, FloatField, DateTimeField? I have tested Mysql with innoDB and sqlite. There is no error or warning info, the fields just can not be written into the migration scripts. -
How to load local static files if CDN fails? (django)
I am using django to develop my site and I am trying to optimize my site for speed so I want to use CDN for my bootstrap and if it fails than i want to use the copy from my server, I have seen How to load local files if CDN is not working but it does it in javascript but it doesn't solve my problem, I want to know how to check if CDN working with Django and if not serve the static files from server? -
Redirecting to a different page after post ajax call made to django view
I have been trying to get this simple piece of code working fine, but still am not able to. Have gone through multiple other links. Am not able to figure out what is that I doing wrong. I have a javascript function submitData() which just has to make an ajax post call to a django view. The django view basically just has to check if the request is a post, if it is, it has to redirect to another page. My javascript function submitData() is as below and have also added the part of code which takes care of sending the csrf token along with the post request. function submitData() { $.post('/loggedin/',{"fname":"name1","lname":"name2"},function(data){ alert("Back from views.py"); }); } $(function () { $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); }); function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) c_end = document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } In my views.py, I have the following code, def loggedin(request): if request.method == "POST": fname = request.POST.get('fname') print fname #The code comes here, prints the fname args = {} … -
Celery could not start worker processes when using scrapy-Djangoitem
Question detail: https://github.com/celery/celery/issues/3598 I want to run a scrapy spider with celery, which contain Djangoitems. this is my celery task: # coding_task.py import sys from celery import Celery from collector.collector.crawl_agent import crawl app = Celery('coding.net', backend='redis', broker='redis://localhost:6379/0') app.config_from_object('celery_config') @app.task def period_task(): crawl() collector.collector.crawl_agent.crawl contains a scrapy crawler who uses djangoitem as item. the item like: import django os.environ['DJANGO_SETTINGS_MODULE'] = 'RaPo3.settings' django.setup() from scrapy_djangoitem import DjangoItem from xxx.models import Collection class CodingItem(DjangoItem): django_model = Collection amount = scrapy.Field(default=0) role = scrapy.Field() type = scrapy.Field() duration = scrapy.Field() detail = scrapy.Field() extra = scrapy.Field() when run: celery -A coding_task worker --loglevel=info --concurrency=1, it wil get some errors below: [2016-11-16 17:33:41,934: ERROR/Worker-1] Process Worker-1 Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/billiard/process.py", line 292, in _bootstrap self.run() File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 292, in run self.after_fork() File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 395, in after_fork self.initializer(*self.initargs) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/prefork.py", line 80, in process_initializer signals.worker_process_init.send(sender=None) File "/usr/local/lib/python2.7/site-packages/celery/utils/dispatch/signal.py", line 151, in send response = receiver(signal=self, sender=sender, **named) File "/usr/local/lib/python2.7/site-packages/celery/fixups/django.py", line 152, in on_worker_process_init self._close_database() File "/usr/local/lib/python2.7/site-packages/celery/fixups/django.py", line 181, in _close_database funs = [self._db.close_connection] # pre multidb AttributeError: 'module' object has no attribute 'close_connection' [2016-11-16 17:33:41,942: INFO/MainProcess] Connected to redis://localhost:6379/0 [2016-11-16 17:33:41,957: INFO/MainProcess] mingle: searching for neighbors [2016-11-16 17:33:42,962: INFO/MainProcess] mingle: all alone … -
updating multiple databases in one view
I'm writing a django-rest-framework backend with rest-framework-mongoengine. So far I have schemas for 2 types - for User and for Device(Box). Sources as follows: models.py: from __future__ import unicode_literals import datetime from mongoengine import Document, connect, EmbeddedDocument, fields, DynamicDocument from django.db import models # Create your models here. from mongoengine import signals connect('yourdb', alias='default') class GPS(EmbeddedDocument): lat = fields.FloatField(null=False, required=True) lon = fields.FloatField(null=False, required=True) class PPM(EmbeddedDocument): time = fields.DateTimeField(default=datetime.datetime.now()) value = fields.IntField(null=False, required=True) @classmethod def pre_save(cls, sender, document, **kwargs): document.time = datetime.datetime.now() signals.pre_save.connect(PPM.pre_save, sender=PPM) class BuyHistory(EmbeddedDocument): time = fields.DateTimeField(default=datetime.datetime.now()) boxid = fields.StringField(max_length=128, null=False, required=True) username = fields.StringField(max_length=128, null=False, required=True) product = fields.StringField(max_length=128, null=False, required=True) amount = fields.IntField() @classmethod def pre_save(cls, sender, document, **kwargs): document.time = datetime.datetime.now() signals.pre_save.connect(BuyHistory.pre_save, sender=BuyHistory) class RecycleHistory(EmbeddedDocument): time = fields.DateTimeField(default=datetime.datetime.now()) boxid = fields.StringField(max_length=128, null=False, required=True) username = fields.StringField(max_length=128, null=False, required=True) amount = fields.IntField() @classmethod def pre_save(cls, sender, document, **kwargs): document.time = datetime.datetime.now() signals.pre_save.connect(RecycleHistory.pre_save, sender=RecycleHistory) class Box(Document): boxid = fields.StringField(max_length=128, null=False, required=True) gps = fields.EmbeddedDocumentField(GPS, required=True) buy_history = fields.EmbeddedDocumentListField(BuyHistory, default='[]') recycle_history = fields.EmbeddedDocumentListField(RecycleHistory, default='[]') ppm_history = fields.EmbeddedDocumentListField(PPM, default='[]') class User(Document): username = fields.StringField(max_length=128, null=False, required=True) rfid = fields.StringField(max_length=32, null=False, required=True) buy_history = fields.EmbeddedDocumentListField(BuyHistory) recycle_history = fields.EmbeddedDocumentListField(RecycleHistory) serializers.py: from rest_framework_mongoengine import serializers from models import User, BuyHistory, Box, RecycleHistory, … -
Efficient serialization/deserialization of nested models with django rest framework
I have a django model that can be nested recursively: models.py from django.db import models class Node(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey('Node', related_name='children', null=True) Nested models commonly have ~100 nodes in my application. I am using django rest framework for serialization/deserialization: serializers.py from rest_framework import serializers from .models import Node from django.db import models class NodeSerializer(serializers.ModelSerializer): # Recursive serializers not supported, so use a blank one children = serializers.Serializer(many=True, required=False) class Meta: model = Node fields = ('name', 'children') def create(self, validated_data): # Remove nested objects to handle separately children = validated_data.pop('children', []) node = Node.objects.create( # parent is null only on the root node parent=self.context.get('parent'), **validated_data) for child_data in children: s = NodeSerializer(data=child_data context={'parent': node}) s.is_valid(raise_exception=True) s.save() return node def to_representation(self, instance): if not isinstance(instance, models.Model): # If the Serializer was instantiated with data instead of a model, # "instance" is an OrderedDict. return instance else: # This renders simple fields representation = super(NodeSerializer, self)\ .to_representation(instance) # Then recursively render nested models representation['children'] = [NodeSerializer(child).data for child in instance.children.all()] return representation def validate(self, data): # serializers.Serializer couldn't validate children, # so we validate here children = self.initial_data.get('children') if children: self._validate_children(children) data.update({'children': children}) return data def _validate_children(self, value): # …