Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom django management command to populate countries with pycountry AttributeError
I am trying to create a custom command to populate countries in admin from pycountry package. But I am getting confusing AttributeError that says I am not referencing it correctly. Can someone help me to identify my mistake? Project settings for management command is: market/ manage.py address/ __init__.py models.py management/ __init__.py commands/ __init__.py market_populate_countries.py views.py Management command code: from __future__ import absolute_import import sys from optparse import make_option from default.core.loading import get_model from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = "Populates the list of countries with data from pycountry." option_list = BaseCommand.option_list + ( make_option( '--no-shipping', action='store_false', dest='is_shipping', default=True, help="Don't mark countries for shipping"), make_option( '--initial-only', action='store_true', dest='is_initial_only', default=False, help="Exit quietly without doing anything if countries were already populated."), ) def handle(self, *args, **options): try: import pycountry except ImportError: raise CommandError( "You are missing the pycountry library. Install it with " "'pip install pycountry'") if Country.objects.exists(): if options.get('is_initial_only', False): # exit quietly, as the initial load already seems to have happened. self.stdout.write("Countries already populated; nothing to be done.") sys.exit(0) else: raise CommandError( "You already have countries in your database. This command " "currently does not support updating existing countries.") countries = [ Country( iso_3166_1_a2=country.alpha2, iso_3166_1_a3=country.alpha3, iso_3166_1_numeric=country.numeric, printable_name=country.name, name=getattr(country, 'official_name', … -
Make a specific option selected in Django template
I have defined a form in Django like this: class ageForm(ModelForm): class Meta: model = Age fields = ['name', 'age'] My model related to this form is this: class Age(models.Model): name = models.ForeignKey(Name) age = models.IntegerField(max_length=3, null=True, blank=True) def __str__(self): return self.name My view for template for this form: class AgeView(View): def get(request, id): template_name = 'list.html' name_age_form_class = ageForm return render(request, template_name, {'age_form': name_age_form_class}) I am initiating the form in template like this: {% for f in name_age_form_class %} {{ f }} {% endfor %} I want to make a specific name selected in the name selection field. How can i achieve this ? EDIT: I don't want to set initial value while instantiate the form. I want to this in template. -
How to use javascript package with Django?
I'm a beginner and not understanding how to use the Slick javascript library with Django: https://github.com/kenwheeler/slick I have installed the package and put it in the node_module folder. I have modified the template to include CDN links in the header, as instructed, and I placed the Slick element in the HTML. However, the formatting is not showing up. Is there anything else I need to do to get Django to recognize this package? Do I need to modify files other than my template file? -
django admin not showing some css and form features
I copied my django (v1.10) source code to my Apache server, and executed the python manage.py collectstatic, it copied 420 files to /var/www/sitename/mainwork/static. The website's css itself works fine, but the admin does not show some features! . It also does not show some links of the forms: (the first snapshot is the way it is supposed to be) the way it supposed to be: the way it is with missing link: what is causing this problem? Thanks in advance. (if any code is required just tell me to add here) -
Session key changes during a POST in Django Unit Tests
I'm saving the session_key to an object to associate data to anonymous users. In Unit Tests, I'm trying to use the Test Client to set a fixed key, but the key changes during a POST request. An example: // tests.py def test_post(self): session_key = "123" session = self.client.session session['session_key'] = session_key session.save() response = self.client.post('/post-url/') self.assertEquals(response.content, session_key) # AssertionError: b'str60i3gjpvru8f7mellsdf2y3xd2jgh' != '123' // views.py @require_http_methods(['POST']) def ajax_post(request): return HttpResponse(request.session.session_key) Based on this comment, I tried to include another GET response response = self.client.get('/') before the session_key was changed, but it doesn't seem to help. What am I doing wrong? -
Not able to open http://localhost:8000/ but opening in public ip ngnix Django
I am new to Python Django. I am working on a Django project using Ubuntu, nginx and python, Django. Question is that : I am able to open the application with URL name in browser like http://example.com but the application is NOT opening locally in server with localhost:8000 or public-ip:8000, below is the output of related commands: $ wget -O- http://localhost:8000 --2017-01-17 13:15:30-- localhost:8000 Resolving localhost (localhost)... 127.0.0.1 Connecting to localhost (localhost)|127.0.0.1|:8000... connected. HTTP request sent, awaiting response... 404 NOT FOUND 2017-01-17 13:15:30 ERROR 404: NOT FOUND. $ netstat -lan | grep 8000 tcp 0 0 127.0.0.1:8000 0.0.0.0:* LISTEN $ elinks http:// localhost:8000 Page not found at / Page not found (404) Request Method: GET Request URL: http:// localhost:8000/ Raised by: mainpages.views.index No tenant for hostname "localhost" You're seeing this error because¤you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Please help. -
Passin gvalue from a jquery slider into Django views.py
How can I pass a value selected from a jQuery slider into Django views.py. Namely I've made a slider using (which probably needs to be edited to do what I want): $(function() { $( ".slider").slider({ min: 0, max: 1, value: 0.3, step: 0.05, }) }); with the relevant html: <form method="get"> <div name="slider" class="slider"></div> <input type="submit" value="submit"> </form> When the user hits the submit button I would like to pass the value in the slider to views.py using something like: value = request.GET['slider'] I've seen similar questions online, however, I'm new to web development and therefore don't quite understand how to adapt them to my case. -
How to check that an uploaded file is a valid Image in Django
I have an ImageField in one of my models so that users can upload an image. When a user submits an upload form, I want to verify that the file in question is a fully valid and displayable image. I tried using PIL to verify that the image was in fact authentic, but using from PIL import Image Image.open(model.file) Image.verify() No matter what file I give it though, it always throws an exception. Anyone know of an easy way to verify the file? -
How to deduce a state from foreign objects states and use it to as a read-only field?
Let's say I have a Book that has many Page. A Page can be either read or unread. I store that value in a state field. I can deduce the book state by looking at its pages: all pages unread means the book is unread at least one page unread means the book is started all pages read means the book is read. I could store and update the book state each time a page state changes, but this is not my point. Instead I'd like to find a way to use that book virtual state as if it was a kind of read-only field. I'd use it to filter results on the website, on the admin, etc... What's the pattern of this? And how to properly implement it in Django? -
Django-like way to handle OAuth users
I am wondering what is the most Django-like way to handle Django's user model together with OAuth users. Django users require a password to be set, but for OAuth users the field needs another value. I found this article that circumvents the problem by filling in a hash: https://github.com/joestump/python-oauth2/wiki/Logging-into-Django-w--Twitter Specifically I want users to log in and then save some settings, like their preferred languages. Using a different model to associate oauth users with these settings seems kind of weird to me. Especially because then it becomes difficult to assign users to a group. Also a user might become an admin and get a password so they can log into the admin interface at a later point. There might also be security issues that I am not thinking of. -
django-wysiwyg-redactor doesn't apply any settings
I have a trouble with django-wysiwyg-redactor working on Django 1.8. I need to make toolbar fixed at admin site but RedactorField doesn't apply any setting that I try to use. I tried all matters that are explained in the docs, but I haven't changes at my Admin site even on the simpliest setting - 'maxWidth':'100px': 1) Write settings at settings.py as explained here enter link description here REDACTOR_OPTIONS = {'maxWidth': '100px'} 2) Use RedactorField at models.py in model definition (also as at the docs example): announce = RedactorField(redactor_options={'maxWidth': '150px'}) (I tried also with redactor_settings as it is in the source code instead of redactor_options but it throws and error 'init() got an unexpected keyword argument 'redactor_settings'') 3) Use RedactorEditor at my forms.py as widget: announce = forms.CharField(widget=RedactorEditor(redactor_settings={'maxWidth': '100px'})) (I tried also with redactor_settings as it is in the source code instead of redactor_options but it throws and error 'init() got an unexpected keyword argument 'redactor_settings'') But any of them doesn't work. I will appreciate any help! I there is not enough info, I can show more source code. -
How to query subclasses of Page in wagtail?
In home page and search page, I'd like to list all kinds of pages with different detailed display. I wrote the code below following the document: from wagtail.wagtailcore.models import Page from my.models import ArticlePage, GalleryPage, VideoPage, SharedLinkPage PAGE_TYPES = (ArticlePage, GalleryPage, VideoPage, SharedLinkPage,) class HomePage(Page): subpage_types = list(PAGE_TYPES) def get_context(self, request): context = super(HomePage, self).get_context(request) context['posts'] = Page.objects.type(PAGE_TYPES).live() context['recent_posts'] = Page.objects.type(PAGE_TYPES).live() return context In this case, I can only get [<Page: 1>, <Page:2>], what I really want is [<ArticlePage: 1>, <GalleryPage:2>]. My question is the same in search page but with search query: Page.search('something', ArticlePage) Would be better: search_backend.search('something').types(PAGE_TYPES).live() -
returned more than one Version Exception when read other's file
Django Version: 1.8.16 Python Version: 2.7.5 All document is public, you can read all of it even you are not login, but when you login, if you don't have super admin permission, the error message come out Request Method: GET Request URL: http://rtd.chan.net/en/latest/ Django Version: 1.8.16 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Version -- it returned 2! Exception Location: /www/rtd/lib/python2.7/site-packages/django/db/models/query.py in get, line 338 Python Executable: /www/rtd/bin/uwsgi Python Version: 2.7.5 Python Path: ['.', '', '/www/rtd/lib64/python27.zip', '/www/rtd/lib64/python2.7', '/www/rtd/lib64/python2.7/plat-linux2', '/www/rtd/lib64/python2.7/lib-tk', '/www/rtd/lib64/python2.7/lib-old', '/www/rtd/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7', '/usr/lib/python2.7', '/www/rtd/lib/python2.7/site-packages'] I try to Google the exception message, the coding solution is to change get to filter, it cause another exception and I don't think it's the real solution, how to fix it? -
Django Python - Ldap Authentication
I am currently work on Django Python . My aim to authenticate the user from the Ldap directory . I do have my python code to access the ldap directory and retrieve the informations. Code : import ldap try: l = ldap.open("ldap.forumsys.com") l.protocol_version = ldap.VERSION2 username = "cn=read-only-admin,dc=example,dc=com" password = "password" l.simple_bind(username,password) except ldap.LDAPError,e: print e My doubt is that , how would i implement this in my django ? . How do use these code in django and to implement it ? Thanks in advance -
Django query caching through a ForeignKey on a GenericRelation
Using a GenericRelation to map Records to Persons, I have the following code, which works correctly, but there is a performance problem I am trying to address: models.py class RecordX(Record): # Child class .... class Record(models.Model): # Parent class people = GenericRelation(PersonRecordMapping) def people_all(self): # Use select_related here to minimize the # of queries later return self.people.select_related('person').all() class Meta: abstract = True class PersonRecordMapping(models.Model): person = models.ForeignKey(Person) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Person(models.Model): ... In summary I have: RecordX ===GenericRelation===> PersonRecordMapping ===ForeignKey===> Person The display logic in my application follows these relationships to display all the Persons mapped to each RecordX: views.py @rendered_with('template.html') def show_all_recordXs(request): recordXs = RecordX.objects.all() return { 'recordXs': recordXs } The problem comes in the template: template.html {% for recordX in recordXs %} {# Display RecordX's other fields here #} <ul> {% for map in record.people_all %}{# <=== This generates a query every time! #} <li>{{ map.person.name }}</li> {% endfor %} </ul> {% endfor %} As indicated, every time I request the Persons related to the RecordX, it generates a new query. I cannot seem to figure out how prefetch these initially to avoid the redundant queries. If I try selected_related, … -
split multiple selections into separate records in a Django model
I have two django models connected by a foreign key. The second model has a CharField that allows for multiple selections. Is there a way upon saving that I can create a record for each selection, instead of having a singular entry with the selected ids concatenated together. I'm guessing I need to create a custom save method for the second model, but I can't figure it out. -
`'utf8' codec can't decode byte 0x99 in position 0: invalid start byte. Hex?
I am creating an email/messaging web app to practice django, and I am saving message text data as a unicode string (<type 'unicode'>). Most of the time, this works, but when i try to retrieve the data, occasionally i will get the following error: 'utf8' codec can't decode byte 0x99 in position 0: invalid start byte. You passed in '\x99\x8c\x1f\xcf\xd1\xafp\xda9\x82\xb8\xf3\x19(\xed\xad\xd2E\x87\xc1\xe3d\xeeT\xbc\xd7\xb1\x9fJ\xb9\x19\x1e\x07x>\xb9\xa3\x8c,\xc3\xca\x8eg\xd4\x91\x10(\x17T%d\x9e\xfe\x0b"/\xa5\x9d\x06\xb7\xc1AU\xf0{\x8a\xbd@\xe1\x94S\x9f\xf0\xb0\xc1\nw\x0e!\x8fG!\x97\xc5\xc30/\x9b\xce\xe9\x1aQ\x97\x9f\xec\x8e\x99Y\xe3\xa5\xd9\x9b\x11\xa8\xc9\xdf\xaf-!\xc5\xfd\xa2\xdb\x04\xabO\x0b\xf9y\x9d\x96tM\x1e\xc4\x9a\x87' ()` I am not sure how to convert this string of what appears to be hex values (i have no idea why it looks like this, it only does this for some messages, and it seems very very random) back to unicode or something usable. .encode() and .decode functions are not solving the problem, and I have exhausted every method and resource that I could find. Any help would be greatly appreciated :) -
Django 1.8 migrating CMS
I am trying to migrate my Django app to Django 1.8 and specifically to django-cms==3.4.1. Since I am coming from Django 1.4 I had to get rid of South first following Migration from South. So I created new migration scripts but I have an error when ./manage.py migrate hits the cms application. It keeps complaining about existing tables or relations and it's correct they exist in my database but I need to migrate CMS to the newer version so I don't know how to make this happen without complaining about existing cms_ tables. Here is the kind of errors I'm getting: $ python manage.py migrate --fake-initial ... return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "cms_pageuser" already exists What can I do to make Django migrate cms without complaining about existing relations ? -
jquery autocomplete is undefined
I'm trying to implement an autocomplete search input in Django using jquery. I have seen quite a few similar questions on this issue, but nothing solved my specific case. In my base.html class I have a head that looks like this: <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> Then in my home.html class, which extends base.html I have the following in head: <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all"/> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> Then in the <body> of my home.html file I have: <input name="object-search"class="form-control "id="search"> <script type="text/javascript"> $(function() { $("#search").autocomplete({ source: "/api/", minLength: 1, }); }); </script> When going to home.html I get the following error: -
ImageField url returns an empty string
I am trying to add pictures to my Django web app. I have a model in my models.py which that looks something like this: # models.py class foo(models.Model): bar = models.ImageField() title = models.CharField(max_length = 140) ''' other things below ''' For my settings.py I have the following code: # settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' and for my urls.py I have the following: # urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) I am rendering my view using the following views.py function: # views.py def renderFoo(request): context = { 'foos' = foo.objects.all(), ''' other models here ''' } return render(request,'path/to/page.html',context) but then on my template when I try to get the image URL by typing: {% for foo in foos %} <img src='{{foo.bar.url}}'\> <h1>{{foo.title}}</h1> {% endfor %} I have the title showing up but the image doesn't show up. When I check the page's source code I have the image tag appering as: <img src=''\> Any idea on why this is happening? -
Accessing a field through a GenericForeignKey in a django template formset
Suppose I have the following model: class Holder(models.Model): other_field = models.BooleanField(default=True) object_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() object = GenericForeignKey('object_type', 'object_id') Then in views.py, I have created a formset for Holder, and passed it to the template: formset = modelformset_factory(Holder, fields =('other_field',)) data = {'formset': formset} In template.html, I want to access one field of the related object. I have tried with: {% for form in formset %} {{ form.object.related_field }} {{ form.other_field }} {% endfor %} Then, other_field is displayed but related_field is not. How could I display the value in related_field in the template? -
GenericRelation vs. JSONField
In my application a number of different kinds of Records can be mapped to a Person. In my initial implementation, I made each record inherit from an abstract base class and used GenericRelations to manage the whole thing. The code is a bit complicated, but it works: models.py class Person(models.Model): ... class PersonRecordMapping(models.Model): person = models.ForeignKey(Person) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class RecordParent(models.Model): people = GenericRelation(PersonRecordMapping) class Meta: abstract = True class RecordA(RecordParent): w = ... x = ... class RecordB(RecordParent): y = ... z = ... And so on. (As I tried to indicate, each type of Record is quite different from the others, with very different fields on each model.) As I built out the application around these models, I began to wonder if this approach would scale, as I will eventually have a number of RecordX-type classes. I began to consider how to get all of the Records in one table with a column indicating which kind of Record each one was, and eventually discovered the new-ish JSONField. At first blush, it seemed to be exactly what I was looking for to simplify this whole thing. class PersonRecordMapping(models.Model): person = models.ForeignKey(Person) record … -
Pulling and showing data from associate table in Django rest framework
I am trying to build an API using Django Rest Framework. Which i am not familiar with. I want to know how I can pull data using references and associated tables. I have three models Users, Company and Reviews. I am storing and Auth_token in user table and I want to be able to pull reviews by a certain user by putting the auth token in the address bar. my models are class User(models.Model): user_name = models.CharField(max_length=45) email = models.CharField(max_length=255) auth_Token = models.CharField(max_length=100,default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.user_name class Company(models.Model): company_name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.company_name class Review(models.Model): title = models.CharField(max_length=64) rating = models.IntegerField(blank=False) summary = models.TextField(max_length=10000) ip = models.GenericIPAddressField() company = models.ForeignKey(Company) user = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.title I am currently able to pull reviews using following apiview: class ReviewView(APIView): def get(self,request): reviews = Review.objects.all() serializer = ReviewSerializer(reviews, many=True) return Response(serializer.data) and the following serilaizer: class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = ('title','company', 'rating', 'summary','user') Please ignore the indentations. However this results in me getting back … -
Django-tenant-schemas: accessing data across all schemas
I'm using the django-tenant-schemas package for a Saas project. My project is for property maintenance companies and so it tracks service issues on a property. When there's a maintenance issue, the user creates a Ticket. The ticket outlines the problem and what needs to happen to get it fixed. Generally, the user will call up a repair person to fix the issue - a vendor. I want to provide a portal for the vendor to view these tickets, do their work, and complete the tickets without them seeing all the other data in the database. That's easy - and I've completed that with the Django sites feature. Here's what I can't figure out: is it possible for a vendor to access tickets across all schemas? For example, if I have 3 users (three different property maintenance companies) who all use the same vendor, and are all issueing this vendor tickets, I would like for the vendor to log into one portal and see the tickets from all three users. I don't want the vendor to have to log into 3 separate portals to see all the tickets. Is this possible? -
Multiforloop in template Django
I have a list in my view with is constains lists of month days like [1,2,3,4,5,6,7,...] of twelve months. In my template I am trying to do this {% for month in month_list %} {% for day in month %} {{ day }} {% if month == "the first list"(that is where the problem dwells) and day == 16%}<p>Martin Luther King, Jr. Day Observance.</p>{% endif %} My problem is getting the first array index. I know there is something like {% ab in list %} {{ ab.0 }} {{ ab.1 }} but I do not have two lists. Any help?