Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Linking a django docker container to a mysql docker container
As I am fairly new to this, I read a decent amount on the Internet before I started and I think I did everything as it was said in the tutorials, however, my django application does not want to use the mysql container. From what I have read, in the settings.py file I have to add the following code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'TheDatabase', 'USER': 'TheUsername', 'PASSWORD': 'ThePassword', 'HOST': 'mysql', 'PORT': '3306', } } I am using a docker-compose.yml to link both docker containers and my docker-compose.yml looks as follow: version: '2' services: mysql: image: mysql:latest environment: -MYSQL_DATABASE: TheDatabase -MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' -MYSQL_USER: TheUsername -MYSQL_PASSWORD: ThePassword django: build: . volumes: - .:/app ports: - "443:443" - "8000:8000" links: - mysql The reason why I think the problem is in the connection between the 2 containers is, because when i visit https://127.0.0.1/ I get 0 issues, however, as soon as I try to log in as the superuser, I get the error message 504 Timed-out, so I assume the issue must be in the database. In the Dockerfile of the Django app I install only Mysql-Python and libmysqlclient-dev, should I install anything else in the container of the … -
Is it possible to use reuse django form in django rest framework serializer for validation?
Is it possible to reuse existing forms written as django forms in django rest framework serializers validation? I would like to keep the logic of the forms and don't spend a lot of time for doing rewrites. If it's possible - what's the best way to do that? -
Add blockquote to djangocms-text-ckeditor
Does anybody know how to add the HTML element blockquote to djangocms-text-ckeditor? I'm pretty sure that this is supported, as when I add the html: <blockquote>Text goes here...</blockquote> Directly to the source panel, it is formatted and displays nicely: I've tried adding as a custom style in the settings as follows: CKEDITOR_SETTINGS = { 'stylesSet': [ {'name': 'PullQuote', 'element': 'blockquote', 'styles': {'color': 'Blue'}} ], } But that doesn't work. I know the syntax is correct, as when I change the element to "h1" it works fine. Any help would be much appreciated. -
Django exists() versues DoesNotExist
I have one question about django exists() and DoesNotExist. Example code: id = 1 # first if User.objects.get(pk=id).exists(): # my logic pass # second try: User.objects.get(pk=id) # my logic pass except User.DoesNotExist: return 0 I often user get() method, which practise is better ? which code is better ? first or second ? sorry for bad english. -
How i can get items from a model that are not used in ManyToMany relationship?
I’ve got a Django model (ModelA) with a ManyToManyField linking to another model (ModelB) like this: class ModelA (models.Model): field = models.ManyToManyField('ModelB',blank=True ) class ModelB (models.Model): .... so my question is how i can get all elements form ModelB that are not be used in ManyToManyField relationship -
Adding metadata for models and objects in django
I am writing a Django based app where I have a model that encapsulates various image types. I load them as fixtures as follows: [ { "model": "app.ImageTypeModel", "pk": 1, "fields": { "type": "PNG", "dims": 1 } }, { "model": "app.ImageTypeModel", "pk": 2, "fields": { "type": "Custom", "dims": 100 } }, { "model": "app.ImageTypeModel", "pk": 3, "fields": { "type": "JPEG", "dims": 1 } }, { "model": "app.ImageTypeModel", "pk": 4, "fields": { "type": "BMP", "dims": 1 } } ] The corresponding model declaration is as follows: class ImageTypeModel(models.Model): type = models.CharField(max_length=100) dims = models.IntegerField() class Meta: db_table = "image_type" Additionally, I have various instances of images as follows (I have removed some fields for simplification): class ImageModel(models.Model): type = models.ForeignKey(ImageTypeModel) class Meta: db_table = "images" Now for each of these image types, I have different properties which I would like to specify. For example, for an image of type Custom, I could have various properties each of which could be a specific data type (like integers, string, floats, vectors of floats etc.). One way to define this would be to have a table for these data types and additional tables for each of the image types (let us call these tables … -
Memory leak with Django + Django Rest Framework + mod_wsgi
I have the following code where I have a function based view which uses a ModelSerializer to serialize data. I am running this with apache + mod_wsgi (with 1 worker thread, 1 child threads and 1 mod_wsgi threads for the sake of simplicity). With this, my memory usage shoots up significantly (200M - 1G based on how large the query is) and stays there and does not come down even on request completion. On subsequent requests to the same view/url, the memory increases slightly everytime but does not take a significant jump. To rule out issues with django-filter, I have modified my view and have written filtering query myself. The usual suspect that DEBUG=True is ruled out as I am not running in DEBUG mode. I have even tried to use guppy to see what is happening but I was unable to get far with guppy. Could someone please help why the memory usage is not down after the request is completed and how to go about debugging it? class MeterData(models.Model): meter = models.ForeignKey(Meter) datetime = models.DateTimeField() # Active Power Total w_total = models.DecimalField(max_digits=13, decimal_places=2, null=True) ... class MeterDataSerializer(serializers.ModelSerializer): class Meta: model = MeterData exclude = ('meter', ) @api_view(['GET', ]) … -
How can I update a field in a queryset with a count atomically in django?
I am trying to update a field of a queryset atomically. I have something like this: counter = 0 for row in myQuerySet: row.myField = counter counter = counter + 1 row.save() That works, but I want to do this atomically, because I have hundreds of registers and it is a waste of time. I need something like this: counter = 0 myQuerySet.update(myField=(counter+=1)) But that does not work. What am I doing wrong? -
How many web workers does a default Django app has?
How many web workers does a default Django app has? How do you configure web workers in Django and how does they work under the hood? -
Django model isn't persisting data to DB on real-time
I'm using Django Python framework, and MySQL DBMS. In the screenshot below, I'm creating the new_survey_draft object using the SurveyDraft.objects.create() as shown, assuming that it should create a new row in the surveydraft DB table, but as also shown in the screenshot, and after debugging my code, the new_survey_draft object was created with id=pk=270 , while the DB table shown in the other window to the right doesn't have the new row with the id=270. Even when setting a break point in the publish_survey_draft() called after the object instantiation, I called the SurveyDraft.objects.get(pk=270) which returned the object, but still there is not id=270 in the DB table. And finally, after resuming the code and returning from all definitions, the row was successfully added to the DB table with the id=270. I'm wondering what's happening behind the seen, and is it possible that Django stores data in objects without persisting to DB on real-time, and only persists the data all together on some later execution point? I've been stuck in this for hours and couldn't find anything helpful online, so I really appreciate any advice regarding the issue. -
How to compare two datetime by day in Django?
from django.utils import timezone good = Goods.objects.get(id=num) now = timezone.now() print(good.create_time) print(now) How to compare these whether they are by one day. 2016-12-01 10:21:32.746505+00:00 2016-12-01 10:24:08.906268+00:00 -
Django display name of foreign key instead of foreign key id
How do I display the name of a foreign key from a query? class Books (models.Models) category = models.ForeignKey(Category) user = models.ForeignKey(User) amount = models.DecimalField(max_digits=15, decimal_places=2) class Category models.Models) name = models.CharField(max_length=30) def list_books_totalamount_by_category(request): context = Books.objects.filter(user=4).values('category').annotate(amount2=Sum('amount') return render(request, 'test.html', {'context':context} How do I make the query display the category name instead of the category_id? Thank you -
Django:Can not load app config (Apps aren't loaded yet)
I am following a tutorial using python 3.5 and Django 1.10 to making a backend, but there is a problem I can not solve. This error also occurs in the author's code downloading from github. I have been spending a day in this question, thank you for your time. <error> Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/Charles/djangop1/urban_tastes/services/apps.py", line 2, in <module> from django.contrib.auth.models import User File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import … -
nginx alias not working for static files folder
I don't know why nginx alias is not working. Why this line doesn't work: location /static/ { alias /home/django11/example.com/finansuinfo/static_root/; } Actually maybe it is working but my admin page static files isn't served. I get error that static/admin/... doesn't exist. I guess it only serves files in static folder but not in static_root folder where all files are collected by manage.py collectstatic Here is my config: server { listen 80; server_name example.com www.example.com; root /home/django11/example.com/example; location / { include uwsgi_params; uwsgi_pass unix:/home/django11/example.com/example/example.sock; } location /static/ { alias /home/django11/example.com/example/static_root/; } # Media: images, icons, video, audio, HTC location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { expires 1M; access_log off; add_header Cache-Control "public"; } # CSS and Javascript location ~* \.(?:css|js|woff)$ { expires 1M; access_log off; add_header Cache-Control "public"; } } -
GCM return 'error': 'NotRegistered' for chrome(push notification) while i did not unsubscribe.please help me
{'failure': 5, 'canonical_ids': 0, 'success': 5, 'multicast_id': 5312901805636923901, 'results': [{'message_id': '0:1480575840991592%0a6d3c0af9fd7ecd'}, {'error': 'NotRegistered'}, {'error': 'NotRegistered'}, {'message_id': '0:1480575840992852%e6968224f9fd7ecd'}, {'error': 'NotRegistered'}, {'message_id': '0:1480575840992130%e8ee8671f9fd7ecd'}, {'message_id': '0:1480575840991594%0e35204cf9fd7ecd'}, {'error': 'NotRegistered'}, {'error': 'NotRegistered'}, {'message_id': '0:1480575840993735%b1274360f9fd7ecd'}]} It is come when we unsubscribe any website but i did not unsubscribe.please tell me what is reason??? -
Cannot find all files in requirements.txt
I've a requirements.txt file I'm trying to install using pip install -r requirements.txt. There are 4 rows it does not install, namely: -e git+http://repo/repo/django-newsletter.git@443f23025471eb605b23d3bd36dc12447bb463a0#egg=newsletter-dev -e git+http://repo/repo/django-richtext.git@d2ce2184b743efe1ef3195e3ae298944a107bcaa#egg=richtext-master -e git+http://repo/repo/django-subscribers.git@e45da03e73ae7fce34bf89025b214e11252ef553#egg=subscribers-master -e git+http://repo.queo.pt/repo/django-bounce_checker.git@ca10c94aa3b9c38348ce330ab9e7116929fa56df#egg=bounce_checker-dev I've never really bothered to look at a requirements.txt file before but these appear to be git calls rather than a typical install. Is there something else I should be doing? Also, I can find two of these (I believe) on git, namely django-newsletter and django-subscribers but not the other two. Any ideas what they might be? Any help most gratefully accepted. -
Django display a model property in admin as a TextField
I have a model (Candidate) with a property (key) which return a big string. I register this model in admin.py and add the field with: class CandidateAdmin(admin.ModelAdmin): readonly_fields = ['key'] But the field is displayed as a CharField. How to show it in a TextField widget ? -
django server http header connection keep alive
current Header: HTTP/1.0 200 OK Date: Thu, 01 Dec 2016 08:33:29 GMT Server: WSGIServer/0.1 Python/2.7.12 X-Frame-Options: SAMEORIGIN Content-Type: text/xml I want to add keep-alive in the http header. Can anybody help? -
Django Deployment on windows
I am learning python and Django now. I have a question related to deploying Django project on windows 7. I know how to start the test server in django and see the project. But I have to do start the server manually every time I restart the PC. Also I have to keep the terminal window open. Consider the below scenario for php projects. We copy and paste the php files in htdocs or www folder in apache server and access them using the respected url. Web Server is running in the background. We dont have to start the server on windows restart. Is something similar possible with Django on apache or any other server? If yes, how should I go about it? Thanks in advance. -
Select or deselect an object by draging it into an space. Django and Javascript jQuery
I am using Django as a backend and forms. I want to drag an item from a list to a div and then save the form so the item I dragged is saved as "selected". It is fine if it has a boolean named "selected" in the model definition. -
Django model method is not working in template
I am calling django model method, which returns either true or false. The value is returned in views.py , but when I return serialized Response with answers_to_questions_objects to template via AJAX and look over JSON structure in JS, there is nothing like liked_by_user attribute, despite print( Question.liked_by_user(one,request.user)) returns value correctly in views.py. I supposed maybe I need to create a property to get attribute of method in template, but it doesn't help. answers_to_questions_objects = Question.objects.filter(whom=request.user.profile).filter(answered=True).order_by('-answered_date') for one in answers_to_questions_objects: Question.liked_by_user(one,request.user) -
Django: OperationalError when I try to create user from admin
I have Django 1.10 with MySQL, every time I enter admin and I try to make a user I get this error: The thing is I can create any other model and if I create a super user from command line I can edit that user but when I press "add user" I get this error. I tried deleting the database and making it again twice. -
'unicode' object has no attribute '_meta' with Django
I spent all the day and this night in order to solve this error : AttributeError at /Identity/formulaire_edit 'unicode' object has no attribute '_meta' Request Method: GET Request URL: http://localhost:8000/Identity/formulaire_edit?csrfmiddlewaretoken=DvKCCaaAYsiWykEtYHrpgNu4AKlXS16DttEc5csQOT9BtQs4Ll4AviLDhi3MaBId&q4=2 Django Version: 1.10 Exception Type: AttributeError Exception Value: 'unicode' object has no attribute '_meta' Exception Location: /Library/Python/2.7/site-packages/django/forms/models.py in model_to_dict, line 82 Python Executable: /usr/bin/python Python Version: 2.7.10 Python Path: ['/Users/valentinjungbluth/Desktop/Django/Etat_civil', '/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages'] Server time: jeu, 1 Déc 2016 07:48:15 +0000 Traceback Switch to copy-and-paste view /Library/Python/2.7/site-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /Library/Python/2.7/site-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /Library/Python/2.7/site-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /Users/valentinjungbluth/Desktop/Django/Etat_civil/Identity/views.py in Identity_Update form = IdentityForm(request.POST or None, instance = query_update) I cannot use my function and I think that's because the attempt value should be a raw integer, but I need to put this variable which is an integer. It's the value returned by user : # views.py def Identity_Update(request) : query_update = request.GET.get('q4') print query_update if query_update : query_update_list = Identity.objects.filter(pk=query_update) #Identity.objects.only('id').filter(pk=query_update) to get only the ID number print query_update_list else : query_update_list = Identity.objects.none() # == [] form = … -
Create Parent Class object from child class's ModelForm
I have a Model 'Appointment'. In that class patient is associated with built-in User model.I have made a modelform for that class. Is it possible to instantiate an object of another class (User in field patient) from inside the same form. I am not able to access User Model's field in the form. How can this be done ? class Appointment(models.Model): doctor = models.ForeignKey(Doctor) clinic = models.ForeignKey(Clinic, null=True, blank=True) hospital = models.ForeignKey(Hospital, null=True, blank=True) day = models.DateField() time = models.TimeField() patient = models.ForeignKey(User) I have created a ModelForm for this model as below: class HospitalCreateAppointmentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(HospitalCreateAppointmentForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) class Meta: model = Appointment fields = ['doctor','hospital','day','time','patient'] widgets = { 'day': forms.SelectDateWidget(), } -
django.db.utils.ProgrammingError: column am.amcanorder does not exist
I am using PostgreSQL as my database and using django tenant schemas. But when I run the following command python manage.py migrate_schemas --shared I get the error saying (checkpoint_env) G:\Django_Projects\RackNole\checkpoint_shashi_2\checkpoint_shas hi_2>python manage.py migrate_schemas --shared System check identified some issues: WARNINGS: checkpoint.MultiSelectResponse.response: (fields.W340) null has no effect on Man yToManyField. === Running migrate for schema public System check identified some issues: WARNINGS: checkpoint.MultiSelectResponse.response: (fields.W340) null has no effect on Man yToManyField. Operations to perform: Apply all migrations: website, checkpoint, account, django_comments, redirects , core, admin, twitter, galleries, tastypie, customers, auth, sites, blog, gener ic, contenttypes, sessions, conf, forms, pages, socialaccount Running migrations: Rendering model states... DONE Applying core.0002_auto_20150414_2140...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\core\managem ent\__init__.py", line 350, in execute_from_command_line utility.execute() File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\core\managem ent\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\core\managem ent\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\core\managem ent\base.py", line 399, in execute output = self.handle(*args, **options) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\tenant_schemas\mana gement\commands\migrate_schemas.py", line 42, in handle self.run_migrations(self.schema_name, settings.SHARED_APPS) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\tenant_schemas\mana gement\commands\migrate_schemas.py", line 65, in run_migrations command.execute(*self.args, **self.options) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\core\managem ent\base.py", line 399, in execute output = self.handle(*args, **options) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\core\managem ent\commands\migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "G:\Py_Envs\Racknole\checkpoint_env\lib\site-packages\django\db\migration s\executor.py", line 92, in …