Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why PyCharm writes "No module name os"?
In the file "settings.py" writes error the "No module named os" I have installed django 1.10 MacBook-Pro-Ahmed:desktop HeartProgrammer$ cd dj_project MacBook-Pro-Ahmed:dj_project HeartProgrammer$ python3 -m venv env MacBook-Pro-Ahmed:dj_project HeartProgrammer$ source env/bin/activate (env) MacBook-Pro-Ahmed:dj_project HeartProgrammer$ pip install django==1.10 Collecting django==1.10 Using cached Django-1.10-py2.py3-none-any.whl Installing collected packages: django Successfully installed django-1.10 You are using pip version 8.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. (env) MacBook-Pro-Ahmed:dj_project HeartProgrammer$ django-admin startproject mysite (env) MacBook-Pro-Ahmed:dj_project HeartProgrammer$ cd mysite (env) MacBook-Pro-Ahmed:mysite HeartProgrammer$ python manage.py startapp blog (env) MacBook-Pro-Ahmed:mysite HeartProgrammer$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. September 29, 2016 - 22:38:23 Django version 1.10, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. My folders hierarchy image What I'm doing wrong? -
Getting Error with Django Phone Number Form Field
I'm building a Django form that includes a phone number field. I've been referring to these two SO questions to understand how to do it: 1, 2. I've created this form field: class ContactForm(forms.Form): phone = forms.RegexField( regex = r'^\+?[1-9]\d{1,14}$', #regex = r'\+?\d{10,14}$', error_messages = {'required', 'Phone number required'}, widget = forms.TextInput(attrs={'class': 'form-control'}) ) I display the field in my template: <div> <label for="id_phone">Your Phone Number</label> {{ form.phone.errors }} {{ form.phone }} </div> I understand what the regexes are doing and they look correct to me. However, I'm getting this error if I use either one of them: ValueError at /business/contact/ dictionary update sequence element #0 has length 8; 2 is required ... Exception Location: /srv/http/swingerpixels.com/venvs/dev/local/lib/python2.7/site-packages/django/forms/fields.py in __init__, line 125 (stacktrace...) widget = forms.TextInput(attrs={'class': 'form-control'}) super(RegexField, self).__init__(max_length, min_length, *args, **kwargs) super(CharField, self).__init__(*args, **kwargs) messages.update(error_messages or {}) (end of stacktrace) Can anyone see what's causing this error? It seems to be caused by the regexes. -
Could anyone check if my relations between models are correct?
Some Companies represent some PlaceTypes (Gym, pool, etc.), and these PlaceTypes have some criterias for evaluation (Staff, cleanness, etc.) class Companies(models.Model): name = models.CharField() class PlaceTypes(models.Model): name = models.CharField() # Gym, pool, etc. company = models.ForeignKey(Companies) class Criterias(models.Model): name = models.CharField() # Staff, cleanness, etc. place_type = models.ForeignKey(PlaceTypes) class Ratings(models.Model): company = models.ForeignKey(Companies) criteria = models.ForeignKey(Criterias) votes = models.PositiveIntegerField() total = models.PositiveIntegerField() So, there is some kind of duplication between Companies -> PlaceTypes -> Criterias and Companies <- Ratings -> Criterias. Is it ok? -
Simple Django Aggregation - Optimization
I'm reading the beginnings of annotating and aggregating and I'm wondering which way is best to complete the following situation: You want to count the number of authors for each book in a queryset. The tutorial suggests the following with annotate: Book.objects.annotate(Count('authors')) My question is, why do it this way when you can accomplish this with model instance methods: #models.py class Book(models.Model): authors = models.ManyToManyField(Author) def author_count(self): return self.authors.count() #views.py books = Book.objects.all() #template.html {% for book in books %} {{ book.author_count }} {% endfor %} Is one situation better than the other? Are there optimization benefits I'm missing? -
Propagate http abort/close from nginx to uwsgi / Django
I have a Django application web application, and I was wondering if it was possible to have nginx propagate the abort/close to uwsgi/Django. Basically I know that nginx is aware of the premature abort/close because it defaults to uwsgi_ignore_client_abort to "off", and you get nginx 499 errors in your nginx logs when requests are aborted/closed before the response is sent. Once uwsgi finishes processing the request it throws an "IO Error" when it goes to return the response to nginx. Turning uwsgi_ignore_client_abort to "on" just makes nginx unaware of the abort/close, and removes the uwsgi "IO Errors" because uwsgi can still write back to nginx. My use case is that I have an application where people page through some ajax results very quickly, and so if the quickly page through I abort the pending ajax request for the page that they skipped, this keeps the client clean and efficient. But this does nothing for the server side (uwsgi/Django) because they still have to process every single request even if nothing will be waiting for the response. Now obviously there may be certain pages, where I don't want the request to be prematurely aborted for any reason. But I use celery … -
how to generate a responsive PDF with Django?
how to generate a responsive PDF with Django?. I want to generate a PDF with Django but i need that is responsive, that is to say, the text of the PDF has that adapted to don't allow space empty. for example to a agreement this change in the text, then, i need to adapt the to space of paper leaf. -
Django internationalization Urls giving 404 error
I am trying to work with Django Translation, I am following docs and tutorials. The fallback language code "en-us" I can see the homepage but when I try to change the languages in browser address bar, I am getting 404 error. The error is Using the URLconf defined in yogavidya.urls, Django tried these URL patterns, in this order: So my urls.py is : Urls.py : # -*- coding: utf-8 -*- from django.conf.urls import include, url from django.contrib import admin from django.conf.urls.i18n import i18n_patterns from .views import home, home_files admin.autodiscover() urlpatterns = [ url(r'^(?P<filename>(robots.txt)|(humans.txt))$', home_files, name='home-files'), ] urlpatterns += i18n_patterns( url(r'^$', home, name='home'), url(r'^admin/', include(admin.site.urls)), ) My settings.py : ... from django.utils.translation import ugettext_lazy as _ INSTALLED_APPS = [ 'yogavidya', .... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', .... ] ROOT_URLCONF = 'yogavidya.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', ], }, }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGES = [ ('en', _('English')), ('tr', _('Turkish')), ] LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I created and compiled messages, my views.py # -*- coding: utf-8 … -
Django: Managing several related test states in Django
Using Django: I need to create (by inserting some rows into an empty (is it really created empty?) DB) a state X of the DB. Then I need to run a test against this state. Then I need to create a state Y by applying some modifications to state X and run another test against Y. Then I may need to create more test states based on X and/or Y and run tests for them. How to do this with Django testing framework? -
Django FileField not including uploaded file in form output request
I am having trouble getting access to a simple uploaded file which I need to parse without saving it. Since the file does not need to be saved I have not made a model for it. All other threads on this state the html form encoding type, name tag are the primary reasons why request.FILES is not appearing-- I have addressed these and still there is no request.FILES being captured. forms.py class DataExportForm(forms.Form): docfile = forms.FileField(label='Select a template',help_text='Extracted info will be returned') HTML {% csrf_token %} <tr><th><label for="id_docfile">Select a template:</label></th><td><input id="id _docfile" name="docfile" type="file" /> <button type="submit" name="action">Upload</button> <br /><span class="helptext">Zip file wil l be returned with data</span></td></tr> </form> </body> </html> views.py ..... ...... if request.method=='POST': form=DataExportForm(request.POST, request.FILES) if form.is_valid(): #Code runs OK till here but request.FILES does not exist. groupList=extractTemplateNames(request.FILES['file'].read()) .... I guess if I get it working I may find the file not in request.FILES['file'] but in request.FILES['docfile'] but at this point request.FILES does not exist. Any tips to solve this would be appreciated. -
Django admin: list_display/search_fields foreign key of a foreign key in admin view
I have a question for django programmer that should be quite easy but at the moment I cannot figure out how to solve. I have these three models (I simplify as much as I can): class Nations(models.Model): label = models.CharField(max_length=200) iso2 = models.CharField(max_length=2, unique=True) class Cities(models.Model): label = models.CharField(max_length=200, null=True) country_code = models.ForeignKey(Nations, to_field='iso2', on_delete=models.SET_NULL, null=True, verbose_name='Nation') class Person(models.Model): username = models.CharField(max_length=200, blank=False) city = models.ForeignKey(Cities, on_delete=models.SET_NULL, null=True, blank=True) As you can see, Person model is just connected with Cities model. What I need to do is to set PersonAdmin class in order to add in the admin view a column showing Nations.label value and make it searchable. In the example below I called this field city__country_code__label, just to make you figure out what I mean (but of course it doesn't work because there is no country_code object in Person model). class PersonAdmin(admin.ModelAdmin): list_display = ('id', 'username', 'city', 'city__country_code__label') ordering = ('username',) raw_id_fields = ('city',) search_fields = ['username', 'city__label', 'city__country_code__label'] [...] how can I ask Django to do this? Thanx in advance! -
Django Aggregate ManyToMany fields
Say I have Django models like so: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): authors = models.ManyToManyField(Author) What's the best way to get the the number of books each author created, possibly ordered? -
django-chozen in django admin: new item in inline forms does not work
I have the following example : models.py class Book (models.Model): title = models.CharField(u'Book Title', max_length=300) class AthoursBook(models.Model): chapter = models.IntegerField(max_length=2) booksathours = models.ManyToManyField(Book, through=u'Athour', verbose_name=u'Athours on book') class Athour(models.Model): name = models.CharField(u'Athour Name', max_length=300) book = models.ForeignKey(Book) admin.py class AthourAdmin(admin.ModelAdmin): inlines = [BookInline] extra = 0 class BookInlineForm(ModelForm): class Meta: model = Book widgets = { 'book': Select(attrs={'class': 'chozen-css'}), } class BookInline(admin.TabularInline): model = Book form = BookInlineForm extra = 0 I want to use django-chosen in django admin but it doesn't work on add new button (on the inline form) as shown on the picture... any ideas? I also tried chosen on its own with no luck... I mean is this possible? - inlines follow my manytomany model which is implemented this way for many other reasons... -
Apache 2.4 with mod_wsgi: 403 Forbidden, don't have permission to access /calbase on this server
So I am trying to deploy my django project on a windows server, using apache 2.4 with mod_wsgi and pythong 3.4. Before I configure httpd.conf and just try start apache with mod-wsgi installed, it works and show me that "it works" page. then I did the following configuration in httpd.conf: # Change Python path used by the server. WSGIPythonPath “/EquipmentCalibration” # Make calls to http://localhost/ refer to the Python/WSGI-script located at the specified location. WSGIScriptAlias / /EquipmentCalibration/equipcal/wsgi.py # Make calls to http://localhost/static refer to the specified folder. Alias /static/ /EquipmentCalibration/static Alias /media/ /EquipmentCalibration/media <Directory /EquipmentCalibration/static> Require all granted </Directory> <Directory /EquipmentCalibration/media> Require all granted </Directory> <Directory /EquipmentCalibration/equipcale> <Files wsgi.py> Require all granted </Files> </Directory> And then try to go to localhost:8080 (I changed the port from 80 to 8080), I got this error saying: Forbidden You don't have permission to access / on this server. And below is the relevant error.log. [Thu Sep 29 15:05:25.171920 2016] [mpm_winnt:notice] [pid 7756:tid 528] AH00456: Apache Lounge VC10 Server built: Jul 9 2016 11:59:00 [Thu Sep 29 15:05:25.171920 2016] [core:notice] [pid 7756:tid 528] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Thu Sep 29 15:05:25.171920 2016] [mpm_winnt:notice] [pid 7756:tid 528] AH00418: Parent: Created child process 7524 … -
Django - Changing order_by on click
Using Django and I would like to change the order of the display of the objects on click without refreshing the page. my model class IndexView(generic.ListView): template_name = 'movies/index.html' page_template = 'movies/all_movies.html' context_object_name = 'all_movies' model = Movie def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update({ 'all_genres': Genre.objects.all(), 'our_pick': Movie.objects.get(pk=259) }) return context def get_queryset(self): return Movie.objects.all() And this is my index.html <menu class="menu"> <ul> <li><a href="#">Newest</a></li> <li><a href="#">Most Popular</a></li> </ul> </menu> on clink on Newest, the query will become: Movie.objects.all().order_by('release_date') and on click on Most popular, the query will become: Movie.objects.all().order_by('popularity') How can I achieve that without refreshing the page? any help would be appreciated! -
Reverse model admin custom URLs
Inside my admin.py file I have: def get_urls(self): urls = super(TextAdmin, self).get_urls() my_urls = patterns('', url( r'customfunc1', customfunc2, name='customfunc23', ), ) return my_urls + urls Which will enable the following URL: http://localhost:8000/admin/text/customfunc1 Which will execute function customfunc2. My question is now how would I reference this URL through doing reverse? I tried: reverse("admin:text_customfunc1") reverse("admin:text_customfunc2") reverse("admin:text_customfunc3") reverse("text:customfunc1") But none of those work. -
Django not updating object in classmethod. Very strange
I don't understand this. This model has a classmethod that looks for all addresses and updates them, but it is not working: views.py address = Address.objects.get(id=address_id) default = request.data.get("default", address.default) if default.lower() == "true": print "default is true" Address.set_default_address(address.id, address.client) else: print "default is false" address.default = default print "in view -> address.id - address.default: %s - %s" % (address.id, address.default) Address.set_default_address: class Address(models.Model): ... default = models.BooleanField(default=False) @classmethod def set_default_address(cls, address_id, client): client_addresses = Address.objects.filter(client=client) print "client_addresses: %s" % client_addresses for address in client_addresses: if address.id != address_id: print "address is set to False - address id: %s" % address.id address.default = False address.save() else: print "address is set to True! - address id: %s" % address.id address.default = True address.save() print "classmethod address.id - address.default: %s - %s" % (address.id, address.default) The classmethod is designed to be called if the new address has to be set to default=True and change all other addresses to default=False. The printed output looks like this: default is true client_addresses: [,] address is set to False - address id: 1 address is set to True! - address id: 2 classmethod address.id - address.default: 2 - True in view -> address.id - address.default: 2 … -
django prepopulated fields inheritance
I knew that there were limitations on pre populated fields, https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields "prepopulated_fields doesn’t accept DateTimeField, ForeignKey, nor ManyToManyField fields." but you will note it says nothing about OneToOne fields (implied or explicit) nor does it reference base classes. So it was a little disconcerting to find that these don't seem to work, either. That messes with my models, of course, because I wanted to use the slug from the common parent. The child has no fields of its own that would be suitable for a slug. I assume I am not the first one to come across this issue, although both my Google and SO searches came up empty. Is there a best practices workaround in this situation, (like importing the parent into the child's admin.py?) or do I need to refactor my models to get rid of inheritance just to make my slugs work? -
Template View - kwargs and **kwargs
I am reading about Template views through a tutorial and some of the code kind of confused me. The author used this code sample from django.utils.timezone import now class AboutUsView(TemplateView): template_name = 'about_us.html' def get_context_data(self, **kwargs): context = super(AboutUsView, self).get_context_data(**kwargs) if now().weekday() < 5 and 8 < now().hour < 18: context['open'] = True else: context['open'] = False return context The thing that confused me syntactically was this statement context = super(AboutUsView, self).get_context_data(**kwargs) if we already are receiving **kwargs then why are we passing it to the super function with ** (double start). I think we should pass it as context = super(AboutUsView, self).get_context_data(kwargs) this is the contextMixin which is receiving this call. class ContextMixin(object): """ A default context mixin that passes the keyword arguments received by get_context_data as the template context. """ def get_context_data(self, **kwargs): if 'view' not in kwargs: kwargs['view'] = self return kwargs From what I have read is that the use of **kwargs pretty much means that kwargs is currently a dictionary and needs to be converted to named-value. If that is correct then how can kwargs be a dictionary when its parameter is actually **kwargs. I hope my question makes sense. Please let me know if … -
How to make auto increment field in django which starts from 10000
I want to make an auto increment field in Django which starts from bigger value , I found use Autofield in models but It starts from 1 . class University(models.Model): id = models.AutoField(primary_key=True) university_name = models.CharField(max_length=250, unique=True) university_slug = models.SlugField(max_length=250, unique=True) def __unicode__(self): return self.university_name How can do this ? Any helpful suggestion will be appreciated ? -
DRY way to declare several similar form fields
Let's say I'm trying to declare a (django) Form class with several FileFields: class = MyForm(forms.Form): file_0 = forms.FileInput() file_1 = forms.FileInput() ... I have about 20 sequential inputs to declare - what's the best way to avoid typing this all out like a chump? -
How can I sort a nested list accordign to each element in nested lists
I have a model Page which stores an optional parent page (instance of itself). In my views I made a function which will return a nested list of all pages and their parents. For example, my page architecture is CCC AAA DDD KKK EEE ZZZ BBB So DDD has the parent page AAA, which has it's own parent page CCC. The CCC is top page and has no parent page. The function will first get a queryset of all instances of Pages and sort them alphabetically. Then it will proceed to recursively generate a "full parent architecture" list, where each element on that list is another list of all parent pages, including the page itself. From the example above if we take a slice of list for page DDD, it would return [CCC, AAA, DDD]. My function currently returns a list like this for the above stated example: [ [CCC, AAA], [ZZZ, BBB], [CCC], [CCC, AAA, DDD], [CCC, AAA, DDD, EEE], [CCC, AAA, KKK], [ZZZ], ] As you can see from the that list, all elements are sorted alphabetically according to the last element on that list. Now I want to display all those parent pages on my front end … -
Saving chartist.js charts into PDF (Django)
I'm making a dashboard that displays various data in the form of charts. However, if I try to print the screen the style all disappears. The same happens if i use something like report lab to try and do this. I've tried using CairoSVG to convert to PNG, which i can insert into a PDF with reportlab. However, I get an error that Cairo is not installed, nor can I install it. Does anyone know of a good way to turn SVG into PNG which can then be inserted? Or another possible solution? -
django-auth-ldap not finding groups
I am using a fork of django-auth-ldap (django-auth-ldap-ng==1.7.6) with pyldap==2.4.25.1 to connect to ldap. I am able to successfully log in but I am running into errors. I am getting a DN_SYNTAX error even though I am able to still log in with ldap credentials and map attributes. Here is the main error code: INFO "GET /login HTTP/1.1" 200 3141 DEBUG (0.000) SELECT "auth_user"."id", "auth_user"."password","auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" LIKE 'zorpho' ESCAPE '\'; args=('zorpho',) DEBUG Populating Django user zorpho ERROR search_s('zorpho@MyCompany.local', 0, '(objectClass=*)') raised INVALID_DN_SYNTAX({'desc': 'Invalid DN syntax', 'info': "0000208F: NameErr: DSID-03100225, problem 2006 (BAD_NAME), data 8350, best match of:\n\t'zorpho@MyCompany.local'\n"},) DEBUG search_s('zorpho@MyCompany.local', 0, '(objectClass=*)') returned 0 objects: WARNING zorpho@MyCompany.local does not have a value for the attribute mail ERROR search_s('zorpho@MyCompany.local', 0, '(objectClass=*)') raised INVALID_DN_SYNTAX({'desc': 'Invalid DN syntax', 'info': "0000208F: NameErr: DSID-03100225, problem 2006 (BAD_NAME), data 8350, best match of:\n\t'zorpho@MyCompany.local'\n"},) DEBUG search_s('zorpho@MyCompany.local', 0, '(objectClass=*)') returned 0 objects: WARNING zorpho@MyCompany.local does not have a value for the attribute sn ERROR search_s('zorpho@MyCompany.local', 0, '(objectClass=*)') raised INVALID_DN_SYNTAX({'desc': 'Invalid DN syntax', 'info': "0000208F: NameErr: DSID-03100225, problem 2006 (BAD_NAME), data 8350, best match of:\n\t'zorpho@MyCompany.local'\n"},) DEBUG search_s('zorpho@MyCompany.local', 0, '(objectClass=*)') returned 0 objects: WARNING zorpho@MyCompany.local does not have a value … -
how to dynamically create and fill content (javascript based) while using jquery tabs?
taking it a step further from my last question (change cell content displayed on click - javascript) I'd like to be able to create such tabs (and their relative ids dynamically). once I do, i'd like for each tab to display the same setup of charts and tables (everything already covered for statically). I am using django as a backend solution and while I can create a series of dictionaries that would emcompass all the data I need (already up and running statically), I am experiencing issues when dealing with the "dynamic" part of the javascript (assign data for each tab dynamically) while also iterating through the jtabs. so i'd need to turn this: <div id="tabs_3"> <ul class="clicked"> <li><a href="#tabs_3-1">CORE 1</a></li> <li><a href="#tabs_3-2">CORE 2</a></li> <li><a href="#tabs_3-3">CORE 3</a></li> </ul> <div id="tabs_3-1"> <div id="bar-chart"></div> <div id="line-chart"></div> <div id="pie-chart"></div> </div> <div id="tabs_3-2"> <p>r et purus.</p> </div> <div id="tabs_3-3"> <p>, lacus.</p> </div> </div> # as well as the javascript section - which i-ll cut short since it's code based off google's charts // draw pie chart var pieChart = new google.visualization.PieChart(document.getElementById('pie-chart')); pieChart.draw(pieData, pieOptions); into a for loop where these elements change: <li><a href= #tabs_3-1 > CORE 1 </a></li> <div id= "tabs_3-1" > <div id= … -
Is there any way to load a template dynamically inside of a static navbar template based on the current url?
Hi I'm new to django and I'm trying to make a site with it. My project structure is currently like so: project/ manage.py project/ __init__.py settings.py urls.py myapps/ __init__.py main/ __init__,models,views,urls,etc... static/ main/ templates/ main/ I'm using html5boilerplate with all the css, javascript and images are located in myapps/main/static/main/ And all of my templates reside in myapps/main/templates/main/ With unique names. When the user hits the main page they load up a slightly modified index.html (renamed to boilerplate.html) that came with html5bp: <!-- boilerplate.html --> {% load static %} ... <body> <!--[if lt IE 8]> ... <![endif]--> <!-- Add your site or application content here --> {% include "main/index.html" %} <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <script src="{% static 'main/js/plugins.js' %}"></script> <script src="{% static 'main/js/main.js' %}"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> ... </script> </body> ... I'm using index.html as my static sidebar but I have it in a separate template in case I want to change it down the line and it separates the boring stuff from the fun stuff (who likes looking at bp code?). <!-- index.html --> <div id="sidenav" class="sidenav"> ... </div> <div id="main"> {% include /*SOMETHING HERE*/ %} </div> Now whenever a user is redirected …