Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hoveron button producing error inside Django
my_path is a field in models.py where my_path = models.FilePathField('some/path/) in my template I have the following where on hover on the button will play an audio. <audio id='vaSound' controls="controls" preload="auto"> <source src={{ my_path }}></source> </audio> <button style="font-size:10px"><i id='someIcon' class="fa fa-play"> </i></button> I verified that my_path points to an audio file (/static/audio/someaudio.ogg), in fact the same path works outside of Django. But in Django I am having this error, GET http://127.0.0.1:8000/app_name/some_url/static/audio/someaudio.ogg [HTTP/1.0 404 Not Found 22ms] I tried to hard code the path but same error? -
How can i process a multiple files from a file field in django?
I am trying to figure out how to process multiple files from a filefield in Django. I have figured out how to add the "multiple" attribute to the form field. What I need to do now is loop through each file and perform some logic. I have a form with fields like this (in views.py): class RecipientListForm(forms.Form): name = forms.CharField() recipients = forms.CharField( required=False, widget=forms.Textarea(attrs={'placeholder':"James Jameson, james.jameson@aol.com"}), label="Paste recipient information (comma-separated, in 'name, email' format)") recipients_file = RecipientsFileField( required=False, widget=forms.FileInput(attrs={'multiple':"true"}), label="Or upload a .csv file in 'name, email' format (max size %dMB)" % RecipientsFileField.MAX_FILESIZE_MB) def __init__(self, account, recipient_list=None, *args, **kwargs): super(RecipientListForm, self).__init__(*args, **kwargs) self.account = account self.recipient_list = recipient_list def clean(self, *args, **kwargs): ... RecipientsFileField looks like this (also in views.py): class RecipientsFileField(forms.FileField): MAX_FILESIZE_MB = 30 def validate(self, value): super(RecipientsFileField, self).validate(value) if not value: return fname = value.name if (value.content_type not in (('text/csv',) + EXCEL_MIMETYPES) or not re.search(r'\.(xlsx?|csv)$', fname, re.I)): raise forms.ValidationError('Please upload a .csv or .xlsx file') if value.size >= self.MAX_FILESIZE_MB * 1024 * 1024: raise forms.ValidationError('File must be less than %dMB' % (self.MAX_FILESIZE_MB,)) I have tried to perform my logic in the clean method of RecipientListForm but I have only been able to access the first file that … -
How to get user by Token in django Rest
Using: class PostSerializer(serializers.ModelSerializer): author = ExtUserSerializer(required=False, allow_null=True) class Meta: model = Post field = ('title','description','rating','author') def create(self, validated_data): return Post.objects.create(**validated_data) and @api_view(['GET']) def post_list(request, format=None): if request.method == 'GET': posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) How to modify Serializer and view to fill field author automatically -
No Reverse Match although namespace is registered
App is named foo/bar Main urls.py: url(r'^', include('foo.bar.urls', namespace="foobar")) foo/bar/urls.py: url(baz/$', foo.bar.views.BazView.as_view(), name="baz") tests.py: def test_baz_load(self): response = self.client.get(reverse("foo.bar:baz")) self.assertEqual(response.status_code, 200) And I keep getting NoReverseMatch: foo.bar' is not a registered namespace -
FileField/ImageFIeld URL isn't giving me a HTTP URL
I have this code, where partner.logo is an ImageField in the Partner model. {% for m in matches %} <img src="{{ m.partner.logo }}" alt="" /> <h2><a href="{{ m.partner.url }}">{{ m.partner.name }}</a></h2> <p>{{ m.reasons }}</p> <p>{{ m.partner.profile }}</p> {% endfor %} Now, the Django documentation says if you go m.partner.logo.url, you'll get a URL to the file. However, all I got was and that actually is the same string that I'd get from m.partner.logo. This isn't a URL, and it's not helping! I was expecting something like http://127.0.0.1:8000/uploads/road-sky-clouds-cloudy.jpg. Am I missing something? -
django-haystack custom search form field doesn't display
I am writing a custom search form using Haystack + whoosh. The search form is supposed to have two field, one is a drop down box for user to choose which model field to search for, and another charfield for taking the key word. Right now my set up for this is the following : #form.py class MultipleSearchForm(SearchForm): search_type = forms.ChoiceField(required = False, choices = SEARCH_CHOCIES) q = forms.CharField(required=False, label=_('Search'), widget=forms.TextInput(attrs={'type': 'search'})) def search(self): sqs = super(MultipleSearchForm, self).search() if not self.is_valid(): return self.no_query_found() schoice = self.cleaned_data['search_type'] if schoice: if schoice == 'Asset #': sqs = sqs.filter(asset_number = self.cleaned_data['q']) return sqs #url.py url(r'^search/', views.search_view, name='search_view'), #views.py def search_view(request): form = MultipleSearchForm(request.GET) equipments = form.search() return render_to_response('calbase/search.html', {'equipments': equipments}, {'form': form}) #search.html {% extends 'calbase/default.html' %} {% block search %} <h2>Search</h2> <form method="get" action="."> <table> {{ form.as_table }} <tr> <td>&nbsp;</td> <td> <input type="submit" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for equipment in equipments %} <p> <a href="{{ equipment.object.get_absolute_url }}">{{ equipment.object.asset_number }}</a> </p> {% empty %} <p>No results found.</p> {% endfor %} {% else %} {# Show some example queries to run, maybe query syntax, something else? #} {% endif %} </form> {% endblock %} Yet, I got something … -
Quiero saber que empleado hizo mas ventas?
Hola¡ Por favor alguien que me ayude quiero calcular que empleado hizo mas ventas en django, quiero mostrar el nombre, el numero de ventas , el promedio de ventas por hora pero no se como hacerlo. Estos datos los debo traer de la base de datos pero no se como ir sumando las ventas de un solo empleado, y compararlas con el de otro empleado. No se si me haga entender muy bien. Alguien que me ayude, se lo agradecería demasiado. -
Django custom command - Not Implemented Error
I'm trying to set up a cronjob on my Ubuntu server to run a django .py file - but I'm having trouble running the script first. I'm using the command python3 /opt/mydir/manage.py updatefm which produces the error: File "/opt/mydir/manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/site-packages/django/core/management/__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 285, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.4/site-packages/django/core/management/base.py", line 324, in handle raise NotImplementedError() NotImplementedError Can anybody enlighten my on what I'm doing incorrect? Here is my script and structure: /mydir /mydir /management __init__.py /commands updatefm.py updatefm.py class Command(BaseCommand): args = '' help = 'Help Test' def update_auto(self, *args, **options): hi = 'test' My app name is listed in settings.py as it should be. -
HTML editor with django and pycharm
i'm a newbie in developping websites and want to create one in django. to bad that pycharm doesn't have a free html viewer. Are there any alternatives? greetings -
Django FilePathField path
What do you put for the path in the FilePathField model field in Django, absolute or the directory where the file? If not absolute given that the file is somewhere inside the project how do access it using relative path? -
Python interpreter PATH oddity. Can't use django
I have three Python environments across two different interpreters. The first is the basic Python27 in my c:. The second is an Anaconda interpreter with its own environment and another environment in it's \envs\ directory. I have directed my PYTHONPATH variable to point to the Anaconda interpreter not in the \envs\ folder. I also have my PATH variable set to the scripts directory from that environment However, when I run Django, I get a message about a discrepancy in versions. I think this results from the fact that Django is using the interpreter in my C:\ directory, Python27. When I echo my PATH environment variable in cmd, this is what I see: C:\Program Files (x86)\ActiveState Komodo Edit 10\;C:\Program Files (x86)\ActiveState Komodo IDE 10\;C:\Program Files\MATLAB\R2014a\bin\win64;C:\ProgramData\Oracle\Java\javapath;c:\Program Files (x86)\Intel\iCLS Client\;c:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\IVI Foundation\VISA\WinNT\Bin;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Python27;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\WINDOWS\system32\config\systemprofile.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files (x86)\Windows Kits\10\Windows Performance Toolkit\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\MATLAB\R2016a\runtime\win64;C:\Program Files\MATLAB\R2016a\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Users\jackf_000\sw\FFMPEG\bin;C:**\Users\jackf_000\sw\Anaconda2\Scripts**;C:\cygwin64\bin;C:\Users\jackf_000\AppData\Local\Microsoft\WindowsApps; When I run python in cmd and import os to see the executable, I get the following output: C:\Users\jackf_000>python Python 2.7.9 (default, … -
How to make a fast lightweight mobile friendly django website?
I'd like to know what's a good choice to make a mobile friendly django website. I'm aware there are many frameworks which help to build responsive websites but I'd like to know how hard would be to code a really minimalistic library able to succeed with the google test and being a seo-friendly website at the same time. I guess the main question would be: can you advice me how should I start creating a really fast mobile friendly django website? -
Overriding django's CheckboxSelectMultiple widget for Awesome Bootstrap Checkboxes
If I print an instance of the following form in a template: class StrategiesForm(forms.Form): letters = MultipleChoiceField( choices=((0, 'a'),(1, 'b'),(2, 'c')), label="a_label", required=True, widget=CheckboxSelectMultiple(), ) I get: <label for="id_letters_0">a_label:</label> <ul id="id_letters"> <li> <label for="id_letters_0"> <input id="id_letters_0" name="letters" type="checkbox" value="0"> a </label> </li> <li> <label for="id_letters_1"> <input id="id_letters_1" name="letters" type="checkbox" value="1"> b </label> </li> <li> <label for="id_letters_2"> <input id="id_letters_2" name="letters" type="checkbox" value="2"> c </label> </li> </ul> This is basically bunch of inputs embedded in labels, which are embedded in list items. For Awesome Bootstrap Checkboxes to work I need to change the layout a bit. Specifically, inputs must be above the labels not in them. Also, both the input and the label need to wrapped in a div with class "checkbox checkbox-primary", instead of a li. How can I accomplish this by defining a new widget, preferably overriding django's existing? -
Add confirmation step to custom Django management/manage.py command
I created the following custom management command following this tutorial. from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from topspots.models import Notification class Command(BaseCommand): help = 'Sends message to all users' def add_arguments(self, parser): parser.add_argument('message', nargs='?') def handle(self, *args, **options): message = options['message'] users = User.objects.all() for user in users: Notification.objects.create(message=message, recipient=user) self.stdout.write( self.style.SUCCESS( 'Message:\n\n%s\n\nsent to %d users' % (message, len(users)) ) ) It works exactly as I want it to, but I would like to add a confirmation step so that before the for user in users: loop you are asked if you really want to send message X to N users, and the command is aborted if you choose "no". I assume this can be easily done because it happens with some of the built-in management commands, but it doesn't seem to cover this in the tutorial and even after some searching and looking at the source for the built-in management commands, I have not been able to figure it out on my own. -
Django get_object_or_404 is not defined
I am developing a standalone application which uses ORM of django. In my main application, I am using django's module of get_object_or_404. I have imported it with all its dependencies when I run the script, it gives me the error: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/root/standAlone/tasks.py", line 48, in task1 NameError: global name 'get_object_or_404' is not defined Here is my full script code: import django from celery import Celery from django.conf import settings settings.configure( DATABASE_ENGINE = "django.db.backends.mysql", DATABASE_NAME = "database name", DATABASE_USER = "username", DATABASE_PASSWORD = "password", DATABASE_HOST = "host", DATABASE_PORT = "3306", INSTALLED_APPS = ("myApp",) ) django.setup() from django.db import models from myApp.models import * from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render,redirect from django.shortcuts import get_list_or_404, get_object_or_404 from celery.decorators import task from celery.utils.log import get_task_logger app = Celery('tasks', broker='redis://broker_url') @app.task(name="task1") def task1(recipe_pk): recipe = get_object_or_404(Recipe, pk=recipe_pk) #error occurs here recipe.status = 'Completed' recipe.save() Does anyone know how to solve this problem? -
Cleanest way to delete stale ContentTypes?
I'd like to get rid of the follow message I get when running migrations: The following content types are stale and need to be deleted: appname | modelname Any objects related to these content types by a foreign key will also be deleted. Are you sure you want to delete these content types? It seems cleaner to encode the decision to delete or not delete in the migrations. What's the cleanest way to detect and delete stale ContentTypes as part of my migrations? Why is it not done automatically if ContentTypes are created automatically? -
Django ORM query with multiple joins
I've been trying to come up with the django version of this query and I can't seem to get it. select * from answer a left join groups g on a.group_id = g.id left join group_permissions gp on g.id = gp.group_id where gp.user_id = '77777'; I've been trying something like this: answers = Answer.objects.filter(user_id=user_id).prefetch_related('group__grouppermissions') -
Postgresql foreign key referencing -with different data types?
I was given an assignment to setup a Python+Django env with Postgresql and on the front have an Angular pulling data via Django REST service. It's a id/book/author mock DB. They wanted me to create a primary key for id (fine) but then they asked me to reference the author via foreign key to a Django user model (authors), is there a way to do that via PGADMIN? -
django: is there a way to 'import' functionality from admin site?
I am trying to build my own site but really envy some features provided by admin, like model change history, user group authentication, login and stuff. I am assuming there should be a easy way to port all that from admin since they are already there. 1. For example, does django keeps record of change history of a specific instance of a model like what we have in admin, so that I could just call it? 2. Does Django have built in user and group authentication system that, like, I just put tags on forms to specify what user group can edit it? -
Django table not created when running migrations that explicitly create table.
While experimenting with some major changes to my Django models I seriously messed everything up. Luckily, I had not committed any changes, so I dropped all the changes. The next step was to get my database back the way it was before. Eventually, I got to the point where I could successfully run the makemigrations and migrate commands without issue. However, whenever I try to visit the site, I get the ProgrammingError saying that my table topspots_notification does not exist. I have the following migration file in my migrations folder: # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-08-25 15:52 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('topspots', '0018_siteuser_share_location'), ] operations = [ migrations.CreateModel( name='Notification', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.TextField()), ('recipient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipient_notification', to=settings.AUTH_USER_MODEL)), ('sender', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='sender_notification', to=settings.AUTH_USER_MODEL)), ], ), ] Which is supposed to create that table. If I try to run this migration specifically, it will fail while trying to unapply later migrations that reference that table, since that table does not exist. I have tried deleting the above migration (where my notification table is created), and … -
How to display images in Django 1.10
i am not good in django, i use Django 1.10 and now i have problem with image displaying. I read in this version some stuff has changed but i don't get it. Here is what i have now: settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_DIR = os.path.join(BASE_DIR, 'static') TEMPLATE_DIR = os.path.join(BASE_DIR, '/templates') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_ROOT = 'C:/Users/john/myprojects/goal/website/goal/media/' MEDIA_URL = '/media/' Maybe something is unusual here and i can delete it? template: {% block content%} {{ car.name }} {{ car.photo.url }} {% endblock %} Here is folder where i have my images: C:/Users/john/myprojects/goal/website/goal/media/images And what i see instead of image on my website: /media/images/mynewcar.jpg What must i change? -
CSRF with Django, React+Redux using Axios
This is an education project, not production. I wasn't intending to have user logins as part of this. Can I make POST calls to Django with a CSRF token without having user logins? Can I do this without using jQuery? I'm out of my depth here, and surely conflating some concepts. For the JavaScript side, I found this redux-csrf package. I'm not sure how to combine it with my POST action using Axios: export const addJob = (title, hourly, tax) => { console.log("Trying to addJob: ", title, hourly, tax) return (dispatch) => { dispatch(requestData("addJob")); return axios({ method: 'post', url: "/api/jobs", data: { "title": title, "hourly_rate": hourly, "tax_rate": tax }, responseType: 'json' }) .then((response) => { dispatch(receiveData(response.data, "addJob")); }) .catch((response) => { dispatch(receiveError(response.data, "addJob")); }) } }; On the Django side, I've read this documentation on CSRF, and this on generally working with class based views. Here is my view so far: class JobsHandler(View): def get(self, request): with open('./data/jobs.json', 'r') as f: jobs = json.loads(f.read()) return HttpResponse(json.dumps(jobs)) def post(self, request): with open('./data/jobs.json', 'r') as f: jobs = json.loads(f.read()) new_job = request.to_dict() id = new_job['title'] jobs[id] = new_job with open('./data/jobs.json', 'w') as f: f.write(json.dumps(jobs, indent=4, separators=(',', ': '))) return HttpResponse(json.dumps(jobs[id])) I tried … -
django call another view using its url, inside a view
I am using django-rest-framework 3.3.2, django 1.9, python 3.5. I am working on REST API backend for an e-commerce website. User on website should be able to add items to shopping-cart and wishlist even if he/she hasn't registered yet. So I want to create dummy user object (and an Oauth2 access token) for the guest user. So I have a view like: class GuestUserAccessTokenView(views.APIView): def get(self, request, format=None): user, password = self.__create_guest_user() # assume it creates a dummy User object payload = { "grant_type": "password", "username": user.email, "password": password } url = 'http://localhost:8000/o/token/' # calling url of TokenView of django-oauth-toolkit basic_authentication = self.__get_basic_auth() headers = {'content-type': 'application/x-www-form-urlencoded'} r = requests.post(url=url, data=payload, auth=basic_authentication, headers=headers) # i get error on this line response_dict = { 'access_token': r.json()['access_token'] } return Response(response_dict) def __get_basic_auth(self): oauth_application = Application.objects.get(name='web') # from oauth2_provider.models import Application basic_auth = HTTPBasicAuth(oauth_application.client_id, oauth_application.client_secret) # from requests.auth import HTTPBasicAuth return basic_auth When I call this view, I get the following error: Traceback (most recent call last): File "/Users/amrullahzunzunia/virtualenvs/flyrobe_new/lib/python3.5/site-packages/requests/packages/urllib3/connection.py", line 137, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "/Users/amrullahzunzunia/virtualenvs/flyrobe_new/lib/python3.5/site-packages/requests/packages/urllib3/util/connection.py", line 91, in create_connection raise err File "/Users/amrullahzunzunia/virtualenvs/flyrobe_new/lib/python3.5/site-packages/requests/packages/urllib3/util/connection.py", line 81, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, … -
Django application decomposition advice
Good day. I am a Django developer with some experience. I am familiar with different best practices and controversial points of view. Recently, while working on one project, I struggled for a while when I came upon one giant existing app. The issue isn't resolved and I'm still in progress of thinking. Your advices will be really appreciated! The issue itself: project has a giant application, let's name it "Directory". The application is big and serves to multiple purposes: 1) Provides basic content types for the whole project 2) Provides some helping structure entities (like, Categories, Attributes etc) 3) Handles User Area dashboard views. 4) Handles basic front-end public views. 5) Handles search. I really don't like how big it is right now. While thinking on possible way of decomposition, I came up with multiple variants. Most likely it'll be the best to do it like this: I can create a dashboard app, a search app, a frontend functionality app (serves for displaying public content). The biggest stopper right now is the model layer. The thing is, all of the possible apps mentioned above depend literally on the same models. In my opinion, it'll be wrong to put these models … -
How to write common implementation of __str__ method for all my models in Django?
I want all my models to override __str__ method in similar fashion: class MyModel1(models.Model): name = models.CharField(max_length=255) def __init__(self): self.to_show = 'name' def _show(self): if hasattr(self,self.to_show): return str(getattr(self, self.to_show)) else: return str(getattr(self, 'id')) def __str__(self): return self._show() class MyModel2AndSoOn(models.Model): another_param = models.CharField(max_length=255) # same implementation of `__str__` but with another_param I do not want to repeat the same code for all my models so I tried inheritance: class ShowModel(models.Model): name = models.CharField(max_length=255) def __init__(self): self.to_show = 'name' def _show(self): if hasattr(self,self.to_show): return str(getattr(self, self.to_show)) else: return str(getattr(self, 'id')) def __str__(self): return self._show() class MyModel1(ShowModel): another_param = models.CharField(max_length=255) class MyModel2(ShowModel): another_param = models.CharField(max_length=255) but it messes with id of MyModel1 and MyModel2 by replacing id with a pointer to ShowModel. How to write common implementation of __str__ method for my models without inheritance or how to prevent treating ShowModel class as a Django model?