Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and MySQL display data from models
I am trying to display data from my models. I've also changed the database connection from the default sqlite3 to MySQL. And I've tried all the information I got online and still can't get it to work. Here's my views.py class BrandsView(CreateView): form_class = StockForm model = Stock template_name = 'myapp/brands.html' def get_queryset(self, request): stock = Stock.objects.all() return render(self.template_name, {'all_stock':stock}, request) Here's my models.py class Stock(models.Model): date_created = models.DateTimeField(auto_now_add=True) brand_name = models.CharField(max_length=30, choices=brand_name_choice, default='design') brand_style = models.CharField(max_length=25, choices=brand_style_choice, default='soft') brand_sample = models.ImageField() Here's my brands.html <div class="container"> {% for name in stock %} {{ name.brand_name }} <img src="{{ name.brand_sample.url }}" class="respnsive-img" /> {% endfor %} </div> I've checked that the STATIC_URL and STATIC_ROOT as well as MEDIA_ROOT and MEDIA_URL are set correctly. I have also tried manipulating the data in the shell, ie python manage.py shell and it works. It produces the desired output but when I try python manage.py runserver, it doesn't display any data in the web browser. what am I not getting right? -
Django-admin not working Ubuntu17.04
I tried installing Django 2.0 in ubuntu17.04 using pip3 install Django==2.0 when i start to create my project using djngo-admin startproject mysite it started shotawing django-admin is currently not instaled. I am new to ubuntu 17.04 where am i doing wrong`pip3 install Django==2.0 -
How to use custom font with weasyprint
I have a django app and I would like to create a pdf from my django view. I use weasyprint, and for some reason it doesn't accept my custom font. The font url is working and 2hen I render the same html with the same font-face, I see the coorect font, but my pdf is rendered with a wrong one. My render code is: import os from weasyprint import HTML, CSS from weasyprint.fonts import FontConfiguration from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from django.urls import reverse def render_to_pdf(template_src, context_dict={}): font_config = FontConfiguration() font_string = ''' @font-face { font-family: 'Titillium Web'; font-style: normal; font-weight: 300; src: local('Titillium Web Light'), local('TitilliumWeb-Light'), url('http://X.X.X.X:8000/static/fonts/titillium_web.woff2') format('woff2'); } *, div {font-family: 'Titillium Web';} ''' template = get_template(template_src) rendered_html = template.render(context_dict) pdf_file = HTML(string=rendered_html).write_pdf(stylesheets=[ CSS(settings.BASE_DIR + '/gui/executive_summary.css'), CSS(string=font_string)],font_config=font_config) response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="report.pdf"' return response Any idea what am I doing wrong? -
runserver works fine but wsgi application not?
When I runserver the application it works fine, but when deploying it with uwsgi+nginx it fails. Although I created a simple test 'hello world' wsgi application and it works fine. The following is the content of the log file when i issue the uwsgi command: uwsgi --ini myconfig.ini ... Traceback (most recent call last): File "./Makaneyyat/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/db/models/base.py", line 124, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/db/models/base.py", line 331, in add_to_class value.contribute_to_class(cls, name) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/db/utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 6, in <module> from .features import DatabaseFeatures File "/var/www/html/new.makaneyyat.org/venv/lib/python3.6/site-packages/django/contrib/gis/db/backends/postgis/features.py", line … -
How to select_for_update, edit and save multiple object in Django
How to select_for_update and save multiple object in Django? Example: with transaction.atomic(): for a in cls.objects.select_for_update().filter(pk__in=[id1, id2]): a.save() This code gives me: deadlock detected DETAIL: Process 28083 waits for ShareLock on transaction 368522; blocked by process 28063. Process 28063 waits for ShareLock on transaction 368523; blocked by process 28083. HINT: See server log for query details. CONTEXT: while locking tuple (2,9) in relation "bitwayapi_account" on tests where i run this code in multiple threads for two objects. As I know, save() performs commit. But it also unlocks locked rows or something other causes deadlock? My actual task is to select 2 accounts and transfer money from one to another. How do i select_for_update, edit objects and save them? -
DRF pass non model field variable to serializer
I have a serializer TestSerializer, how can i pass a new variable that is not a model field that is a list, ex: users_list = [1,2,3,4] and validate it? I tryed this but it's not working: class TestSerializer(serializers.Serializer): user_list = serializers.ListField(child=IntegerField()) def create(self, validated_data): users = validated_data['user_list'] # rest of create function -
Product views counter
Many re-read, namuchalsya, but can not solve, the elementary, as I understand it, the task. Help please the beginning developer. Thank you My model// class Item(models.Model): item_title = models.CharField(max_length=100,unique=True, blank=True, null=True, default=None) slug = models.SlugField(unique=True, default=None) description = models.TextField(blank=True, null=True, default=None) quantity = models.PositiveIntegerField() #need replace quantity at stock price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to="item_images", null=True) category = models.ManyToManyField(Category, related_name='items') views = models.IntegerField(default=0) available = models.BooleanField(default=True) created_date = models.DateTimeField(default=timezone.now) updated_date = models.DateTimeField(auto_now=True, auto_now_add=False) and my view// class ItemDetail(DetailView): model = Item template_name = 'product/product-details.html' context_object_name = 'product' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['addProdform'] = ProductForm #remove in future context['CommentAddForm'] = CommentAddForm context['cart_product_form'] = CartAddProductForm context['popular_item_list'] = Item.objects.order_by('-views')[:4] return context My task, as I understand it, when invoking a product instance is to increment the field of views and store it in a session, but so far nothing has happened -
Django create Scheduling
Hi, I run a app of Django, and I want that it run in a specific time (for example: form 9 am to 0 pm). One sol can be (in view.py): I can verify the hour and if it is not beteween this hours can redirect to a specifict page. There is a other form? -
DRF passing extra variable to serializer
I made a serializer that creates a CompletedTest object. When i make the create method i need to pass 2 new varibles one - "test" containing test id, and the other "user_list" containing a list with users ids, ex: [1,2,3,4]. I managed to pass "test" containing test id but i couldn't pass "user_list". models.py class CompletedTest(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) test = models.ForeignKey(Test) created = models.DateTimeField() completed_with = models.ManyToManyField('self', blank=True) serializers.py class CompletedTestSerializer(serializers.Serializer): test = serializers.CharField(source='test.id') user_list = serializers.ListField(child=serializers.IntegerField()) def create(self, validated_data): test = validated_data['test'] users = CustomUser.objects.filter(id__in=validated_data['user_list']) for user in users: try: CompletedTest.objects.get(test_id=test, user_id=user) except CompletedTest.DoesNotExist: completed_test = CompletedTest.objects.all() completed_test.create(user=user, test=test, created=timezone.now()) completed_test.get(user=user).completed_with = completed_test.exclude(user=user) def update(self, instance, validated_data): pass views.py class CompletedTestView(ListAPIView): queryset = CompletedTest.objects.order_by('id') serializer_class = CompletedTestSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) def post(self, request): comp = CompletedTestSerializer(data=request.data) comp.is_valid(raise_exception=True) comp.save() return Response({'success': True}) In my tests this is what i'm passing: { "test": 1, "user_list": [1,2,3] } With the current user_list variable i am getting this error: TypeError at /tests/completed/ int() argument must be a string, a bytes-like object or a number, not 'dict' -
I am unable to deploy in pythonanywhere for my project due to WSGI application issues
Error running WSGI application Improperly Configured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. 2017-12-11 07:01:22,866: If you're seeing an import error and don't know why, 2017-12-11 07:01:22,866: we have a dedicated help page to help you debug: 2017-12-11 07:01:22,866: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2017-12-11 07:01:22,866: *************************************************** 2017-12-11 07:01:27,434: Error running WSGI application 2017-12-11 07:01:27,434: ImportError: No module named django.core.wsgi 2017-12-11 07:01:27,434: File "/var/www/patilnayan092_pythonanywhere_com_wsgi.py", line 36, in 2017-12-11 07:01:27,435: from django.core.wsgi import get_wsgi_application 2017-12-11 07:01:27,435: *************************************************** 2017-12-11 07:01:27,435: If you're seeing an import error and don't know why, 2017-12-11 07:01:27,435: we have a dedicated help page to help you debug: 2017-12-11 07:01:27,435: https://help.pythonanywhere.com/pages/DebuggingImportError/ NOTE below for the patilnayan092_pythonanywhere_com_wsgi.py file: import os import sys path = u'/home/patilnayan092/online_test/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTING_MODULE'] = 'online_test.settings' from django.core.wsgi import get_wsgi_application [This is line 36] application = get_wsgi_application() NOTE: I have used Python 2.7 Version & Django 1.9.5 for this requirement version. What could be the issues for this WSGI python application ??? Kindly let me know about this issues ASAP. -
Very weird issue with import
I'm very new to Django and I'm hitting a very weird issue. I have a script that sync data to populate a database: $ cat modules/stash.py import stashy class SyncProject: def __init__(self, endpo, user, passw): import stashy self.stash = stashy.connect(endpo, user, passw) I run my script with: $ python manage.py shell < modules/stash.py The weirdness is that if I don't put the second import stashy, it doesn't work: NameError: name 'stashy' is not defined From the bit of Python I did a long time ago, that seems very unexpected and forces me to add import in every single method... Not sure if there is something wrong in how I import my dependencies or the way I run the script... -
Update the reverse Foreignk key Model on Model update
I have 3 models, Account, Company and Product. Product has an ForeignKey to Company, company and FK to account. all of them have a field called 'is_active'. class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) is_active = models.BooleanField(default=False) class Company(Meta): account = models.ForeignKey(Account, related_name='account', on_delete=models.CASCADE) is_active = models.BooleanField(default=False) What I need: when Company is_active becomes False I want for all Products related to the Company, is_active to become false when Account is_active becomes False I want for all Companies related to the Account, is_active to become false, and also propagate to the Products I know that I need to change the save(or use post-save signal), but I don't know how to select and change the Foreign Keys Model, and propagate multiple levels down, in case of Account The relation is in reverse from parent to child and not from child to parent., so no field FK available. -
Django application template folder location
I installed django postman application by following project quick start guide. When I try to access the page http://127.0.0.1:8000/messages/inbox/ I get TemplateDoesNotExist at /messages/inbox/ with following message: Django tried loading these templates, in this order: /usr/local/lib/python2.7/dist-packages/django_postman-3.6.0.post1-py2.7.egg/postman/templates/base.html (File does not exist) However base.html is in /usr/local/lib/python2.7/dist-packages/django_postman-3.6.0.post1-py2.7.egg/postman/templates/postman/base.html, there is one more directory with application's name but template loader doesn't look for it. I am sure it is a setting in settings.py with TEMPLATES variable. This is my TEMPLATES settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
images not getting displayed from amazon s3 bucket for django project
These are my s3 configuration. DEFAULT_FILE_STORAGE = 'doctocliq.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'doctocliq.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'doctocliq' S3DIRECT_REGION = 'us-west-2' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' Uploaded all the static files to the bucket with collectstatic command, except images all the other static files are working, on local server there is no issue also. The site link is http://doctocliq-dev.us-west-2.elasticbeanstalk.com/. Hope some body can help me, thank you. -
How can i save django dynamic formset data with using forms
I am trying to save formset extra fields data using forms and views . Eg. Team has no.of players . so i want to add new player by click on add more button . the code i tried below . the problem is if i add more than one player at a time.. it is saving last object value only.. please correct me .. o/p for below code models.py from django.db import models class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname forms.py from django import forms from django.forms.formsets import formset_factory class PlayerForm(forms.Form): pname = forms.CharField() hscore= forms.IntegerField() age = forms.IntegerField() PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.Form): tname= forms.CharField() player= PlayerFormset() views.py from django.shortcuts import render, get_object_or_404,redirect from .models import Player,Team from .forms import TeamForm,PlayerFormset from django.contrib import messages from django.contrib.auth.decorators import login_required from django import forms from django.forms import formset_factory def post(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, … -
How to install packages for django-1.11.8
I am getting erorr when installing modules using pip for python 2.7 after django-2 comes. I am trying to install django_cron for django-1.11.8 and python-2.7 but I am getting the error- @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-JKhsAF/Django/ So how to install modules for python-2.7 and django-1.11.8 ???? -
access the celery result
I want a message to be displayed in my web-application (which is using django framework ) for a particular changes in some tasks .I have implemented celery but cant make it run as a daemon process and I want to access those changes in UI. Can anyone suggest me ways to do so? I have been able to configure the celery but not make it work continously in background.My actual requirment is if there is any changes in the celery I want it to invoke a message in my UI.is it possible? -
Celery Supervisor Secret Key Error
I have a django 1.11.4, python3.5, gunicorn 19.7.1 server with supervisor, redis 2.10.6 and celery 4.1.0. My File structure is like so: samy_python ├── celery.py ├── __init__.py ├── settings ├── urls.py ├── wsgi.py website ├── static ├── templates ├── samy | ├── samy_firebase.py | ├── tasks.py ├── views.py I get my secret with: # settings.py SECRET_KEY = os.environ.get("secret_KEY") My supervisor conf file for celery is: [program:gunicorn] .... environment = secret_KEY="12345" ..... [program:celery] directory=/home/username/Projects/samy/samy_python command=/home/username/Projects/samy/samy_python/env/bin/celery --app=samy_python.celery.app worker -B -l info user=username stdout_logfile=/var/log/celery/celery.log stderr_logfile=/var/log/celery/celery.log autostart=false autorestart=false startsecs=10 My Celery File: # celery.py from __future__ import absolute_import import os import logging logger = logging.getLogger('myapp.celery.py') from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "samy_python.settings") # Celery App # TODO # [START Celery App] app = Celery('samy_python') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # [END Celery App] My init file: # __init__.py from __future__ import absolute_import from .celery import app as celery_app The Configuration in my settings.py file for celery: BROKER_URL = 'redis://localhost:6379/1' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' Where the error could be coming from is in my settings.py file I use an env variable to set the environment. (Production, Dev, or Test): DEBUG = False DJANGO_TESTING = False DJANGO_DEVELOPMENT … -
How to Import Django Static File with Dynamic Name using Regex
I'm building a SPA with Django and React, but I'm relatively new to Django and can't find info on importing a static file with a dynamic name using regex. The static file is a webpack bundle in the format 'main-[hash].js' - examples: main-92e041e445bf7b737036.js and main-3583de2c3fcf00501624. Also, I realize that I can change webpack to generate bundles with static names, but that'd be no fun. -
There will get cross-domain issue when I deploy the frontend and django backend to remote server
Deploy the test environment to remote server. I use python manage.py to run the development server for django backend: python manage.py runserver 8001 and use the apache to listen the 80 port for website frontend. So, when website request the backend, there is cross-domain issue, because the port is not same. How to handle this issue correctly if in the development environment? Or if this is impossible, whether only can use distribution environment to realize it? -
Django Change Date Format from YYYY-MM-DD HH:MM to MM/DD/YYYY
I'm trying to pass input from a template to a query in my view, but if the date is not passed in Django's default date format YYYY-MM-DD then it throws an error. [u"'11/11/2012' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] template.html <form method="GET" action="/BusComm/interactions"> <div style="width: 100px; float:left"> <p>To Date:</p> </div> <div style="width: 200px; float:left"> <input type="date" Placeholder="mm-dd-yyyy" name="date_to" id="id_q" value="{{ query }}" float="right"> </div> <input type="submit" value="Submit" /> </form> View.py def interactions(request): today = datetime.now().date() table = interactionsTable(Interactions.objects.all()) if request.GET.get('date_from'): date_from = request.GET.get('date_from') table = interactionsTable(Interactions.objects.filter(date__range=[date_from, today])) return render(request, 'BusComm/interactions.html',{ 'table': table, }) The interactionsTable(Interactions.object.filter()) line is the one that throws the error. My question is how can I change the date format in Django to accept MM/DD/YYYY instead of YYYY-DD-MM? -
How to deploy the website frontend and Django backend ?
How to config the website frontend and backend ? I use Python/Django write the backend, and use html/css/js write the frontend. now I want to put the frontend and backend to the remote server (CentOS 7.2). I installed apache, in httpd.conf I config the DocumentRoot: DocumentRoot "/var/www/html/website" under the /var/www/html/website there is the website's index.html. But where I put the Django code to as the backend, and how to config it? If is in java-ee, the common practice is put the frontend and backend together, how about Django backend? How to deploy them? -
Run a Django project from VSCODE
Is there a way to run a Django project from VSCODE editor? Currently I use the windows CMD to run my project. Every time when I hit the button 'run' on VSCODE it doesn't run the project. On pyCharm we can add 'runserver' to its script parameters configurations. Is there something like that on VSCODE? Thanks. -
This is about Python window program(CRUD, DB connect). please answer
Hi I am a third year programmer. I recently started studying Python in earnest. However, programming languages such as php and JavaScript have a lot of information on the Internet, but they are not accessible to Python. So I would like to ask some people who studied Python first, so I write this. The goal is, in conclusion, to create a Windows program -CRUD (DB linked) within December by python. Is there a good example and site to learn about Python? A- Web program. 1. A good source or site about Django 2. Using Django to create a CRUD (source) 4. Other frameworks except Django. 3. CRUD web program example by direct coding. B- Windows program.(I want to create) 1. CRUD window program example through Python direct coding 2. Windows program examples for Python direct coding 3. Windows program frameworks. I am curious. Please help .. Please answer me. thank you. -
Django app in heroku deleting model objects after some time
I've written a simple django Q&A forum app and deployed it on Heroku, the local version of the site works fine. However, the production version does not store the questions, answers etc. for more than a few hours. I decided to stick with sqlite3 that comes with Django. I don't expect a lot of traffic to the site so I decided it would be worth it to keep the development db for now. site: http://immense-plateau-35286.herokuapp.com I've tried a few solutions from the DB setup page on Heroku, but have not had any success so far. Any idea what this might be?