Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django not filling out variable entries?
In my settings.py I define a nonempty SITE_NAME: SITE_NAME = 'Pets Gallery' In my views.py I have: def all_pets(request): pets = models.Pet.objects.all() random.shuffle(pets) return render(request, 'multiple_pets.html', { 'pets': pets, 'site_name': settings.SITE_NAME, 'page_name': 'All the pets we have!'}) In the present version of the templates, the base template has: <title>{{ page_name }} - {{ site_name }}</title> ... <h1>{{ page_name }}</h1> The specific template is just a stub that extends the base class; I want to customize it but I'm working on smoke testing for now. The rendered page appears to be treating all values as empty. The rendered HTML source has: <title> - </title> ... <h1></h1> Why would it be treating variables (for the moment, nonempty strings) as empty, unavailable, etc.? Thanks, -
Django view is saving form data but not generating required document
views.py class list_bags_view(InlineFormSetView, CreateWithInlinesView): model = PackingBags template_name = 'packinglist.html' form_class = PackingBagsForm inlines = [PackingSetInline, ] def save_formdata(request): if form.is_valid(): form.save(commit=True) def generate_doc(request): doctype = form.cleaned_data['format'] filename = fill_template( 'odtemplates/PACKAGING LIST.odt', form.cleaned_data, output_format=doctype) visible_filename = 'packaging.{}'.format(doctype) return FileResponse(filename, visible_filename) the class based view is achieving everything required apart from generating a document from the form data. will appreciate any feedback on what i am doing wrong. thanks. -
Reference Original Post Data in Django
I am trying to figure out how to post the original field data along with its result to my results page. I have an app written in Django that has two html pages. An input page and a results page. The input page has a form. The result page has the output. Here is the code I have in place: models.py class IssuingCA (models.Model): ICA_name = models.CharField(max_length=200) filepath = models.CharField(max_length=200) def __str__(self): return self.ICA_name views.py (simplified version) def index(request): issuers = IssuingCA.objects.order_by('ICA_name') issuerOptions = {'issuers': issuers} return render(request, 'index.html', issuerOptions) def results(request): issuer = request.POST['selectedIssuer'] issuername = 'Where I want the ICA_name value "icas" displayed' info = {'issuer': issuer, 'issuername': issuername} return render(request, 'results.html', info) index.html --snip-- <label for="selectedIssuers">Issuing CA</label> <select id="selectedIssuers" name="selectedIssuers"> {% for icas in issuers %} <option value="{{ icas.filepath }}">{{ icas }}</option> {% endfor %} --snip-- results.html --snip-- <div>{{ issuer }}</div> <div>{{ issuername }}</div> --snip-- Let's set up a some sample data for the DB: ICA_Name = "squirrels"; filepath = "in/some/forest" The way the application works is that it presents a drop down in the index.html page that displays the ICA_name of all the values. When you select the ICA_name, in this case, 'squirrels' and submit, it … -
django framework runserver not working
enter image description here screenshots Hi, the django server isn't working on the command: python manage.py runserver (on providing the port number as well) I'm using windows 8, the path is set in environment variables. I've tried re-installing both python and django but it didn't help. Please help so I can proceedenter image description here -
Efficient way to debug a code
I'm trying to find out the more efficient way debug my code with Vim. I know there exists something pretty good with PyCharm which is called watch (https://www.jetbrains.com/help/pycharm/2016.3/debug-tool-window-watches.html). In fact, I am looking for something similar. Question : What is the most efficient way to debug a code (python, django, ...) with Vim? Plugin maybe? -
django-auth-ldap query. Cannot add LDAP users to active, staff, superuser roles
Looking for some help with the django-auth-ldap package. Background - I am trying to add LDAP users to the default user roles STAFF, ACTIVE, and SUPERUSER. As you can no doubt see from the the debug.log that the django-auth-ldap successfully finds the LDAP username and populates DJANGO accordingly. However it does not add the LDAP user to the relevant roles i.e.active, staff, superuser, because it states that it does not belong to the relevant group although performing an LDAP search on both the username and group says otherwise. Any help/advice would be greatly appreciated. Thanks debug.log search_s('ou=xxxx,o=xx,c=uk', 2, '(uid=%(user)s)') returned 1 objects: cn=someusername,ou=xx,ou=xxxxx,ou=xxxx,o=xx,c=uk Populating Django user someusername cn=someusername,ou=xx,ou=xxxxx,ou=xxxx,o=xx,c=uk is not a member of cn=somegroup,ou=xx,ou=xxx,ou=xxxx,o=xx,c=uk cn=someusername,ou=xx,ou=xxxxx,ou=xxxx,o=xx,c=uk is not a member of cn=somegroup,ou=xx,ou=xxx,ou=xxxx,o=xx,c=uk cn=someusername,ou=xx,ou=xxxxx,ou=xxxx,o=xx,c=uk is not a member of cn=somegroup,ou=xx,ou=xxx,ou=xxxx,o=xx,c=uk settings.py import os import ldap import logging from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType ** Omitted for clarity ** AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LDAP_AUTH_URL = "ldaps://ldap.xxxxxxxxxxx.xx.uk/" LDAP_AUTH_SEARCH_BASE = "ou=xxxx,o=xx,c=uk" # Application definition AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: False, ldap.OPT_REFERRALS: False, } AUTH_LDAP_SERVER_URI = "ldaps://ldap.xxxxxxxxxx.xx.uk" AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=xxxx,o=xx,c=uk", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=xx,ou=xxx,ou=xxxx,o=xx,c=uk", ldap.SCOPE_SUBTREE, … -
FieldError: Cannot resolve 'publish_year' into field
I am new to Django and I am currently using django by example by I am getting this error FieldError: Cannot resolve 'publish_year' into field Here is how my model is: # Abstract Model class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'),('published', 'Published'),) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices= STATUS_CHOICES, default='draft') class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset()\ .filter(status='published') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) def __str__(self): return self.title -
Unable to continue Wagtail installation, "./migrate.py migrate" traceback
I'm installing Wagtail on Linode Ubuntu 16.04 LTS. I followed the following guides so far: https://www.linode.com/docs/getting-started http://docs.wagtail.io/en/v1.9/getting_started/index.html For the second link, I followed the installation guides for Python, pip, virtualenv and the required Pillow libs. I got up to the following in the installation process: $ pip install -r requirements.txt $ ./manage.py migrate The migrate command produces the following error: Traceback (most recent call last): File "./manage.py", line 10, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management I haven't been able to find a solution for this. Any help is greatly appreciated. -
Django causing "Row size too large" with MySQL backend
How do you fix the notorious "Row size too large" error that MySQL emits when you're using Django? I have a query that I'm appending multiple tables to using Django's select_related(), and if I output the SQL query Django generates, and run that manually in a MySQL shell, it runs fine, but when Django tries to execute it and iterate over the records, Django throws the 500 error: Warning: Row size too large (> 8126). Changing some columns to TEXT or BLOB may help. In current row format, BLOB prefix of 0 bytes is stored inline. How do I fix this? Since it's just a "warning", can I instruct Django to ignore it? I've tried the numerous fixes on the MySQL side, such as enabling Innodb with Barracuda format and table compression, but that's had no effect. I've also tried reducing the number of tables included in my select_related(), but that's also had no effect. -
Using Django with Jython and Oracle
I am using jython 2.7.0 with Django 1.8.17. I am trying to use oracle 11g express edition as my database. I can't change the oracle database, and later it will be using the full edition. However, the django-jython package doesn't have oracle as a backend db connection. What is the easiest way I can get this to work? I also cannot use the cx_oracle package with jython, because the cx_oracle package uses a C implementation of python. I can use jdbc (using the ojdbc6.jar) to make a raw connection to the oracle database, but I don't know how to use this raw connection to make use of django's ORM capabilities. Can anyone help? Also I am just starting to learn jython and django. -
Python/Django/Testypi bug: Error when calling the metaclass bases getattr(): attribute name must be string
Can't understand the nature of the bug. I suppose it's somehow related to version incompatibilities, because I need to modify existing code and didn't know which version of python/django/testypi were used creating this. I hope someone well familiar with tastypi might help me to fix it. -
In Django model form how to use Ajax / jQuery in one of the field?
In Django I'm building a model where user will input information in the form and the same information will be stored in Database. However, in one of the field I want to use Ajax / jQuery to let the user search and select one of the option targeting the HTML field using following jQuery code: $( function() { $.getJSON("beta.json", function(data) { autoComplete = []; for (var i = 0, len = data.length; i < len; i++) { autoComplete.push(data[i].iata + ", " + data[i].name); } $( "#from" ).autocomplete({ source: autoComplete, minLength: 3 }); $( "#to" ).autocomplete({ source: autoComplete, minLength: 3 }); }); }); However Django forms does not allow the option to target the HTML field. Is there any way I can use Ajax and jQuery with Django forms? -
How to return multiple files in HttpResponse Django
I have been wracking my brains in this problem. Is there a way in django to serve multiple files from a single HttpResponse? I have a scenario where i am looping through a list of json and want to return all those as file form my admin view. for company in company_json_list: response = HttpResponse(json.dumps(company), content_type="application/json") response['Content-Disposition'] = 'attachment; filename=%s.json' % company['name'] return response Now this will only let me return/download one json file as return would break the loop. Is there a simpler way to just append all this in a single response object and return that outside loop and download all json in the list in multiple files? I looked through a way to wrap all these files into a zip file, but i failed to do so as all the examples that i could find had files with path and name which i don't really have in this case. -
How to make HTML imported Campaign Monitor templates editable?
During the import procedure I made sure to mark the imgs editable, and put several content sections into multiline constructs. The imported templates show up in the client's template set, but when I try to edit them, I only presented with the zip/HTML upload option instead of the actual editor: From my code base, my own template object has the exporting code: class EmailBodyTemplate(models.Model): ... def migrate_email_template(self, cm_client_id, cm_token): cm_template = Template(cm_token) # Basically I expose a specially tailored HTML version of my template # for CM: adding editable to imgs, introducing multiline wrappers and # adding unsubscribe, view in browser and other special links html_url = settings.HOME_URL + reverse('email_import_view', args=(self.id,)) template_id = cm_template.create(cm_client_id, self.name, html_url, None) self.template_id = template_id self.save() -
How to validate form using Ajax and then submit using Django?
I have a fairly complicated scenario here. I have a Django form with 2 fields in it. I have an Ajax call in place, that on submit takes the values of these two input fields and just returns an alert box with the message "Hi [field1 input]!". What I want to be able to do is: Make the ajax call to the backend by Clicking "Submit" button If the two fields are the same, return alert with message "True" On clicking "Ok" to the alert box, change "Submit" button to "Proceed" On clicking "Proceed" submit form to backend to save to the database. If the two fields aren't equal, return alert saying the same and don't change the button. I know this is highly specific and pertains only to my case, but I want to draw attention to the general idea here of validating using Ajax and then submitting forms in Django. Is this possible? -
Forbidden (403) CSRF verification failed. Request aborted. Django
I have this error when loading the template the model of the form, and enter the amount in the The text sends me to the page Help Reason given for failure: The CSRF symbol is missing or incorrect. From Django, help pls! views.py: def ListAll(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': user = request.user if user.is_superuser: pedido = Pedido.objects.filter(especialidad=especialidad) template = 'admindata.html' return render_to_response(template,locals()) else: if request.method == 'POST': form = PedidoEditForm(instance=especialidad) else: form = PedidoEditForm(request.POST, instance=especialidad) if form.is_valid(): form.save() pedido = Pedido.objects.filter(especialidad=especialidad) return render_to_response('index2.html',locals(), {'form':form}) template html: {% if especialidad.estadistica == "0" %} <section id="contenido"> <div class="container" style="margin:50px auto width="100%""> <form id="myform" method="POST"> {% csrf_token %} {{form.as_p}} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp; <input type="submit" class= "btn btn-success" value="Guardar"> {% else %} <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> <td>Ingresar</td> </tr> </thead> <tfoot> <tr> <td>Servicio</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> <td></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ ped.especialidad.nombre }}</td> <td>{{ ped.articulo.cod_experto }}</td> <td>{{ ped.articulo.nombre }}</td> <td>{{ ped.cantidad }}</td> <td><a href="{% url "usuario:cant_ingresar" ped.id especialidad.id %}" method='GET' type="submit" class="btn btn-primary pull-right" value="editar" onclick="document.location.reload();"/>Ingresar</a></td> </tr> {% endfor %} {% endif %} </tbody> </table> … -
How to get all related objects in django model ForeignKey and OneToOneField
I'm using django 1.9. I have the following Django models: @python_2_unicode_compatible class Projects(models.Model): index = models.IntegerField(blank=True,default=1) year = models.CharField(max_length=255, blank=True) title = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) def __str__(self): return '%s, %s, %s, %s' %(self.index,self.year,self.title, self.description) @python_2_unicode_compatible class Awards(models.Model): title = models.CharField(max_length=255, blank=True) def __str__(self): return '%s' %( self.title) @python_2_unicode_compatible class Images(models.Model): projects = models.ForeignKey(Projects,null=True,blank=True, related_name='images_projects') awards = models.OneToOneField(Awards,null=True,blank=True,related_name='images_awards') title = models.CharField(max_length=255, blank=True) file = models.ImageField(upload_to='upload_images/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s, %s' %(self.file, self.pk) 1)I'm trying to get all the model objects Projects and model objects Images that are related to the model Projects Projects.objects.all().select_related('images_projects') As a result, I get only model objects Projects. 2) I want to get all the objects of the model Awards and associated fields in the Images. Awards.objects.all().prefetch_related('images_awards') As a result, I receive only all fields of the Award model. How to get related fields together with all objects of the main model in my 2 cases? -
Backend parsing code which is called in some period of time
Project is based on creating own objects by parsing information from some website. So, own objects have to be up-to-date, but it would be weird and inefficient , if function(which parses updated information and saves it using Django ORM) is called for every user loading the page. So I figured it might be some independent code, called with some frequency(like once a day) . Is the concept right? And how to run a python/django function once in period of time? -
Django not using local machine time
I will preface my question by saying that I have found a work around and am more interested in the why Django is doing what it is doing. I am new to Django and am using it within a virtual environment. When I call a simple datetime.now() the result is in UTC and not my machine's local time. I believe this is the behavior on Linux and Macs while PCs will return the machine local time. In other python based frameworks I have used in a virtual environment the machine local time is returned. As I said, just curious as to why Django is doing what it is doing. -
Django Attribute error on serializer when using intermediate model
I've been trying to create a serializer for a Model in which one of the fields is a ManytoManyField through a Model that adds more fields. The problem is that the intermediate serializer is not recognizing that has added fields. Why could I be doing wrong? Here is my code: models.py: class Product(models.Model): name = models.CharField(max_length=30, unique=True) class Movement(models.Model): date = models.DateTimeField(auto_now_add=True) products = models.ManyToManyField(Product, through='Movement_Product') class Movement_Product(models.Model): movement = models.ForeignKey(Movement) product = models.ForeignKey(Product) amount = models.IntegerField() price = models.DecimalField(max_digits=9, decimal_places=2) class Input(Movement): invoice_number = models.CharField(max_length=30, null=True) serializers.py: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product class MovementProductSerializer(serializers.ModelSerializer): product = ProductSerializer() price = serializers.DecimalField(max_digits=9, decimal_places=2) amount = serializers.IntegerField() class Meta: model = Movement_Product class InputSerializer(serializers.ModelSerializer): date = serializers.DateTimeField() products = MovementProductSerializer(many=True) class Meta: model = Input The error I got when I try to render the InputSerializer: Attribute Error at /api/input/ Got AttributeError when attempting to get a value for field `product` on serializer `MovementProductSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. Original exception text was: 'Product' object has no attribute 'product'. -
How to run django.setup() properly from within a stand-alone python file inside of a django app (on linux-ubuntu)?
Im trying to run a stand-alone python file in a django project. The problematic code is below (standalone.py): import os import django # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") tried as well os.environ["DJANGO_SETTINGS_MODULE"] = "myproject.settings" django.setup() The error i receive is: 'No module named myproject.settings'. Somehow the project settings file is not being recognized. The file runs just fine on my local machine however the problem occurs when running the file on a linux-ubuntu server. This file is being run from within an app: myproject>myapp>standalone.py When i move this file to the same directory that myproject resides in, the file runs just fine, so im assuming that the myproject.settings module is not being recognized from within the app directory. As a temp fix: sys.path.append('path_to_myproject/') seems to resolve the issue, but definitely not something i want in production code. Any suggestions on how to resolve this issue? Thanks in advance -
Django: why django.contrib.auth.views.logout not use registration/logged_out.html
Django 1.10, My Urls: from django.conf.urls import url from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout'), ] My account/templates/registration/logged_out.html: {% extends "base.html" %} {% block title %}Logged out{% endblock %} {% block content %} <h1>Logged out</h1> <p>You have been successfully logged out. You can <a href="{% url "login" %}">log-in again</a>.</p> {% endblock %} Instead of registration/logged_out.html used, the admin logout html used (see the following). Why? How to debug? Thanks -
Why am I getting this NoCredentialsError on a Django project?
I'm currently working on a project built on Django that uses Wagtail for template managing. I created a model, that uses a Streamfield, which is basically a field similar to RickTextField that allows you to insert predefined or custom blocks and arranged them in the order you like. I made a couple of custom blocks which consists in simple HTML pieces with the corresponding placeholders. Anyway, when trying to use a specific block, it yells this error: My problem is that the issue doesn't say much to me and googling didn't help either. -
Chinese django translations not working
My settings.py looks like this: LANGUAGES = ( ('en', _('English')), ('fr', _('French')), #Simplified Chinese ('zh-hans', _('Simplified Chinese')), ) In my template I have: <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> and <button type="submit" value="zh-hans" name='language'>{% trans 'Simplified Chinese' %}</button> And in my urls.py I have: url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), In my po file I have: msgid "Menu" msgstr "菜单" I compiled the messages but it doesn't work. I have working translations for french so I don't understand what is going on with the Chinese translations. -
Way to represent SQL queries as objects in Django/Python
The following query: SELECT task_id FROM task_log L1 LEFT JOIN task_log L2 ON L1.started BETWEEN L2.started AND L2.ended WHERE L2.task_id IS NULL; Simply reads all task logs that were started when no other tasks were running. An abstraction in PHP/ZF2 looks like this: $db->select(array('L1' => 'task_log')) ->columns('task_id') ->join(array('L2' => 'task_log'), "L1.started BETWEEN L2.started AND L2.ended", array(), 'left'); I was looking for something similar in Django, or at least python. As per this discussion, it is (understandably) out of question to build this in django models. Are there any other alternatives in python/django?