Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django connectivity with MYSQL [duplicate]
This question already has an answer here: Error using MySQL Connector/Python with Django 1.11 2 answers I have installed mysql, python 2.7 and django 1.11. I am novice in django and was following instructions step by step to set up and run the server. I created a new project djangodemo and edited the settings.py file in django project to check the connectivity to mysql database. This is the setting i put in there: DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'train_set', 'USER': 'XXXX', 'PASSWORD': 'XXXXXXX', 'HOST': '127.0.0.1', 'PORT': '3306', } } After that as per the instruction, I ran the following command: C:\DjangoProj\djangodemo>python manage.py runserver However, I am getting the following error: C:\DjangoProj\djangodemo>python manage.py runserver Unhandled exception in thread started by <function wrapper at 0x0000000004071E48> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Python27\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import … -
Use Django's ORM in Celery
I have a few django micro-services. Their main workload is constant background processes, not request handling. The background processes constantly use Django's ORM, and since I needed to hack a few things for it to work properly (it did for quite a while), now I have problems with the DB connection, since Django is not really built for using DB connections a lot in the background I guess... Celery is always suggested in these cases, but before switching the entire design, I want to know if it really is a good solution. Can celery tasks (a lot of tasks, time-consuming tasks) use Django's ORM in the background without problems? -
Django Application not working (cPanel, Cloudlinux)
I'm trying to setup an Django Application using the following: cPanel server with Cloudlinux Using Cloudlinux Python Selector to create a virtualenv Python 2.7 is working But when I try to startup the application it gives me the following: I'm not really familiar with this... Maybe you guys can help? [ 2017-06-05 13:15:00.9565 751654/7f837c603700 age/Cor/App/Implementation.cpp:304 ]: Could not spawn process for application /home/djangotest/env2: An error occurred while starting the web application. It exited before signalling successful startup back to Phusion Passenger. App 754955 stderr: File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/conf/init.py", line 97, in init App 754955 stderr: File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup App 754955 stderr: File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/conf/init.py", line 53, in getattr App 754955 stderr: File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/init.py", line 22, in setup App 754955 stderr: File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application App 754955 stderr: File "/home/djangotest/env2/passenger_wsgi.py", line 8, in File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/conf/init.py", line 97, in init File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/conf/init.py", line 53, in getattr File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/init.py", line 22, in setup File "/home/djangotest/virtualenv/env2/2.7/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application File "/home/djangotest/env2/passenger_wsgi.py", line 8, in <module> -
How do I know which groups each product is in?
class Product(models.Model): name = models.CharField(max_length=256) class Group(models.Model): name = models.CharField(max_length=32, unique=False) products = models.ManyToManyField(Product, blank=True) Products in group.pk == 1: products = Group.objects.get(pk=1).products.all().values('name') Result: <QuerySet [ {"name": "product1"}, {"name": "product2"}, {"name": "product3"}, ] How do I know which groups each product is in? Like this: <QuerySet [ {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]}, {"name": "product2", "groups": []"}, {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}}, ] Thanks! -
Best options creating a web page
I have been asked to create a web page for the company I am working at. I would like to create it from scratch as the one they currently have was set up using Wordpress and is very limited. I wanted advice on a few matters before I start: I want to use Django. I have used it before and seems like a good option. However I have come across Django REST API and I want to implement this as I want the page to be mobile friendly and it seems like this is the best way to do this. Is it best to create an app with django and then add it in? I have come across Bower as a Dependency Manager. I am only working here for a short time and want to leave things as consolidated as possible. It seems BOWER helps with all the updating throughout time. Has anyone had any experiences with it? My understanding is that I can link it with JQery for the front end and Jenkins for deployment. Is using ReactJS a good option for the front end? It seems very promising. Last question, has anyone used AWS for hosting? Is the … -
[Django rest framework]: Serialize a list of strings
I am working with django and djando rest framework I hace created a new endpoint installedapps`. When making GET requests to it, I want to return the data contained in a list of strings (list of installed apps) The list of strings looks something like this: installed_apps = ['django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_js_reverse', 'djcelery', 'bootstrap3', 'foo', 'bar', 'apirest'] Until now I have only worked with model serializers, and everything was pretty easy. But now i dont know how to return this list of strings This is what I have tried so far: class InstalledAppsViewSet(viewsets.ViewSet): serializer_class = serializers.InstalledAppsSerializer def list(self, request): from credits.views import GetInstalledApps installed_apps = GetInstalledApps.get_installed_apps() serializer = serializers.InstalledAppsSerializer( instance=installed_apps, many=True) return Response(serializer.data) class InstalledAppsSerializer(serializers.ListField): name = serializers.CharField(max_length=256) child = serializers.CharField() installed_apps_field = serializers.SerializerMethodField( 'get_installed_apps') I am always getting all kind of errors. Any help on how to do this? Return the content of the list of strings -
django - model - what are the benefits?
I have customized my Django project to work with mariaDB (mySQL). Works fine, however I have issues (or concerns) with models. First of all - I am not sure why I should need them if for me (personally) its much easier to use SQL statements to get the data. Using API for DB queries might be useful for people who do not know SQL, but for me its less flexible. Can anybody explain me main benefits of using models? Here is one of the issues I have. See the code below. class Quotes(models.Model): updated = models.DateTimeField() tdate = models.DateField(default='1900-01-01') ticker = models.CharField(max_length=15) open = models.FloatField(default=0) vol = models.BigIntegerField(default=0) 1) why program does not consider 'default' when DB table and fields are created? 2) why - what I define as FloatField on DB is 'double' and not 'float' (I checked this using phpMYAdmin) How can I properly set default value? My table will have at least 1 million of entries. Do I need to concern about performance using API instead of direct SQL queries? Usually one query will select 700-800 entries. Is it good approach to use MySQLdb and direct SQL's instead of models? sorry that some questions might sound too … -
Django: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
I am new to Python and Django. I am trying to install Django on Linux. Python version currently available on the server is Python 2.4.3 I installed Python 3.4.2 following the below steps: wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz tar -xvzf Python-3.4.2.tgz cd Python-3.4.2 ./configure --prefix=/root/python3 make make install The python correctly got installed. so when i do /root/python3/bin/python3.4 i get Python version 3.4.2 so i created a soft link -> ln -s /root/python3/bin/python3.4 python3 Now i created a virtualenv through /root/python3/bin/pyvenv-3.4 venv3.4 source venv3.4/bin/activate then i installed DJango: pip install Django==1.9 Django got successfully installed Created the project myproj: django-admin startproject myproj myproj project successfully created: cd myproj now when i do python manage.py migrate i get error: **Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/root/venv3.4/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 89, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/root/venv3.4/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations … -
Django not finding some JS and CSS resources
Perhaps this is a laughable problem but am really lost. It was working fine until I ported the project to a new laptop. Here is my filesystem structure: bill ==>bill (contains settings.py) ==>static ==>welcome ==>manage.py Now in static i have my directory, i have folder plugins, js and css. The following are in my base.html template: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title>{% block ownername %}{% endblock %} {% block title %}{% endblock %}</title> <script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script> <!-- Bootstrap 3.3.6 --> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'plugins/datepicker/datepicker3.css' %}"> **<link rel="stylesheet" href="{% static 'plugins/lobibox/lobibox.min.css' %}">** <script src="{% static 'plugins/slimScroll/jquery.slimscroll.min.js' %}"></script> **<script src="{% static 'plugins/moments/moment.min.js' %}"></script>** It loads some resources while it gives 404 for some other resources that are there and working in my old laptop. The configuration is the same since I used virtual environment to start it. What am I missing please? I am really lost on what it is doing. -
Django: flatpages/default.html not found when usign flatepages
I completed Django's 7 part tutorial and am now reading both the official documentation about flat pages as well as this other site. in my_project/settings.py I have added the sites and flatpages apps as well as the SITE_ID. in my_project/urls.py I have added urlpatterns += [url(r'^pages/', include('django.contrib.flatpages.urls')),] and because I also need to have flatpages/default.html as a template, in my_project/templates/flatpages/ there is a file named default.html So I went onto the admin page and added a flatpage named "test" and then went to ...8000:/pages/test/ to get an error message TemplateDoesNotExist. So where did I go wrong? -
How to fix such an error in Django url-routing, get_object_or_404and Slug?
How to get exactly the series that is specified in the URL, but the name of all series is the same, and they should be the same, but it takes only the URL of the series itself, that is, it searches only for the URL series, but not how, so that this series was in The series which is specified in the URL and also was in the season exactly the volume that is specified in the URL here is url Url works fine but I can not go to the right series! urlpatterns = [ url(r'^$', homeview, name='homeview'), url(r'^subscribe/$', validate_email, name='subscribe'), # /series/ url(r'^(?P<serial_slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), # /series/Prison_Break/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/$', post_of_season, name='post_of_season'), # /series/Prison_Break/season_5/ url(r'^(?P<serial_slug>[\w-]+)/(?P<season_slug>[\w-]+)/(?P<series_slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), # /series/Prison_Break/season_5/2/ ] Models class Series(models.Model): id = models.AutoField(primary_key=True) rus_name = models.CharField(max_length=60) eng_name = models.CharField(max_length=60) slug = models.SlugField(unique=False) serial_of_this_series = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True) season_of_this_series = models.ForeignKey(Season, on_delete=models.CASCADE, default=True) number_of_series = models.IntegerField(default=0, blank=True, null=True) description = models.TextField(max_length=700, blank=True, default=None) size_of_torent_file = models.CharField(max_length=60, default=None) link_for_dowloand_serie_in_quality_360p = models.CharField(max_length=60, default=None) link_for_dowloand_serie_in_quality_720p = models.CharField(max_length=60, default=None) link_for_dowloand_serie_in_quality_1080p = models.CharField(max_length=60, default=None) rating = models.FloatField(default=0, blank=True) is_active = models.BooleanField(default=True) timestamp_rus = models.DateField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp_eng = models.CharField(max_length=60) time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=42) def get_absolute_url(self): return reverse('series:post_of_serie', kwargs= {'serial_slug': … -
Adding/Removing url patterns from django during runtime
For example I have a url in my urls.py- url(r'^my-url/$', views.my_view) Now on a particular action from views, I want to remove this url from urlpatterns and add a new url during runtime. Is it possible, if so, how? -
Django search in multiple field with multiple value
I have a model which stores login logout time and date for users class LoginLogout(models.Model): username = models.CharField(max_length=30, unique=True) date = models.DateField(auto_now_add=True) login_time = models.TimeField() logout_time = models.TimeField(null=True, blank=True) Now I need to search in this model by the field date and username. I have a form which takes date_from, date_to and username as input. Any field can be blank. If username is blank all results will be returned. Now what will be the queryset for achieving the desired queryset. -
Django url dispatcher uses strings to specify function, why?
The Django documentation shows examples like this: from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), ] However, I have seen some code that looks like this: from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', 'special_case_2003'), ] Where special_case_2003() is the name of a function in views.py. What is the difference between these two methods? -
how to get only user's photo list by Listview django
All. I want to use Listview to show only user's photo list not other user's photo list. but it doesn't work. user can get other user's photo. this is views.py class PhotoListView(ListView): model = Photo def get(self, *args, **kwargs): #if user connect to other user's page, go to the user's page. if kwargs['username'] != self.request.user.username: return redirect('index') #to get only user's photo list. username = self.request.user.username return super(PhotoListView, self).get(username=username, *args, **kwargs) this is model.py class Photo(models.Model): user = models.ForeignKey(User) image_file = ProcessedImageField(upload_to='%Y/%m/%d/orig', format='JPEG', options={'quality': 100}) source = TaggableManager(through=Taggedsource, related_name='source') subject = TaggableManager(through=Taggedsubject, related_name='subject') description = models.TextField(max_length=500, blank=True) comments = models.PositiveSmallIntegerField(default=0, null=True) posted_on = models.DateTimeField(default=datetime.now) -
How to post a request in django with with username and password as parameters
How to make a post request from my django view with username and password as parameters. I have tried to do request.POST[url, auth=(userid, password)] but it gives a querydict error. -
How to set default_app_config for Django with apps directory structure?
I wan't to declare default_app_config variable for my app, but i have an error django.core.exceptions.ImproperlyConfigured: Cannot import 'accounts'. Check that 'apps.accounts.apps.AccountsConfig.name' is correct.. All my apps is located in directory apps: project_name/ apps/ app1/ app2/ .... accounts/ I am using my apps like this: INSTALLED_APPS = [ # Local Apps 'apps.category', 'apps.products', 'apps.cart', 'apps.orders', 'apps.accounts', 'apps.attributes', 'apps.pages', 'apps.compare', 'apps.filters', 'apps.brands' ] And now when i want to set default_app_config for my app, i get the error above. init.py in app folder: default_app_config = 'apps.accounts.apps.AccountsConfig' apps.py in app folder: from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' verbose_name = 'Пользователи' Why I get the error? -
Collectstatic command loaded my statis files the first time and then once i restarted the surver it stopped working
Hello everyone i am working on a project that is not my own and has no documentation. Don't ask why i guess the developer expected to be the only one working on it. Unfortuanetly i am not able to get in contact with him. The first time i ran the collectstatic command, it loaded all of the static files, then i left the computer running over the weekend and when i came back and restarted the server it stopped working and would not load the static files. settings.py STATIC_URL = 'static/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'run/media/') STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'run/static/') MEDIA_URL = '/media/' I would also like to add that the guy has created a very, very custom admin site, and he has included settings for both the admin and the regular setting, hence settings.py and settings_admin.py. In addition he also has a urls.py and admin_urls.py. If anyone can give me info as to why he would do this, i would greatly appreciate it. urls.py file: from django.conf.urls import include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.static import serve from rest_framework.urlpatterns import format_suffix_patterns from myapp import settings import myapp.apps.style.views urlpatterns = [ url(r'^', include('myapp.apps.config.urls')), url(r'^', include('myapp.apps.user.urls')), url(r'^', include('myapp.apps.game.urls')), url(r'^', include('myapp.apps.reward.urls')), url(r'^', … -
Jquery Django Put request for array not working
$.ajax({ type: 'PUT', url: '/api/profiles/1/countryupdate/', contenttype: 'application/json', dataType: 'json', data: { interestedCountry: [1,2] }, success: function(data) { console.log('interestedCountry', data) }, error: function() { console.log('error country interestedCountry') } }); This is my code for put request from frontend to the REST API. The value in interestedCountry are the primary keys for the country. When, I send the data as { interestedCountry: 1 } Then, it is updated. I am unable to send array from the front end. Why? Is there any mistake? But in the REST API, I am able to update the multiple selected values. -
Get url variable from request
One of my URLs looks like this: url(r'^(?P[0-9]+)/foo/', Foo.as_view()), Given this CBV: Class Whatever(View): @decorator(my_id) def post(self, request, my_id): # ... I need to access to my_id in the decorator. What is the best way to accomplish this? Maybe, overriding initial and take it from request.path? -
Django: My Register_Lost page not showing up
Still newbie in django, please help me Urls.py : from django.conf.urls import url from . import views app_name = 'lostfound' urlpatterns = [ # /lostfound/ url(r'^$', views.IndexView.as_view(), name='index'), # /lostfound/lostitems url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'), this is the main problem of my url, i can't display my register_lost.html # /lostfound/lostitems/addlostitems url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),` Views.py : from django.views import generic from .models import Wallet class IndexView(generic.ListView): model = Wallet template_name = 'lostfound/index.html' class LostItemsView(generic.ListView): model = Wallet template_name = 'lostfound/lost_items.html' class RegisterLostView(generic.ListView): model = Wallet template_name = 'lostfound/register_lost.html' lost_items.html : <div class="menu-button z-depth-3 right"> <a class="waves-effect waves-light btn" href="{% url 'lostfound:register_lost' %}"> <i class="medium material-icons right">playlist_add</i>Tambah Data </a> </div> this is my register_lost.html that i want process register_lost.html : {% extends 'lostfound/base.html' %} {% extends 'lostfound/lost_items.html' %} {% block title %}Register Lost Items{% endblock %} {% block content %} {% load staticfiles %} {% block sign_in %} {% endblock %} <h1>Hello</h1> {% endblock %} -
django inspectdb issue for MySQLdb
In Django, i change the settings for Mysqldb in settings.py . as per the documentation , inspectdb is a command used to create a models automatically(For legacy databases only). but if we do so , i met one problem, for my project first i used one table (dag) of my db. after that i need more information from another table(same DB), so i commented(/**) the codes of previous table and added new table(dagstats) as a models than i do makemigrations what it does is, delete my previous table(dag) in my DB and added the new table. what if i need to access the previous table ?? why is this happening ?help me out with the mechanism of models in Django. thank you in advance -
django cache REST API Urls issue
I have followed the solution provided in Stack overflow Link & it is working perfectly when i use this from my browser. However, when i tried hitting that url with curl, it doesn't cache for the browser.. Let me explain. If i hit a url like example.org/results?limit=7 from my chrome, it takes 8-10 seconds to load & successive hits takes time in milliseconds So what i did is call this URL with the curl command; but it didn't use the cached data & created the cache again. So i found out the issue is with the arg parameter in the below code as it contains the browser headers in WSGIRequest object which is being used in caching key. @method_decorator(cache_page(60 * 60 * 24)) def dispatch(self, *arg, **kwargs): print(arg) print(kwargs) return super(ProfileLikeHistoryApi, self).dispatch(*arg, **kwargs) What can i do is to pass only the kwargs to create the cache. Thanks for the help in advance. -
Django App Log level info not getting write into file
I have added below setting in Django for Info level log logger = logging.getLogger(__name__) logging.basicConfig(LOGGING=settings.LOGGING) LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s %(message)s', }, }, 'handlers': { 'file': { 'class': 'logging.handlers.TimedRotatingFileHandler', 'formatter': 'verbose', 'level': logging.INFO, 'filename': '/logs/django/api.log', 'interval': 1, 'when': 'midnight', 'encoding': 'utf8' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': logging.INFO, 'propagate': True, }, }, } If I change this level to Debug then it works properly but when I change it to INFO Level then the log will not be written into the file. Can somebody help? -
Optimizing postgres contains (LIKE) query in django for CHAR field
So I've got a query for a search endpoint in my Django (postgres) backend like so: widgets = Widgets.objects.\ filter(user=request.user).\ filter(title__icontains=data['query']).\ distinct('url')[:250] title is a CHAR field (models.CharField(max_length=255, blank=True) in django). contains here of course amounts to a '%LIKE%' query in Postgres. I'd like to speed up that query. It seems like most optimizations for postgres text search are only for TEXT fields - is there any way to speed up exact string searches on a CHAR column? Or would I be better off converting those columns to TEXT, taking the storage increase hit, and better indexing them somehow?