Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Idiomatic way to change user roles
I currently have a app that requires easy switching between user subclasses. Each user role has different fields, so they don't need to carry over, but each User instance should be attached to one of these subcalsses. What is the most idiomatic way of switching these roles? Should we even be using subclasses in the first place? I have seen these pages: Convert a subclass model instance to another subclass model instance in django? Change class of child on django models We are pre-prod, and therefore open to changing schema if there is a better approach, unlike these two examples. -
OSError: dlopen(libvlc.dylib, 6): image not found with django on OSX
I know there are like 3 related links, but im not supposed to disable any security features for our project. How do I fix this without disabling anything? It runs on my group mates ubuntu, but anyone with mac it does not run. -
Django FileField not cooperating with Python 3's csv module
I have this form: class CSVImportForm(AuthorshipMixin, FormMixin, forms.Form): data = forms.FileField() def import_csv(self): school_csv = csv.DictReader(self.cleaned_data['data']) for row in school_csv: print(row) The intended purpose of import_csv() is to import the CSV to the application's database, but it has been altered for brevity's sake. An exception occurs when I attempt to iterate over school_csv, which I guess is when DictReader first attempts to read the file: Traceback: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/views/generic/edit.py" in post 215. return self.form_valid(form) File "/opt/project/project/import/views.py" in form_valid 16. form.import_csv() File "/opt/project/project/import/forms.py" in import_csv 67. for row in school_csv: File "/usr/lib/python3.5/csv.py" in __next__ 109. self.fieldnames File "/usr/lib/python3.5/csv.py" in fieldnames 96. self._fieldnames = next(self.reader) Exception Type: Error at /import/ Exception Value: iterator should return strings, not bytes (did you open the file in text mode?) I don't believe that I was presented with the opportunity to ever choose the mode to open the file with. How am I able to open in text mode so the csv module will handle it? I've noticed that InMemoryUploadedFile has a file attribute which seemed useful, but it's … -
You do not have permission to view this directory or page in Django app on Azure
I am trying to deploy from my github repo a Django app. The deployment is successful, and when I check from the Azure command line, the files are there. However, when I access the website I get the following message: "You do not have permission to view this directory or page." Can anyone help? -
Django - Migrating models to MySQL database
ProgrammingError at /blog/ (1146, "Table 'project.blog_category' doesn't exist") Not sure what's causing this. Migrating data doesn't seem to populate the MySQL DB. I've also tried syndb. root@watchtower:/project# ./manage.py migrate Operations to perform: Synchronize unmigrated apps: messages, staticfiles, watchtower Apply all migrations: blog, contenttypes, sessions, admin, auth Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: No migrations to apply. Can I manually create the DB tables? Here is the model.py from django.db import models from django.db.models import permalink class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() posted = models.DateTimeField(db_index=True, auto_now_add=True) category = models.ForeignKey('blog.Category') def __unicode__(self): return '%s' % self.title @permalink def get_absolute_url(self): return ('view_blog_post', None, { 'slug': self.slug }) class Category(models.Model): title = models.CharField(max_length=100, db_index=True) slug = models.SlugField(max_length=100, db_index=True) def __unicode__(self): return '%s' % self.title @permalink def get_absolute_url(self): return ('view_blog_category', None, { 'slug': self.slug }) -
Celery skips task by an hour
But when I just left my computer open and run celery that runs a task every 50 seconds overnight and I saw some skips like for 1 hour. It's actually executing nice except for the unexpected skips. Why is this happening? How to resolve this? Here's an example of the skipped log in my worker -l info 2016-11-03 10:13:36,264: INFO/MainProcess] Task core.tasks.sample[8efcedc5-1e08-41c4-80b9-1f82a9ddbaad] succeeded in 1.062010367s: None [2016-11-03 11:14:19,751: INFO/MainProcess] Received task: core.tasks.sample[ca9d6ef4-2cdc-4546-a9fb-c413541a80ee] Here's an example of the skipped log in my beat -l info [2016-11-03 10:13:35,199: INFO/MainProcess] Scheduler: Sending due task core.tasks.sample (core.tasks.sample) [2016-11-03 11:14:19,748: INFO/MainProcess] Scheduler: Sending due task core.tasks.sample (core.tasks.sample) Here is my task code: # 5 seconds @periodic_task(run_every=timedelta(**settings.XXX_XML_PERIODIC_TASK)) def sample(): global GLOBAL_CURRENT_DATE if cache.get('XXX_xml_today_saved_data') is None: cache.set('XXX_xml_today_saved_data', []) saved_data = cache.get('XXX_xml_today_saved_data') ftp = FTP('xxxxx') ftp.login(user='xxxxx', passwd='xxxxx') ftp.cwd('XXX') date_dir = GLOBAL_CURRENT_DATE.replace("-", "") try: ftp.cwd(date_dir) except: ftp.cwd(str(int(date_dir) - 1)) _str = StringIO() files = ftp.nlst() if (GLOBAL_CURRENT_DATE != datetime.now().strftime("%Y-%m-%d") and files == saved_data): GLOBAL_CURRENT_DATE = datetime.now().strftime("%Y-%m-%d") cache.delete('XXX_xml_today_saved_data') return print files print "-----" print saved_data unsaved = list(set(files) - set(saved_data)) print "-----" print unsaved if unsaved: file = min(unsaved) # modified_time = ftp.sendcmd('MDTM '+ file) print file ftp.retrbinary('RETR ' + file, _str.write) xml = '<root>' xml += _str.getvalue() xml += … -
How to reload Django settings in unittests
I have a a Django project with different settings for different sites and environments. I'm trying to write unittests that check functionality across these different settings, but I'm running into a lot of weird bugs because Django isn't designed to allow easily "reloading" its settings. I'm currently using this function to dynamically reload settings: def load_settings(site=None): os.environ['SITE'] = site or settings.SITE_PRIMARY settings_module = 'myproject.settings' new_settings = importlib.import_module(settings_module) imp.reload(new_settings) return new_settings My settings.py is structured to load a sub-settings module based on the "SITE" environment variable, like: settings.py: import os, importlib ... default Django settings ... SITE = os.environ.get('SITE', 'primary') _module_name = 'myproject.site_%s' % SITE _module = importlib.import_module(_module_name) _module = reload(_module) globals().update( (k,v) for k,v in _module.__dict__.iteritems() if not k.startswith('_')) This seems a bit hackish, but has worked everywhere except unitests. I've found that depending on the order of the unitests, and how individual tests load different site settings, loads will fail. Is there a better way to do this? I'm aware of Django's override_settings decorator, but I need something like that that can load an entire settings module, and on-demand, at arbitrary points within a method. -
Django Webfaction 'Timeout when reading response headers from daemon process'
My Django app on my production server hosted on Webfaction was working fine until I just tried to restart it after pushing a change to the settings.py file. I ran apache2/bin/restart as usual. Then I tried to access my app on my browser, and I got a 504 Gateway timeout. I looked into the mod_wsgi logs and saw this: [Thu Nov 03 23:46:53.605625 2016] [wsgi:error] [pid 8027:tid 139641332168448] [client 127.0.0.1:34570] Timeout when reading response headers from daemon process 'myapp' : /home/<me>/webapps/<myapp>/<ProjectName>/<myapp>/wsgi.py What does this mean and how do I fix it? The only thing I changed in the settings.py file was moving some variable names around. I can still successfully interact with the app with python2.7 manage.py shell But I can't get to it on the web, nor use the API. -
Django Registration Redux adding widgets
I am trying to add widgets for adding class for inputs, for example if you use form.as_p or form|crispy it is ok but I want to use forms seperately like form.username, form.password etc. class RegistrationForm(UserCreationForm): required_css_class = 'required' username = forms.CharField(widget=forms.TextInput({ 'class':'sgn','placeholder': 'Unique name' })) email = forms.EmailField(widget=forms.EmailInput({ 'id':'id_email','class':'sgn','placeholder': 'Email' })) password = forms.CharField(widget=forms.PasswordInput({ 'class':'sgn','placeholder': 'Password' })) re_password = forms.CharField(widget=forms.PasswordInput({ 'class':'sgn','placeholder': 'Re Password' })) class Meta: model = User fields = (UsernameField(), "email") This is in registration/forms.py I little bit customize with adding widgets, after that it shows what I expected but doesn't save on database, I tried different ways but I didn't !!! -
How to make a pdf link in Sjagno
I'm extremely new to Django and I was hoping someone could help me add a link to my website which allows someone to download a pdf file. The pdf file is located here: static/files/offline_reg_form.pdf and I have no idea what the URL should be in the urls.py file or the view in the views.py file. I have looked around but nothing is working as I want it too. Any help would be great, thanks! -
Make all Django URLs case insensitive?
I'm working with a fairly large Django setup with 70+ applications within it. One recent request is to make it work with case insensitive URLs. Is there any way to get every app within it to use case insensitive URLs without having to alter the urls.py for each app? It's a fairly straightforward process to get a single app to be case insensitive (e.g.: Case insensitive urls for Django? ), but given the number of apps, is there a better (e.g.: middleware) way of doing this? -
What if I forget to use 'cleaned_data' in Django?
I am wondering, what happens if I forget to use 'cleaned_data' like on a form below and let the user enter letters in the html form: models.py class MyClass(models.Model): myField = models.CharField(max_length=75,blank=True) forms.py class MyClassForm(ModelForm): reference = forms.ModelMultipleChoiceField(queryset=MyClass.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) Is my Database still save? -
Crontab python django issue
The following works as expected: python /usr/share/str8RED/manage.py getLiveResults However, nothing happens when I use the following cronjob: */1 * * * * python /usr/share/str8RED/manage.py getLiveResults I can get cronjab working and running every minute with echo "Hello World". Any help would be appreciated, many thanks, Alan. -
django admin populate fields in inlined models
i am working on a website for a private school, in witch i have to calculate for each month a total price based on list of chosen services. i am using 3 models class Eleve(models.Model): ... class Tarif(models.Model): eleve = models.OneToOneField(Eleve, on_delete=models.CASCADE) assurance = models.PositiveSmallIntegerField(default="1000") frais = models.PositiveSmallIntegerField(default="750") transport = models.PositiveSmallIntegerField(default="350") garde = models.PositiveSmallIntegerField(default="250") ... class Facture(models.Model): month_choices = ( ('9', 'Septembre'), ('10', 'Octobre'), ... ) eleve = models.ForeignKey(Eleve, on_delete=models.CASCADE) month = models.CharField(max_length=3, choices=month_choices) frais = models.BooleanField(default=True) transport = models.BooleanField() garde = models.BooleanField() total = models.PositiveSmallIntegerField() avance = models.PositiveSmallIntegerField() date = models.DateField(default=datetime.datetime.today) Eleve == Student in admin.py, the models Tarif and Facture are display as TabularInline like so: class TarifInline(admin.TabularInline): model = Tarif formset = RequiredInlineFormSet can_delete = False class FactureInline(admin.TabularInline): model = Facture what i need is when i check transport or/and garde, the total field should be filled with the sum of current_eleve.tarif.transport and cuurent_eleve.tarif.garde the field total must be stored in database for some cases.. any help would be appreciated -
jenkins "django-not-available" pylint error (django project on raspberry pi)
I've a pretty specific problem and I can't find a solution in the net. Description I've a local django project and I use tox to run some tests et al pylint. running tox command local works like charm. Recently I use a raspberry pi (model b with jessi lite) as local server and I installed jenkins (and postgresql) to use it as CI. Problem All tests with jenkins (e.g. flake8, pep257, dodgy, coverage...) performing well only pylint has some problem. It can't import any django modules. I get about 100 errors like this: E: 13, 0: Unable to import 'django.conf' (import-error) It also shows "normal" warning and stuff like that but it ends with the following line: F: 1, 0: Django is not available on the PYTHONPATH (django-not-available) But in my tox.ini I've specified install_requires=[ "Django==1.8.15", ... ] Any ideas would be appreciated! If any information missing please ask :) Thanks in advance -
django rest type error fields is not JSON serializable
I am trying to implement simple rest api with django. However I am getting the following error, //model.py from django.db import models # Create your models here. class Event(models.Model): name = models.TextField() type = models.TextField() location = models.TextField() start_hour = models.TextField() end_hour = models.TextField() creator = models.TextField() class Meta: verbose_name = "Event" verbose_name_plural = "Events" def __str__(self): return self.name //serializer.py from rest_framework import serializers from .models import Event class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('name', 'type') how to deal with this? -
Creating a header image with bootstrap
To learn more about web development I am trying to make a webapp. My first challenge is working out how to interface Django, Bootstrap and custom css. I am trying to create a nav bar consisting of an image where I can overlay a profile image, a link to your account settings etc. I would like it to look like the following image: Essentially it would be a responsive nav bar where the height is set at say 200px and the width is always 100% of your browser window. I have got my custom css as below: .wide { width:100%; height:100%; height:calc(100% - 1px); height:200px; background-size:cover; } And I have tried to interface this with the HTML below: <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <link rel="stylesheet" href="/static/mapvpage/style.css"> </head> <body> <div class="wide"> <img src="{% static "mapvpage/BananaFarm.jpg" %}" alt="My image"/> <div class="col-xs-5 line"><hr></div> <div class="col-xs-2 logo">Logo</div> <div class="col-xs-5 line"><hr></div> </div> </body> </html> I have got the image into my page. However I cannot work out how to change the image size in any way. I am also a bit confused as to how custom CSS interacts with Bootstrap and Django. Can I just use … -
cannot import an app to url.py
I have a events app and I have to use its views.py in the urls.py so, I am trying to import it but urls.py does not see it. I have already define it on INSTALLED_APPS like following, INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'events.apps.EventsConfig', ] but when I tried to import it I am working on virtualenv, maybe the problem is releated with that but I can't figure it out. -
Best practice/help to redirect in Django after form submit
Django noob here, don't quite understand the concepts, so not able to get any help from similar questions from StackOverflow. I have a form with only one dropdown, if the submit is pressed the value of the dropdown should be forwarded to the next page. So that the content is customised depending on the drop-down. How does one redirect, after the post to the next page with arguments? is it even correct to use "HttpResponseRedirect(reverse"? views.py def appStart(request, institution): #so something with institution return render(request, 'application/SectionStart.html', {'content':{'if you would like to contact me emial','email@email.com'}}) def ReviewMyView(request): form_class = ApplicationSelectInstituation if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): for field, value in form.cleaned_data.items(): return HttpResponseRedirect(reverse('appStart', args=(value,))) #return HttpResponseRedirect(reverse('view_blog', args=(), kwargs={'institution': value})) #return HttpResponseRedirect(reverse('appStart'), {'institution': value}) #return HttpResponseRedirect(reverse('appStart'), institution=value) return render(request, 'application/appmyreview.html', { 'form': form_class }) urls.py urlpatterns = [ url(r'^xxx/(?P<institution>\d+)$', appStart, name='appStart'), url(r'^myapp$', ReviewMyView, name='review'), ] -
django - send email
i want to send an email via django view. setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'user@gmail.com' EMAIL_HOST_PASSWORD = 'somepass' EMAIL_USE_TLS = True views.py send_mail( 'Subject here', 'Here is the message.', 'user@gmail.com', ['user@domain.com'], fail_silently=False ) I'm recieving an error: [Errno 10061] No connection could be made because the target machine actively refused it Please advise, i can't figure out what I'm doing wrong. -
cannot find module name - Python, Flask
I am having some issues with my modules in Python. I've spent over a hour reading how to solve the Issue but nothing seems to work. Whenever I try to start my server with, I receive this error message: no module named home I have tried setting up my folder as the root folder for the project but that didn't resolve the issue. I tried the trick with Invalidated Caches/Restart but it didn't work. I also tried with deleting my ~/.PyCharm2016.2 but it didn't work as well. Deleting the .idea folder and restarting PyCharm didn't help as well. Here is how my files are structured: flask-blog | .idea .flask_blog | | | files .home .env | views.py The Branch which says only files contains the rest of my python files, while in the home folder, I have only placed the views.py file. Here is my code: init.py: from flask import Flask app = Flask(__name__) app.config.from_object('settings') from home import views # This is the import that doesn't work manage.py located in the root directory: import os, sys sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from flask.ext.script import Manager, Server from flask_blog import app manager = Manager(app) manager.add_command('runserver', Server( use_debugger = True, use_reloader = True, host = … -
Using a context manager in wsgi.py
Situation: We have a Django application that has an ordinary wsgi.py module which creates an application (WSGIHandler) when run. The application is served via Nginx. Problem: There should be some startup code that executes once when the wsgi.py executes. Specifically code that: Does some initialization of the interpreter process before django is initialized. Does some things after django is initialized (django.setup() is called) like call_command(). Current solution: The way I implemented it by now is with a context manager (see code below). It feels a bit awkward at first glance, but it works well. Question: When will Nginx start to serve requests to the WSGIHandler (pointed to by the module variable application)? Will it start serving request data to application before __exit__() has finished? My (uneducated) guess would be, that Nginx executes wsgi.py in script-style top-to-bottom once, and after that's done, accesses the module variable named application. Anybody knows better? How does this setup look to you? Valid? Unorthodox, but technically valid? Problematic? wsgi.cfg [uwsgi] module = wsgi:application wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_test.settings") from startup import StartupContext with StartupContext(): application = get_wsgi_application() startup.py class StartupContext(): def __enter__(self): """Run before django.setup() is called.""" setup_logging_for_python_process() def __exit__(self, exc_type, … -
How do I fix my url patterns for django 1.10.2?
This is my url pattern: from django.conf.urls import url from django.contrib import admin from school.views import home urlpatterns = [ url(r'^admin/', admin.site.urls), #url(r'^$', home, name = 'home') #school.views.home') #url(r'^$', 'main.views.home', name = 'school_home') url(r'^$', home, name = 'home') ] urlpatterns = [ #'django.contrib.auth.views', url(r'^login/$', 'login', {'template_name': 'login.html'}, name = 'school_login'), url(r'^logout/$', 'logout', {'next_page': 'school_home'}, name = 'school_logout'), ] For some reason I keep getting these awful errors that just won't let my application run when I ask it to runserver. Here is my traceback error message: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03F292B8> Traceback (most recent call last): File "C:\Python34\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python34\lib\site-packages\django\core\management\commands\runserver. py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Python34\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Python34\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Python34\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 14, in c heck_url_config return check_resolver(resolver) File "C:\Python34\lib\site-packages\django\core\checks\urls.py", line 24, in c heck_resolver for pattern in resolver.url_patterns: File "C:\Python34\lib\site-packages\django\utils\functional.py", line 35, in _ _get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\lib\site-packages\django\urls\resolvers.py", line 313, in ur l_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python34\lib\site-packages\django\utils\functional.py", line 35, in _ _get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\lib\site-packages\django\urls\resolvers.py", line … -
Django Commands import error
I am trying to practice custom-management-commands as per the following link: https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/ I got it setup and working and got the following working: self.stdout.write("Hello world!") I then tried to run the following code: from django.core.management import BaseCommand from xmlsoccer import XmlSoccer #The class must be named Command, and subclass BaseCommand class Command(BaseCommand): # Show this when the user types help help = "My test command" # A command must define handle() def handle(self, *args, **options): xmlsoccer = XmlSoccer(api_key='HCDIGHNIVXVKZOOVBPVMYPGIQKNNIYXVFJEPBLVYZFQVQMGTCE', use_demo=False) teams = xmlsoccer.call_api(method='GetAllTeamsByLeagueAndSeason', seasonDateString='1617', league='English League Championship') self.stdout.write("Hello world!") But I get the following error: ImportError: No module named xmlsoccer However, this import line works perfectly when it is in the views.py. I assume I have a setup issue, could someone point me in the correct direction? -
Django - How many DB hits cause using a model method, which access another object via Foreign Key, in template?
Especifically, calling a model method that access another object via Foreign Key, and calling this method several times in a for-loop. Let's assume the following models as an example: class Shipment(Model): discount = FloatField() def getProducts(self): return Product.objects.filter(shipment = self) class Product(Model): shipment = ForeignKey(Shipment) baseCost = IntegerField() def getDiscount(self): return self.baseCost * self.shipment.discount A Shipment offers a discount percentage to each Product. The Product model has a method to get how much money it's discounting, but to calculate that, it has to access it's Shipment. (Of course, we could just store the discount as a field in Product to never calculate it again, but let's ignore that for the sake of this question). Now, let's assume we have the following view: def viewShipments(request): context = { "shipments": Shipment.objects.all(), } render(request, "template.html", context) We simply pass all the Shipments as context. Finally, let's assume the following template: {% for shipment in shipments %} {% for product in shipment.getProducts %} {{ product.getDiscount }} {% endfor %} {% endfor %} If my understanding of how Querysets work is correct, during the first loop it hits the DB to fetch all Shipments (so, 1 hit so far). Then in the second loop it …