Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework list_route() behaves like detail_route()
I'm trying to add a method on my ReadOnlyModelViewSet with list_route() decorator. class CompaniesViewSet(viewsets.ReadOnlyModelViewSet): queryset = Companies.objects.all() model = Companies @list_route() def clean(self, request): context = {} if request.method == 'GET': url_clean = Companies.clean_url(request.query_params.get('url')) context = { 'clean_url': url_clean } return Response(context) But the URL resolves as: ^api/ ^v1/ ^companies/(?P<pk>[^/.]+)/clean/$ [name='company-clean'] So it looks like @list_route() behaves just like @detail_route(). I have another viewset with the @list_route() decorated method which is correctly resolved: ^api/ ^v1/ ^contacts/clean/$ [name='contact-clean'] My DRF's version is 3.1.3, Django: 1.8.5 -
How to set "BINARY" to VARCHAR column definition for MySQL with django.models?
I have simple model following. from django.db import models class ItemAttr(models.model): name = models.CharField(max_length=255) value = models.CharField(max_length=255) converted to CREATE TABLE `webapp_itemattr` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(255) NOT NULL, `value` varchar(255) NOT NULL ) Now, I want to distinguish between uppercase and lowercase in "name" field. How do this? My goal is to get to following SQL. CREATE TABLE `webapp_itemattr` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(255) BINARY NOT NULL, `value` varchar(255) NOT NULL ) apply ALTER TABLE SQL directly, it is work. but at django unit test, this MODIFY SQL is not applyed. ALTER TABLE webapp_itemattr MODIFY name VARCHAR(255) BINARY NOT NULL; -
Django. Get object from template
I have read the django documentation and I don't see clear how to get the objects from a template. I'd like create a "download button" that write the table to csv file. device.html .... <a href="/directory/download" class="btn btn-primary btn-xs" style="float: right;">Download</a> <table class="table table-striped"> <thead> <tr> <th>Device</th> <th>Description</th> <th>Location</th> <th>Model</th> </tr> </thead> <tbody> {% for r in result %} <tr> <td>{{r.name}}</td> <td>{{r.description}}</td> <td>{{r.locationName.value}}</td> <td>{{r.model}}</td> </tr> {% endfor %} </tbody> </table> ... views.py def download(request): import csv # print("downloading...") response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="report.csv"' writer = csv.writer(response) # write table to csv file return response Thanks and Regards, -
How to git clone a repository to heroku
I have a git repository called first-blog and it contains a python-django project named as myproject. I tried to clone this repository to heroku using the command (firstproject)aparna@aparna-HP-Notebook ~/Documents/myproject $ git clone https://github.com/heroku/first-blog.git I got an error Cloning into 'first-blog'... Username for 'https://github.com': AparnaBalagopal Password for 'https://AparnaBalagopal@github.com': remote: Repository not found. fatal: repository 'https://github.com/heroku/first-blog.git/' not found How can I solve this error? -
phpMyAdmin and Django on same Apache server when redirecting to phpmyadmin I get 403 error access forbidden
I'm running a django project on opensuse and working fine and I installed phpMyAdmin before was working fine before django installation, I then configured django and phpMyAdmin to run on same apache server and added this configuration of phpMyAdmin to apache Alias /phpMyAdmin /srv/www/hotdocs/phpMyAdmin/ <Directory /srv/www/htdocs/phpMyAdmin> Options Indexes FollowSymLinks MultiViews ExecCGI Require all granted </Directory> <Location /phpMyAdmin> SetHandler None </Location> I get this error when redirecting to url/phpMyAdmin Access forbidden! You don't have permission to access the requested directory. There is either no >index document or the directory is read-protected. If you think this is a server error, please contact the webmaster. Error 403 If Anybody can help me in this error!! Thank you very much -
comparision between django model version control pacakges
I need to implement django model history version & compare view. I found there are packages like django-reversion, django-simple-history, django-revisions to implement model history version and django-reversion-compare for compare view. My requirement focus mainly on implementing version history & compare view outside admin. Can someone share the feedback on these packages? I found few references like http://treyhunner.com/2011/09/django-and-model-history/, but it's still not clear to me. I am interested to know the ease & limitations of implementing these packages. -
Storing JSON web token in hidden input value
Im looking at building a Django web application that requires authentication but does not require cookies or javascript to be enabled on the client. Would there be any issue with creating a JSON web token and placing this within a hidden input value, checking and validating this value on all post requests? All traffic will be over HTTPS. Similar to this topic, but doesn't mention JSON web tokens specifically. The accepted answer seems to touch on issues that JSON web tokens have solved; How to do stateless (session-less) & cookie-less authentication? -
Reverse for 'registration_register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am trying to make a link in the sidebar of my Person model as persons. For that I made a templatetags folder where my member_template_tags.py: from django import template from member.models import Person register = template.Library() @register.inclusion_tag('member/person_list.html') def get_person_list(): persons= Person.objects.all(), return {'persons': persons} and my view file: class PersonListView(generic.ListView): model = Person context_object_name = 'persons' my person_list.html: {% extends 'member/base.html' %} {% block content %} <h2>Members</h2> <table> <tr> <th>sl.</th> <th>Name and Position</th> <th>Photo</th> <th>Organisation & Address</th> <th>Contact</th> </tr> {% for person in object_list %} <tr> <td>{{forloop.counter}}.</td> <td>{{person.name}}<br> {{person.present_position}} </td> <td><a href="{% url 'member:person-list' %}"> <img src="{{ person.photo_url|default_if_none:'#'}}" class="img-responsive"> </a></td> <td> {{person.organization}}<br> {{person.address}} </td> <td> {{person.tele_land}}<br> {{person.tele_cell}}<br> {{person.email}} </td> </tr> </table> {% endblock %} and in base.html, sidebar code is: <div class="col-sm-3 col-md-2 sidebar"> {% block sidebar_block %} {% get_person_list %} {% endblock %} </div> When I tried it gives following traceback: Template error: In template /home/ohid/test_venv/alumni/member/templates/member/person_list.html, error at line 0 Reverse for 'registration_register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 : {% extends 'member/base.html' %} 2 : 3 : 4 : 5 : <h2>Members</h2> 6 : <table> 7 : 8 : <tr> 9 : <th>sl.</th> 10 : <th>Name and Position</th> Traceback: … -
Models.CharField() Size
I was wondering what will be the size of the data let's say: name = models.CharField(max_length=255) Then the input is "John Doe" What will be the size of the table row let's say? ----------------- | id | name | ----------------- | 1 | John Doe | ----------------- TAKE NOTE: PostgreSQL will be the database -
django registration redux ignoring changes in templates
I've been struggling with django registration redux over the past two weeks.. I'm using the templates the were provided in the documentation but I've made a couple of changes like adding crispy forms and changing the button and some other stuff but the problem is that none of these changes are being shown on http://127.0.0.1:8000/accounts/register or any other link. I'm using djang registration redux 1.4, django 1.8, python 2.7.10 Any help appreciated, thanks -
Allow only editing the current selected Foreign Key in Django Admin
So currently I have something like this: Model: class ConfirmEmail(models.Model): report = models.ForeignKey(Report) owner = models.CharField(max_length = 100) emails = models.ManyToManyField(Sdm) Admin: @admin.register(ConfirmEmail) class ConfirmEmailAdmin(admin.ModelAdmin): change_form_template = 'admin/phone/index.html' readonly_fields = ('owner',) filter_horizontal = ('emails',) list_display = ('owner','report') I create these object in code - meaning I set the report object. But what I would like in the Django admin is if I could allow a user to edit that report object but only the one set. They would be allowed to change it (so hopefully the drop down menu would no longer be there) so the nice pencil icon would still be there, but things like that "+" icon would be gone. And this is not to say the user can't edit all reports, its just that in the ConfirmEmail Admin they can only view that specific report attached to it. I've been smacking away at this and can't seem to get it to work. I would also be inclined to just have the current Report Form embedded into the ConfirmEmail form - but don't know how I would go about doing that. -
Terminating Django channels
I currently have a website, where when the user clicks a button, it sends a socket which then runs a web scraping program and returns the results to the user as it goes along. However, I also want to add a "terminate" button to stop this function but am not sure how to go about doing so. Any help would be great, thanks! -
how to separate authentication class of functions in a Django rest framework ViewSet
how to separate authentication class of functions in a Django rest framework ViewSet I have create a UserViewSet, it has 2 functions: 1.list all users registered(permission_classes should be IsAuthenticated); 2.register a new user(permission_classes should be AllowAny). --------------------views.py----------------------------------- class UserViewSet(ViewSet): @list_route(methods=['get'], permission_classes = [IsAuthenticated, ]) def list(self, request): ... ... @list_route(methods=['post'], permission_classes = [AllowAny, ]) def register(self, request): ... ... --------------------urls.py----------------------------------- users_list = views.UserViewSet.as_view({ 'get': 'list', 'post': 'register' }) urlpatterns = [ url(r'^$', users_list, name='users-list'), ... ... ] --------------------settings.py--------------------------------- REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } ... ... command line to register a user: curl -H "Content-Type: application/json" -X POST -d '{ "email":"user@example.com"}' http://192.168.30.45:8000/users/ Response: {"detail":"Authentication credentials were not provided."} the "permission_class" of my "register" function is set to "AllowAny", still need Authentication? why this happen? -
pip install with django_ckeditor
I am new to web development. I am using conda + pip to manage the packages and virtual environment. And I'm confused with those package management and maybe I'm using them in the wrong way. Currently I have used command pip install django-ckeditor to install the package. Then I saw the ckeditor in both pip list and conda list dill 0.2.5 py27_0 django-ckeditor 5.1.0 <pip> django-photologue 3.5.1 <pip> If I directly add 'ckeditor' to the Django installed app file and try to import like from ckeditor.fields import RichTextField. The ckeditor cannot be resolved. Therefore I tried the other way to work around like pip download django-ckeditor And drag the ckeditor folder to the project root, and it works. However it shouldn't be the right way to import those plugins and I'm getting messy with those sources with the project files. -
How to run python script on a web server?
I have been learning Django, the python webframework, so that I can use python scripts in my website. While I've learned the basics, I'm still a little unsure as to how to actually implement my own scripts into the website. When I run the script on my computer, it spits out a small graph. Can somebody please help explain to me how to get the graph to be displayed on a web page in Django? -
Django sorl-thumbnail : upload_to doens't work?
In sorl-thumbnail document, it says that I can use upload_to option like below. from django.db import models from sorl.thumbnail import ImageField class Item(models.Model): image = ImageField(upload_to='whatever') This is my photo model. from django.db import models from django.core.urlresolvers import reverse from album.models import Album # from album.fields import ThumbnailImageField from sorl.thumbnail import ImageField def upload_location(instance, file_name): return "{}/{}/{}/{}".format( "album", instance.album.day, instance.album.week, file_name ) class Photo(models.Model): album = models.ForeignKey(Album) description = models.CharField(max_length=100, blank=True) image = ImageField(upload_to=upload_location) uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['uploaded_at'] def __str__(self): return str(self.id) def get_absolute_url(self): return reverse( "album:photo_detail", kwargs={ "slug": self.album.slug, "pk": self.id } ) When I upload the new photo, browser doesn't show my image. When I inspect element through Chrome dev tool, it shows like this : <img src="http://localhost:8000/media/cache/3f/e3/3fe3837648ba06585f2f5c505f5d501a.jpg" width="" height=""> But according to my upload_location, the image is supposed to be stored sort of `media/album/ ~~~ '. cache folder even not exist.... I don't know what's wrong... -
How do I test a method in Django which closes the database connection?
I have a long running Python process which uses the Django ORM. It looks something like this: import django from django.db import connection from my_app import models def my_process(): django.setup() while (True): do_stuff() connection.close() models.MyDjangoModel().save() Sometimes do_stuff takes a really long time, at which point I was running into an error where my MySql connection timed out because the database server killed the connection as idle. Adding the connection.close() line forces django to get a new connection every time and fixes that issue. However, I am testing this process using a django.test.TestCase, and calling connection.close causes those tests to fail, as django's TestCase class wraps the test in a transaction, and closing the connection within that transaction causes the transaction to break and raises a django.db.transaction.TransactionManagementError. One attempt at resolving this issue I tried is setting the CONN_MAX_AGE database parameter and calling connection.close_if_unusable_or_obsolete instead, but the transaction also changes the connection's autocommit setting from the settings' default value of True to False which in turn causes close_if_unusable_or_obsolete to try and close the connection anyway (https://github.com/django/django/blob/master/django/db/backends/base/base.py#L497). I guess I could also mock connection.close in test so it does nothing, but that seems kind of hacky. What is the best way to … -
One out of four radio buttons hidden
I hae four sets of radio buttons, each set wrapped in a div. On firefox for windows I see all four sets of radio buttons. My coworker only sees three set in firefox. Both of us see only 3/4 sets in chrome. In linux I don't see the offending set of radio buttons regardless of the browser. Any ideas? Whenever I have a problem like this in Python it turns out that I used a keyword for something. The html is here: https://github.com/melvyniandrag/SentimentLabeler/blob/master/mysite/polls/templates/polls/detail.html the css is here: https://github.com/melvyniandrag/SentimentLabeler/blob/master/mysite/polls/static/polls/detail.css If you git clone https://github.com/melvyniandrag/SentimentLabeler.git cd mysite python manage.py runserver open 127.0.0.1:8000 login a/password you will see the problem. -
Secret key is there though it is saying no secret key in django
When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 14, in <module> from django.db.migrations.executor import MigrationExecutor File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 6, in <module> from .loader import MigrationLoader File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 10, in <module> from django.db.migrations.recorder import MigrationRecorder File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 9, in <module> class MigrationRecorder(object): File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 23, in MigrationRecorder class Migration(models.Model): File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 24, in Migration app = models.CharField(max_length=255) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1081, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 113, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. This is my development settings """ Django settings for kgecweb project. Generated by 'django-admin startproject' using Django 1.8. … -
Django - Get unused/all options in a select tag
I'm using a POST form, but I'm not sure if that is the best way. I have this: <form name='main' method="POST" action={{submit}}> <select class='form-control' size=10 id="test" name='test' multiple> <option>Test1</option> <option>Test2</option> <option>Test3</option> <option>Test4</option> </select> <input type="submit"/> </form> If I use request.POST.getlist('test'), I get only the options that are highlighted. However, I would like all the options that are in the select tag. ex. def myapp_submit(request): #This method doesn't exist print request.POST.getalloptions which would give me all options regardless if they are selected or not. ['Test','Test2','Test3','Test4'] why would I do this? I'm using Jquery to use two select lists that you can select options from one list and put it in another. When the user submits I want to know which options remain in each select list. -
How to colorize Django test results in OSX terminal?
I'd like to colorize the Django test outputs with the nice visual queues of "green=pass, red=failure" font colors in the terminal, similar to what I get with rails/rake (e.g. ....F..FF.... where F is red for failure and the dots are green for passing unit tests). Anyone know how to do this easily? Is there a bash_profile or python import or setting? -
How can I tell in my view, which of the 2 forms' fields were filled?
I want to display both form1 and form2 on a web page. If form2 is filled (if success == True), I want my view to not execute if form1.is_valid: (which gives errors). How can I access the value of success in views.py? forms.py class Form1(forms.Form): .... .... def clean(self): .... .... class Form2(forms.Form): .... .... def clean(self): .... success = False views.py def my_view(request, element_pk): .... .... if request.method == POST: form2 = Form2(request.POST) form1 = Form1(request.POST) if form2.is_valid(): .... if form1.is_valid(): .... else: form2 = Form2() form1 = Form1() -
django-summernote loading static files in UI
I'm new to django-summernote and even new to django all together. Trying out django-summernote with basic setup and currently it doesnt do much other than display the editor. I'm having issue serving up the static contents, such as css and javascript files. I've try the Template config to summernote in pip install dir (site-packages) without any luck. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [... Any idea how to fix this issue? Here is my config in settings.py: SUMMERNOTE_CONFIG = { # Using SummernoteWidget - iframe mode 'iframe': False, # or set False to use SummernoteInplaceWidget - no iframe mode # Using Summernote Air-mode 'airMode': False, # Use native HTML tags (`<b>`, `<i>`, ...) instead of style attributes # (Firefox, Chrome only) 'styleWithTags': True, # Set text direction : 'left to right' is default. 'direction': 'ltr', # Change editor size 'width': '90%', 'height': '480', # Or, set editor language/locale forcely 'lang': 'en-US', # Customize toolbar buttons 'toolbar': [ ['style', ['style']], # ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', # 'strikethrough', 'clear']], ['fontname', ['fontname']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], #['height', ['height']], #['table', ['table']], ['insert', ['link', 'picture', 'video', 'hr']], ['view', ['fullscreen', 'codeview']], ['help', ['help']], #['highlight', ['highlight']], ], # Set common … -
django sorl-thumbnail doesn't work even very simple example
Env : Max OSX 10 ,Python3.5, Django 1.10 I exactly follow below things, pip install sorl-thumbnail Add sorl.thumbnail to my settings.INSTALLED_APPS python manage.py makemigrations and python manage.py migrate <my_app> And my very very simple template : {% extends 'chacha_dabang/skeleton/base.html' %} {% load thumbnail %} {% block content %} {% thumbnail "http://www.nextgen-gallery.com/wp-content/uploads/2008/12/abend.jpg" "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} {% endblock %} But it doesn't even work! When I check html elements through Chrome development tool, no img tag at all! Only my base.html elements exists.... Anything that I missed? -
Django Admin list_filter by reverse lookups
I have 3 models involved. two of them related to the third one by two foreign keys. in QuxAdmin I wish to create a list filter by Bar and Foo entities related to the qux entity. class Foo(models.Model): a = models.ForeignKey(Bar, related_name='a') b = models.ForeignKey(Bar, related_name='b') class Bar(models.Model): c = models.ForeignKey(Bar, related_name='c') d = models.ForeignKey(Bar, related_name='d') class Qux(models.Model): name = models.CharField(max_length=128) I'm using django 1.8.4 and python 3.5.2 How can I solve it?