Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Isn't there a way to connect a foreign key to a primary key of which datatype isn't integer?
class Commentor(models.Model): email = models.CharField(max_length=100, blank=False, null=False, primary_key=True) ... class Comments(models.Model): ... commentor = models.ForeignKey(Commentor) Above is a part of my code. As you see, if Django model reflects my intention well, commentor attribute of Comments should be like 'commentor_email' of which datatype is string. But the result is 'commentor_id' of which datatype is integer. What should I do to enforce the foreign key attribute to follow settings of the Commentor.email attribute? -
How do I change the search field label in Django admin?
In Django admin.py class TableAdmin(admin.ModelAdmin): search_fields = ["name", "description", "category"] list_display = ["name", "description", "category"] admin.site.register(Table, TableAdmin) Here, we can change the list_display, label name by using below code, name.short_description = "Product Name" Now the question is, How do I change the search fields label name? -
django error HomePageView' object has no attribute 'META' windows 7
This is my urls.py and views.py as below. I do not know what is wrong ? error HomePageView' object has no attribute 'META' from django.conf.urls import url from hello.views import HomePageView urlpatterns = ( url(r'^$', HomePageView.as_view(), name='home'), ) -
Django session id without expiry date and time
In Django there is a session middleware, after authenticating in the site the session id is created in the cookie with expiry date and time (default two weeks), We can over ride this by SESSION_COOKIE_AGE in the settings.py. After the expiration the the session id is removed and site is logged out. SESSION_COOKIE_AGE = 1209600 And my question is, is there any way ?that we can override, that it should not contain expiry date and time, is this possible? if anything please suggest me, it will be very great-full. Thanks in advance. -
Django inspectdb skips tables with constraints
I read a few topics on this, but none really seemed to offer a solution in inspectdb, or an alternative, that permits Django to make models for an existing database. So I ran python manage.py inspectdb > models.py. It did a mostly good model of creating models for the existing database that do require some tweaks, but is mostly done. However, it skips tables that have constraints on them, saying: Unable to inspect table 'users' The error was: list index out of range Duplicate the table and remove constraints, it now compiles a model for the table. Cool. Is there a way to get inspectdb to include tables with constraints? Or an alternative tool that compiles models from tables in an existing databases? PostgreSQL in this case. -
upload a specific file form Django/Python
I just have a upload file form in my django project (I'm using 1.10). Everything is working pretty fine actually, but as people will be uploading a csv file into the server I need to limit my logic into just request the file with a specific name and format. This is my code: views.py def list(request): # Handle file upload if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile = request.FILES['docfile']) newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('action')) else: messages.add_message(request, messages.ERROR, 'Something went wrong with files! Please contact the system administrator') return render(request, 'upaction-report.html') # Load documents for the list page # Render list page with the documents and the form return render(request, 'upaction-report.html', {'form': form}) forms.py class DocumentForm(forms.Form): docfile = forms.FileField( label='File format should be under the following format:', help_text='- .csv format and under the name "Action_Report"', ) template html <form action="{% url "list" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }}</p> <p> {{ form.docfile.help_text }}</p> <p> {{ form.docfile }} </p> <p><input type="submit" value="Upload File"/></p> </form> Any guess on how applying that limit? In case the file is not the right just to pop up a message … -
django how to find what is setting vary header
I have a few django sites with varying degrees of static content so I want to be able to cache these somewhere. A few of the sites do not have the Vary header set to cookie. which I would expect if there was no action done with cookies. but on another site (on pages with no csrf protection) I am getting Vary: cookie in the response. I tried deleting all the cookies, and I still get Vary: cookie in the response even when there were no cookies sent... How can I go about tracking down what is adding the vary header in the response? EDIT: I should add that the django versions and the middlewares are identical -
Enable CORS in Django app on Heroku
I'm attempting to use django-cors-middleware to allow cross-origin resource sharing in my Django-based API hosted on Heroku. I've followed the setup specified in my settings.py, namely: INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE_CLASSES = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True (I show 'django.middleware.clickjacking.XFrameOptionsMiddleware' because I read in another SO post that django-cors-middleware doesn't work with clickjacking middleware, but it doesn't seem to work either way.) I'm using https://resttesttest.com to test. When I make the request it spits out: Oh no! Javascript returned an HTTP 0 error. One common reason this might happen is that you requested a cross-domain resource from a server that did not include the appropriate CORS headers in the response -
Django: check whether run as development or production when testing?
I'm using Django 1.9 and django.test for my unit test. This is my code for testing signals: @receiver(post_save, sender=EmailNotification, dispatch_uid="spacegraphy") def post_save_notification(sender, instance, created, **kwargs): if created: if settings.DEBUG: print("post_save: created!!!") else: instance.send_notification() When I run this application in local, it run as development mode, which shows print(settings.DEBUG) as True. (I checked it in shell_plus of django-extension However, when I test my unit tests, print(settings.DEBUG) show False. I have no idea why it happened. Any idea, please? -
Django app per websitemenu item?
take a look at apple.com and see the website menu items Mac, iPad, iPhone, etc...would you consider each menu item a Django app or what should they be? Thanks for the help everyone. -
Django HMAC Registration with Unique Email
Is it possible to use RegistrationFormUniqueEmail with the HMAC activation workflow? My urls.py looks like this: from django.conf.urls import url, include from app.registration import RegistrationViewUniqueEmail urlpatterns = [ url(r'^accounts/register/$', RegistrationViewUniqueEmail.as_view(), name='registration_register'), url(r'^accounts/', include('registration.backends.hmac.urls')), ] I have a file app/registration.py from registration.backends.hmac.views import RegistrationView from registration.forms import RegistrationFormUniqueEmail class RegistrationViewUniqueEmail(RegistrationView): form_class = RegistrationFormUniqueEmail I am able to complete registration i.e. the user is created in the auth_user table and I am unable to create more than one user with the same email address as expected, but I believe it is failing when the authentication email is being sent. SMTPAuthenticationError at /accounts/register/ (535, b'5.7.8 Error: authentication failed: UGFzc3dvcmQ6') Does anyone know what's going wrong here? -
Django inner join on nulls
I currently have Django models like this MyFirstObject(models.Model): some_field = models.BooleanField(default=False) MySecondObject(models.Model): first_object = models.ForeignKey(MyFirstObject, db_column='firstObjectId') Because of various issues, our data integrity is corrupt. So, I need to find instances where MyFirstObject has been deleted, but MySecondObject still has a row w a foreign key to it. The database would look similar to: TABLE my_first_object id someField 1 a 2 a 3 b TABLE my_second_object id firstObjectId 1 1 2 3 3 4 Notice row 3 of the TABLE my_second_object has an firstObjectID that does not have a corresponding record in the my_first_object table. I want to find all instances like that. If I was doing raw SQL, I would do SELECT my_second_object.id, my_second_object.firstObjectId FROM my_second_object LEFT JOIN ON ( my_second_object.firstObjectId = my_first_object.id ) WHERE my_first_object.id IS NULL In Djago, I am trying MySecondObject.objects.filter(my_first_object__id__isnull=true) But when I look at the query that results, it is doing an inner join instead of left join. Does anyone have suggestions? Thanks! -
Drop Database from Django Admin
I'm creating a functionality that allows an admin to drop a database from the Django admin. However, I keep getting errors that a drop database cannot be execute from a transaction block or that the database is open. I have tried solutions placed here and here, either writing it in a template and executing from SQLAlchemy directly but no luck. My current code block is this engine = sa.create_engine('postgresql_string') session = sessionmaker(bind=engine)() session.close_all() engine.dispose() session.autocommit = True session.connection().connection.set_isolation_level(0) session.execute('DROP DATABASE IF EXISTS test_db;') session.connection().connection.set_isolation_level(1) But it still will throw an error even when I terminated all activity from pg_stat_activity, any other ideas on how to implement this? -
Can't call a view from within a template
I'm trying to call a view with an optional parameter from a template, but an exception is thrown. This is my view: def page(request, page_id=1): page = Page.objects.filter(pk=page_id).first() context = { 'page': page, 'answers': Answer.objects.filter(source_page_id=page.id) } return render(request, 'page.html', context) And here's my attempt to call it from page.html template: <ul> {% for answer in answers %} <li><a href="{% url 'page' answer.target_page_id %}">{{ answer.choice_text }}</a></li> {% endfor %} </ul> But for some reason, an exception is thrown, as follows: Reverse for 'page' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$$'] What's happening here? Thanks in advanced. -
Django-tables2 table renders empty when coulmns are created dynamically
I defined django-tables2 Table class with Column fields set dynamically: attrs = ['attrA','attrB','attrC'] class ExpTable(tables.Table): def __init__(self, *args, **kwargs): for attr in attrs: setattr(ExpTable, attr, tables.Column()) super(ExpTable, self).__init__(*args, **kwargs) # view def home(request): exps_dicts = some_function_to_create_tabledata() # [{'attrA':'valueA','attrB':'valueB',...}, # {'attrA':'anonther_valueA',...},...] table = ExpTable(exps_dicts) return render( request, 'some_template.html', {'experiments':table} ) While Tables object is created and its 'Column' attributes are set and data attribute is filled with proper data, the table object renders empty. Everything worked when I created the whole class dynamically: exps_dicts = some_function_to_create_tabledata() ExpTable = type('ExpTable', (tables.Table,), exps_dicts) but I needed to customize table style via table's Meta subclass but I do not know how to do that without creating a class. -
Django - 2 Foreign Key fields in one model (limit choices)
I am trying to add simple option to my admin panel. I have category, subcategory and site models. For example: Computers (category) - PC (subcategory) - Notebooks (subcategory) Health (category) - Diet (subcategory) - Fitness (subcategory) Subcategory is within category. When I am adding site in my admin panel I have list of all categories and subcategories. When I choose category (Computers) in my Subcategory field I have: PC, Notebooks, Diet, Fitness (all subcategories). I don't have any idea how can I filter this only to PC and Notebooks. Any suggestions? class Category(models.Model): name = models.CharField(max_length=30, unique=True, verbose_name='Nazwa kategorii') slug = models.SlugField() image = models.ImageField(upload_to='category_images', verbose_name="Image", blank=True) description = models.TextField(default='Description', verbose_name="Category description") class Meta: verbose_name_plural = "Categories" def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def image_thumb(self): if self.image: return '<img src="/media/%s" width="40" height="40" />' % (self.image) else: return('') image_thumb.short_description = 'Thumb' image_thumb.allow_tags = True def __str__(self): return self.name class SubCategory(models.Model): category = models.ForeignKey( 'Category', related_name='subcategory', on_delete=models.CASCADE, blank=True, null=True, ) name = models.CharField(max_length=30) class Meta: verbose_name_plural = "Subcategories" def __str__(self): return self.name class Site(models.Model): category = models.ForeignKey('Category') # sub = SubCategory.objects.filter(category=category) subcategory = models.ForeignKey('SubCategory', related_name='subcategory') name = models.CharField(max_length=30) -
Please suggest some project based django book like 'tango with django'
Can anyone suggest me some project based book for learning django ? -
How to print a field of a list under iteration in a view?
I'm trying to print a field of a list of answers from a view with no success (nothing is printed to the html), as follows: <ul> {% for asnwer in answers %} <li>{{ answer.choice_text }}</li> {% endfor %} </ul> I'm new to Django, so I guess that I'm missing something which is pretty obvious. Your help is greatly appreciated. -
Using Heroku for Django Media Files
On the heroku domain, I am not able to load my Media(Images Saved by using ImageField property) file images. However, I am able to see the images saved in the static field if I set debug = True Any ideas on how to solve this issue? Thanks -
Maintain the State of Onchange After Error Is Thrown
When a specific value is chosen from a drop-down menu, a div's "show" or "hide" property is set using the following: <script> $(document).ready(function() { $("#id_record_filter_key").change(function() { // advanced-search is the id of the div containing the additional search fields if ($(this).val() != 0) { $("#advanced-search").show(); } else { $("#advanced-search").hide(); } }); }); </script> But if the page yields a data validation error, the "show/hide" value of this property of the div is not retained. How can this be retained when an error is thrown? -
Eradicating the presence of NoneType errors in scheduling periodic celery tasks (for Django project)
For a Django project, I need to set up a celery asynchronous task that's to be periodically served by celery beat. This task calculates a value every 24 hours. So in my settings.py, I have: CELERYBEAT_SCHEDULE = { 'tasks.calculate_value': { 'task': 'tasks.calculate_value', 'schedule': timedelta(seconds=60*60*24), #execute every 24 hours }, } The variable's value persists in cache memory (my cache backend is memcached) for over 24 hours. My problem is that when this set up goes live in production, there will be a 24 hour lag before the variable gets calculated. NoneType errors will show up for those first 24 hours. Thus, is there any way I can ensure this variable is calculated right at the point of updating the code (so that no NoneType errors result), and then every 24 hours from there on? Note: I know I can always handle NoneType exceptions through try and except. But I'm wondering if I have other options here. -
Submit MultipleChoiceField in Django with custom multiselect jQuery box
I am trying to submit a multiple choice field using this jQuery plugin. My form is as follows: class BackupForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(BackupForm, self).__init__(*args, **kwargs) self.fields['contas_choice'] = forms.MultipleChoiceField( choices=get_backup_choices(self.user) ) for field in self.fields: self.fields[field].widget.attrs.update({'class': 'form-control', }) self.fields['contas_choice'].widget.attrs.update( { 'name': 'from[]', 'id': 'search', 'class': 'form-control', 'size': '8', 'multiple': 'multiple', } ) contas_choice = forms.MultipleChoiceField(required=False) # other fields And on my template: <form action="" class="form-horizontal" method="post">{% csrf_token %} <div class="row"> <div class="col-xs-5"> {% for choice in form.contas_choice %} {{ choice }} {% endfor %} </div> <div class="col-xs-2"> <button type="button" id="search_rightAll" class="btn btn-block"><i class="glyphicon glyphicon-forward"></i></button> <button type="button" id="search_rightSelected" class="btn btn-block"><i class="glyphicon glyphicon-chevron-right"></i></button> <button type="button" id="search_leftSelected" class="btn btn-block"><i class="glyphicon glyphicon-chevron-left"></i></button> <button type="button" id="search_leftAll" class="btn btn-block"><i class="glyphicon glyphicon-backward"></i></button> </div> <div class="col-xs-5"> <select name="to[]" id="search_to" class="form-control" size="8" multiple="multiple"></select> </div> </div> <div id="actions" class="row"> <div class="col-md-12"> <button type="submit" class="btn btn-primary">Baixar</button> <a href="/listar-contas/" class="btn btn-default">Cancelar</a> </div> </div> </form> This renders the select field just like I wanted, as in the example of the plugin reference. But when I try to submit the form, I get an HTML message saying "Please select an item in the list", even after I have moved all the items to the right box. Therefore, I can't … -
How do I pipe a model query into the Django Shell via a Bash Script?
I'm writing a startup.sh script to be ran when a docker container is created. #!/bin/bash python manage.py runserver python manage.py makemigrations accounts python manage.py migrate python manage.py check_permissions python manage.py cities --import=country --force *python manage.py shell | from cities.models import * Country.objects.all().exclude(name='United States").delete()* python manage.py cities --import=cities python manage.py cities --import=postal_code I am guessing the line in question is incorrect, what would be the correct way to do this in a bash script? -
AttributeError 'unicode' object has no attribute 'numero'
I'm new with django, so I apologize for this (probably) dumb question: I'm trying to make a form based on the content of a model named Lineathat, depending of the input, redirects the user to a view named lineas_detalles. If the input is not a part of the model Lineathe form is supposed to do nothing. I can perfectly load the page where the form is, but when I enter something and I submit I get the error: AttributeError at /lineas/ 'unicode' object has no attribute 'numero' The content that is intended to go into the form is a number. lineas.html {% load staticfiles %} [...] {% block content %} <h1>Escoja una línea</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit">Actualizar</button> </form> {% endblock %} forms.py from django import forms from .models import Linea class LineaForm(forms.ModelForm): class Meta: model = Linea fields = ('linea',) models.py from __future__ import unicode_literals from django.db import models class Linea(models.Model): linea = models.CharField(max_length=2) def __str__(self): return self.linea [...] urls.py from django.conf.urls import url from . import views urlpatterns = [ [...] url(r'^lineas/$', views.lineas, name='lineas'), url(r'^lineas/(?P<linea_numero>)/$', views.lineas_detalles, name='lineas_detalles'), ] views.py from django.shortcuts import render, redirect from .forms import LineaForm def lineas(request): if request.method == … -
Allauth login on homepage not working
To allow Django's allauth to work on my homepage, I copied the allauth HTML for the login and signup forms to my own base.html (The login form can be seen here). So this successfully renders the form and its fields on my homepage. However, when I click submit on the login form, it just redirects me to allauth's /accounts/login URL, which renders the same form. Only after that does submitting the form work. It's the same with the signup form when I submit the signup form on my homepage, it redirects me to /accounts/signup and then the signup works after submitting again. How can I make the login/signup work initially from my homepage? My urls and views: urls.py urlpatterns = [ url(r'^$', views.boxes_view, name='news'), url(r'^accounts/', include('allauth.urls')), ] views.py def boxes_view(request): search = request.GET.get('search') posts = Post.objects.all().filter(category=1).order_by('-date') if search: posts = posts.filter(Q(title__icontains=search)|Q(content__icontains=search)) else: posts = Post.objects.all().filter(category=1).order_by('-date') context = {'posts': posts,} return render(request, 'polls.html', context) base.html ... {% load i18n %} <form class="login" method="POST" action="{% url 'account_login' %}"> <div class="loginWrapper"> <div class="loginNested"> <div class="loginBox"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' …