Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to handle manytomany field with scrapy
I want to use scrapy with django. My goal is link actors field to name field but I don't know how to deal with django manytomany. My database is Mysql(I'm not using djangoItem) Please guide me. Thank you. models.py class Movies(models.Model): content_ID = models.CharField(max_length=30) release_date = models.CharField(max_length=30) running_time = models.CharField(max_length=10) actors = models.CharField(max_length=300) series = models.CharField(max_length=30) director = models.CharField(max_length=30) label = models.CharField(max_length=30) image_urls = models.CharField(max_length=200, null=True) images = models.TextField(null=True) image_paths = models.TextField(null=True) def __str__(self): return self.content_ID class Actors(models.Model): name = models.CharField(max_length=100, null=True) movielist = models.ManyToManyField(EnMovielist) image_urls = models.CharField(max_length=200) images = models.TextField(null=True) image_paths = models.TextField(null=True) def __str__(self): return self.name -
Django Settings for Rendering static images from Google Cloud storage
I have my Django App hosted on Google Compute Engine. I wish to render static elements of the App from Google Cloud Storage. I have all the static elements inside Google Cloud storage bucket www.example.com/static My Settings.py: # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '../example_static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '../example_media') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), MEDIA_ROOT,) 000-default.conf File: <VirtualHost *:80> ..... DocumentRoot /var/www/html Alias /static /opt/projects/example-google/example_static .... </VirtualHost> With Current settings, it is picking up the static files from path: /opt/projects/example-google/example_static. Can someone please explain the settings change required for rendering all the static images from Google Cloud storage bucket www.example.com/static ? Thanks, -
can't print the value of json object in django
I have this json object in ajax_data variable { "columns[0][data]": "0", "columns[1][name]": "", "columns[5][searchable]": "true", "columns[5][name]": "", "columns[4][search][regex]": "false", "order[0][dir]": "asc", "length": "10", } I have converted it using json.loads() function like. ajax_data = json.loads(ajax_data) I want to get the value if "order[0][dir]" and "columns[0][data]" but if i print it using ajax_data['order'][0]['dir] its giving error : KeyError at /admin/help 'order' But same code works if i access it for length key then it works. -
Microcaching with nginx reverse proxy for gunicorn upstream webserver (Django application)
I need help in setting up a microcaching config for my webserver (nginx reverse proxy + gunicorn). My web application is a Django-built forum-like website which gets ~200 requests per second, and where new posts appear every second or so as well. Current NGINX config: My website is both accessible over HTTP and HTTPS. At the moment, my config at /etc/nginx/sites-enabled/myconfig contains 3 server blocks, one for the upstream server, one server block listening on port 80, and another listening on port 443. Full config is given at the end. New NGINX config: Having gone through the example given on nginx's website, it seems I have to implement the following steps within my config: 1) I add the following to both the 80 and 443 server block, outside of any location blocks (or should it be added within location / - if so, how will that differ?): server { proxy_cache one; proxy_cache_lock on; proxy_cache_valid 200 1s; proxy_cache_use_stale updating; ... } 2) I specify a proxy cache location outside of any server block, e.g. writing something like this outside of all server blocks: proxy_cache_path /tmp/cache keys_zone=cache:10m levels=1:2 inactive=600s max_size=100m; I test the configuration, and if it works, I restart nginx. That's β¦ -
How to nest or jointly use two template tags in Django templates?
I'm trying to use template filters to do run a loop, but I'm unable to combine two python statements within the same statement/template. Whats the correct way to combine two variables in a template? Please see the syntax and explanation below: I'm building a forum with a double index, meaning, I've got a col-md-2 with list of categories. Each categories has forums, and depending on which category is clicked, that category's forums populate the next col-md-2. The remaining col-md-8 gets its content based on which category and which forum is selected. My logic: I've defined a template tag that loads the list of categories, which never change irrespective of which page gets loaded or which category or forum is selected. So that works fine. But based on the selected category, my second column needs to get populated. For this, I'm trying to define a custom filter (below). However, I'm not sure how to use this as it needs to be passed to another template where it runs a loop to render the html. Even if I create the for loop in this template (rather than passing it to another), I still have to do nested template tags, something like: {% β¦ -
Django dumpdata of multi-table inherited objects
I am trying to dumpdata my classes, which are: class SuperClassManager(Manager): def get_by_natural_key(self, identifier): return self.get(identifier=identifier) class SuperClass(Model): objects = SuperClassManager() identifier = CharField(max_length=31) def natural_key(self): return (self.identifier, ) class Class(SuperClass): pass But the dumped data is: [ { "model": "app.superclass", "fields": { "identifier": "identifier" } }, { "model": "app.class", "fields": {} } ] There's no way to relate the Class instance to the SuperClass instance in this case. What am I missing? Why isn't the superclass_ptr existent in Class (which points to SuperClass) being serialized so it is possible to relate the instances? Problem being: I have more than one subclass to my superclass and many instances of each subclass. So I need this relation to happen so my fixtures will make sense. -
Code Editor App in Django
Do you know any simple text or code editor app in Django? I want something similar to github editor (see attached image). I've looked into the existing similar wysiwyg apps already, but they seem to much complicated for something i want. I don't need the html tags. Thank you in advance! -
Gunicorn workers throwing obscure error in log file
A virtual machine hosting my Django web application has recently been acting erratically (set up with gunicorn + nginx reverse proxy). Erratic being the server becomes unavailable for many minutes under high load (~85% CPU utilization). I looked into var/log/upstart/gunicorn.log, and I see the following at some parts of the log. Can anyone tell me what this is? From cffi callback From cffi callback <function _osrandom_rand_bytes at 0x7fe2dd2b9b18>: Traceback (most recent call last): File "/home/myuser/.allenvs/myenv/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 66, in _osra$ <function _osrandom_rand_bytes at 0x7fe2dcc079b0> @ffi_callback("int (*)(unsigned char *, int)", File "/home/myuser/.allenvs/myenv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 159, in handle_abort : Traceback (most recent call last): File "/home/myuser/.allenvs/myenv/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 66, in _$ sys.exit(1) SystemExit: 1 @ffi_callback("int (*)(unsigned char *, int)", File "/home/myuser/.allenvs/myenv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 159, in handle_abort sys.exit(1) SystemExit: 1 I can't find much documentation about this error. Thanks in advance. -
No module named django.core in virtualenv Windows 10 - curious solution
I started this question because I didn't know why I was getting this error. I found a very simple solution on accident, and I haven't seen it explained elsewhere. If it has been, I'll take this down. I'm using Windows 10 and Python 3.5 in an activated virtual environment. I have added paths to my system environment variables. Problem: Following the djangorest quickstart tutorial, I got stuck on one of the first steps: http://www.django-rest-framework.org/tutorial/quickstart/. When I enter the command: django-admin.py startproject tutorial . I get the error that it can't find the django.core file. I can't even find this file in a search, so this is still confusing. Here is what worked: After searching the other threads I tried something someone said NOT to do: django-admin startproject tutorial . This is the same, but without the .py Investigation: I ran assoc .py and ftype Python.File and got: Python.File = "C:WINDOWS\py.exe" "%L" %* This must mean the .py links to the stated location. Not sure exactly how it works or what the symbols after the location mean or how to change any of this to make it more compatible with a virtual or other environment. I'm getting lost in online information β¦ -
KeyError when doing OneToOneField lookup from User model in Django
I have a model Applicant(AbstractBaseUser): resume = models.OneToOneField(resume) But when I try to do applicant = Applicant.objects.get(pk=1) applicant.resume I get a KeyError on the key user. I know that Django does foreign key relationship lookups with the lowercase name of the class so it appears that it is trying to lookup my User model, but in this case my user is an Applicant and thus it is failing. This is at least what I believe is happening. If anyone has any insights they would be greatly appreciated. -
unable to completely uninstall django on windows
Hello and sorry in advance for the mistakes i will make, but this is my first question. I just started with python and django. I installed django 1.10 (global) and then I installed virtualenv and virtualenvwrapper. First problem: I created a few environments but never figured out how to install different versions of django in an env. I activate an env, use pip list and django is missing. I use django-admin --version or python -c "import django; print(django.path) and it works. question: how to install different version of django in an environment? Second problem: I activated an env and used pip install django==1.9 (i thought it will install only in that env), but unfortunately i noticed by using django-admin --version that i have same version in env and outside it. (now 1.9) I used pip uninstall django command and it uninstalled version 1.9 but it seems that version 1.10 is still present (but broken). Can you please help? As soon as I get my answers, i will be able to carry on with my project. Thank you -
Django exception line number logging through middleware
I am trying to create Django middleware that logs specific information about exceptions that are raised from within views. I am having trouble getting the line number on which the exception was raised. Specifically, the end of the traceback shows File "<string>", line None. Where is this "<string>" coming from, and why does it show line number None? I get this same result whether I navigate to /view_raises_exception/ through my tests or through a browser window. I'm sure I could probably dig through the traceback in my process_exception() method to get the line number, but I'm wondering why exception.lineno isn't giving me the result I expect. My setup: Ubuntu 14.04.3 LTS (Cloud9) Python 3.4.3 Django 1.9 View: def exception_view(request): raise SyntaxError('Custom error message...') Urls: from django.conf.urls import url from . import views urlpatterns = [ url(r'^view_raises_exception/', views.exception_view), url(r'^view_raises_no_exceptions/', views.no_exception_view), ] Middleware file: from django.http import HttpResponse class ExceptionLoggingMiddleware(object): def process_exception(self, request, exception): name = type(exception).__name__ message = str(exception) line_no = exception.lineno print('***INSIDE PROCESS_EXCEPTIONS***') print('Name:', name) print('Message:', message) print('Line Number:', line_no) # return HttpResponse('Exception handled.') Server log: System check identified no issues (0 silenced). September 09, 2016 - 22:58:40 Django version 1.9, using settings 'middlewares_library.settings' Starting development server at http://0.0.0.0:8080/ Quit β¦ -
Django URL 404 Not Found
I'm currently following sentdex's Django web dev tutorial series and I've ran into an issue. When I click on this link, I'm getting this a 404. Highlighted is the regex I'm using. I'm pretty new to Django and URLs so I'm not too sure what the issue could be. -
Are there other management app-modules in Django?
A typical app looks like this: myapp/ βββ forms.py βββ __init__.py βββ management β βββ commands β β βββ __init__.py β β βββ my_command.py β βββ __init__.py βββ models.py βββ tests.py βββ urls.py βββ views.py .management.commands is the Django-enforced standard for management commands but why is it so deep. Are there other kinds of .management module? -
Django 1.9 | makemigrations on production server fails
Im developing an intranet web app, everything is working fine in my development enviroment, but when i try to deploy the project on my server and start the database migration with makemigrations i get the error that "app.table doesnt exist". The problem im facing is that indeed, the table doesnt exist because its the first migration im making, and the error is presented in my forms.py file. I tried: - Deleting the app/migrations folder, didnt helped - Executing "python manage.py migrate --fake", same result And i do have created the database -
what is the most secure django rest framework authentication implementation?
I'm setting up django rest framework in addition to the authentication piece. Here is the entry: http://www.django-rest-framework.org/api-guide/authentication/ There really isn't any reccomendations on which is the most secure solution. Can anyone let us know which is most secure implementation? -
How to disable cache locking for testing purposes
I have a Django app that uses Redis for caching. It relies on cache locking (cache.lock()) to reliably access and modify cache values from asynchronous tasks. My goal, though, is to disable locking (making cache.lock() uneffective) on testing environments, as the asynchronous tasks become synchronous while testing and this is leading the tests to deadlocks. However, even using Django's DummyCache, the locking behavior seems to remain. Am I able to disable the locking behavior in Django's cache settings? Couldn't find anything related in the docs. -
How to connect to an external database in Django, query data, and make plots
I am on my first Django project. I want to create a website which shows a few plots that I desire. I want the data for the plots to come from an external mySQL table, for which I have the login credentials. Please help me with the following questions in as much detail and code as you can: 1. What are the different ways of storing data that I have queried from the database. What is best for the purpose of making plots? 2. How will I go about doing this? Please provide as many code examples as you can The help is appreciated. -
Django two-way relationship between group and group members
I am trying to model a two-way relationship between group members and the group they belong to. More specifically, I'd like to model something like this: class Member(models.Model): name = models.CharField(max_length=50) group = models.ForeignKey('Group') #leader = models.BooleanField() class Group(models.Model): name = models.CharField(max_length=50) leader = models.ForeignKey('Member') So I want every member to be linked to a group. But each group should have a leader. I'd normally add a "leader" attribute to assign a leader for a group or add an extra model / table. However, I would like to be able to choose the leader from the members list for a specific group in the Django Admin interface and the above attempt results in an error of course, because the reference each other. What's the best way to achieve this? -
Django - how do I clone object without applying clone changes to source object
Best described by example: View: def my_view(request): obj_old = Inventories.objects.get(id = source_id) obj_new = obj_old obj_old.some_field = 0 obj_old.save() obj_new.some_field = 1 obj_new.id = None obj_new.save() The problem is that the changes I make to obj_new are also applied to obj_old so that the value of some_field is 1 for both obj_old and obj_new. Any ideas how to fix this ? -
django user have not add/change group permission but have add user permission. And it can give add/change group permission to the new user it creates
I have a superuser root. It create a new user 'admin' from admin panel which have all permission but not add/change group. I want when this 'admin' user create another user this admin user should not be able to give him those permission which this admin user does't have. -
How to use installation of Django
Hello guys! I have problem with my python 3.4 I need to install Django, but i don't know what happend ... This problem.. How fix it? -
Django store shell history
I lost all my history when I login to shell. Inorder to view the history, I installed ipython and tried to use it. Now, I get a error when I try this command - ipython manage.py shell_plus --print-sql [TerminalIPythonApp] CRITICAL | Bad config encountered during initialization: [TerminalIPythonApp] CRITICAL | Unrecognized flag: '--print-sql' Similarly even bpython also does not work. -
Pytest tests are very slow without internet though no test makes network calls
I am having a weird issue with pytest in a Django project. When I run a single empty unit test, It takes on average 7 secs, with reuse db, takes 3 secs on avg. With wifi off, it takes 20 secs on avg. With wifi on and network disabled, takes >150 secs on avg. For other team members of mine, there is no difference in time for the above mentioned cases. I checked using different network monitoring tools and there is no network activity happening also. -
DataError: (1406, "Data too long for column 'name' at row 1")
I've read nearly all other posts with the same error and can't seem to find a proper solution. In my models.py file I have this: class LetsSayCups(models.Model): name = models.CharField(max_length=65535) def __str__(self): return str(self.name) I get this error when I try to load aws mysql data into my local mysql server. I had the issue occur for another part in my models.py file, and the way I was able to work around it was by going into the my.cnf.bak file and changing the sql_mode from: sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES to: sql_mode='' And it worked!!! Until later on I find another error. The specific error is something like this: ... File "/Users/im_the_user/Desktop/my_company/my_project/load_items.py", line 122, in load_the_items existing_cups = Cups.objects.get_or_create(name=cups) ... django.db.utils.DataError: (1406, "Data too long for column 'name' at row 1") The above ... means things came before/after that I left out in this. Updating my my.cnf.bak file wasnt enough, nor was making the CharField max_length to 65535. What else could I do?