Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter custom look up
How can I add custom filtering to Django search? currently lookup_expr='icontains' match the words that contains string. Example: I want to search the work "elephant". if i type ele, phant, then icontains works. But if i type elepant (missed h) then icontains wont return anything. So I want to build the search text that matches similar word. How can I do that in django? -
Circular reference Django on_delete=PROTECT
I have these two relations class Parent(models.Model): name = models.CharField(max_length=10, primary_key=True) last_child = models.ForeignKey('Child', on_delete=models.PROTECT) class Child(models.Model): name = models.CharField(max_length=10, primary_key=True) birth = models.DateTimeField() parent = models.ForeignKey('Parent', on_delete=models.CASCADE) The desired functionality is that there should never be a case where some child gets deleted, except for when their parent gets deleted (then they all die with the parent) Will this particular implementation achieve the desired properties? Or will there be some funky side affects to having a circular reference with one being PROTECT while the other CASCADE? (e.g. while CASCADE deleting the children, it hits the last child, which is PROTECTed by the parent) -
Pass more than on foreign keys from a single model to a Django inline form?
I have a master-detail table with multiple fields unique togather as a composite key. Master table SLDc Detail table SLDCDet Goal is to pass 'comp' and 'year' to the detail inline form. Django gives me this error : 'purchase.SlDcdet' has more than one ForeignKey to 'purchase.SlDc'. Views.py ''' Define the three forms here''' author = SlDc.objects.get(inv_id=inv_id) author_form = TmpForm(instance=author) BookFormSet = inlineformset_factory(SlDc, SlDcdet, exclude=('emp_id', 'voucher', 'lineitem', 'id',),form=TmpFormDetForm) <------ should i give fk_name="" here? How can i give both? Models.py class SlDc(models.Model): inv_id = models.CharField(max_length=6) comp_id = models.CharField(max_length=2) year_id = models.CharField(max_length=2) class Meta: managed = False db_table = 'sl_dc' unique_together = (('comp_id', 'year_id', 'inv_id'),) class SlDcdet(models.Model): inv = models.ForeignKey(SlDc, models.DO_NOTHING, related_name="+") lineitem = models.CharField(max_length=2) prod = models.ForeignKey('SlProduct', models.DO_NOTHING, related_name="+", blank=True, null=True) comp = models.ForeignKey(SlDc, models.DO_NOTHING, related_name="comp_fk") year = models.ForeignKey(SlDc, models.DO_NOTHING, related_name="year_fk") class Meta: managed = False db_table = 'sl_dcdet' unique_together = (('comp', 'year', 'inv', 'lineitem'),) -
Fastest way to compare list item against a junk of text or string in python
I have a python list ['Yahoo Search - Yahoo Search Marketing', 'Yahoo Site Explorer - Yahoo! Search Marketing Ambassador', 'Yamaha - Yamaha DM2000', 'Yamaha Digital Consoles - Yamaha M7CL', 'Yamaha PM5D - Yammer', 'YAML - YMS', 'Yantra - Yard', 'Yard Management - Yard Signs', 'Yard Work - Yardi', 'Yardi Enterprise - Yardi Property Management', 'Yardi Property Management Software - Yardi Voyager', 'Yarn - Yaskawa', 'Year End Accounts', 'Year End Accounts - Year End Close', 'Year End Closing - Year-end', 'Year-end Close', 'Year-end Close - Year-end Closing', 'Yearbook - Yearly', 'Yeast - Yeast two-hybrid', 'Yellow Belt - Yellow Book', 'Yellow Pages - Yelp', 'Yeoman - Yiddish', 'Yield - Yield Enhancement', 'Yield Management', 'Yield Management - Yields', 'Yieldstar - Yii', 'Yin Yoga - Yodeling', 'Yoga', 'Yoga - Yoga', 'Yoga Instruction - Yoga Nidra', 'Yogurt - Yoruba', 'Young Adult - Young Adult Literature', 'Young Adult Services - Young Adults', 'Young Adults', 'Young People - Young Professionals', 'YourKit - Yourdon', 'Youth Activism - Youth Advocacy', 'Youth At Risk - Youth Culture', 'Youth Development', 'Youth Development - Youth Education', 'Youth Empowerment - Youth Engagement', 'Youth Entrepreneurship - Youth Groups', 'Youth Justice - Youth Leadership', 'Youth Leadership Training - Youth Marketing', 'Youth Media - Youth Mentoring', … -
Django : Is it better to set PostgreSQL as database from the start of project?
I just wonder whether I start with PostgreSQL or sqlite3 when starting Django project. I usually start with sqlite3, which is a default database, and change it into PostgreSQL at the time to deploy. I use TDD and heard that it is much faster when use PostgreSQL as a database. Is it right? If so, do I have to use PostgreSQL from the start? Need some advices. Thanks -
Problemas updateView en Django 1.10
Estoy tratando de actualizar un solo campo de un modelo utilizando vistas basadas en clases (updateView). Pero al hacerlo actualiza el campo, pero el camnpo foraneo lo coloca en null. models.py class comentario(models.Model): comentario = models.TextField(max_length=600) autor_comen = models.CharField(max_length=60) fecha_comen = models.DateTimeField(auto_now_add=True) estatus = models.BooleanField(default=False) id_noticia = models.ForeignKey('noticia', null=True, blank=True) id_recurso = models.ForeignKey('recurso', null=True, blank=True) id_evento = models.ForeignKey('evento', null=True, blank=True) views.py class comen_noticia_list(ListView): model = comentario fields = ['id', 'estatus', 'id_noticia_id'] template_name = 'template/comentario_aprobar.html' paginate_by = 2 def get_queryset(self): queryset = super(comen_noticia_list, self).get_queryset() return queryset.filter(estatus=False).order_by("fecha_comen") template {% extends "template/base.html" %} {% block content %} {% include "template/menu.html" %} <div class="container"> <h4>Aprobrar Comentario N° {{ object.id }}</h4> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="input-field col s5"> {{ form.id.errors }} <i class="material-icons prefix">group</i> <input id="id" type="text" class="validate" value="{{ object.id }}" readonly="true"> <label for="autor_comen">Id:</label> </div> </div> <div class="row"> <div class="input-field col s8"> {{ form.comentario.errors }} <i class="material-icons prefix">edit</i> <textarea id="comentario" name="comentario" class="validate" col="10" rows="10">{{ object.comentario }}</textarea> <label for="comentario">Comentario:</label> </div> </div> <div class="row"> <div class="input-field col s5"> {{ form.autor_comen.errors }} <i class="material-icons prefix">group</i> <input id="autor_comen" type="text" class="validate" name="autor_comen" value="{{ object.autor_comen }}" readonly="true"> <label for="autor_comen">Autor:</label> </div> <div class="input-field col s5"> {{ form.fecha_comen.errors }} <i class="material-icons prefix">email</i> <input type="text" id="fecha" name="fecha" class="validate" value="{{ … -
Django, bundle together count queries?
Lets say I have the relation class Person(models.Model): is_asian = models.BooleanField() is_male = models.BooleanField() is_gay = models.BooleanField() last_name = models.ForeignKey('FamilyName') is_happy = models.BooleanField() class FamilyName(models.Model): title = models.CharField(max_length=200, primary_key=True) Currently, when I want to get a bunch of statistics about my population I do have_x_many_males = Person.objects.filter(is_male=True).count() have_x_many_gays = Person.objects.filter(is_gay=True).count() have_x_many_roberts = Person.objects.filter(last_name_id='robert').count() ... However this is incredibly inefficient if the number of statistics I have grows Is there a way to bundle the queries altogether and execute them at once and get back a list or something ? >>> main_query = [query_1, query_2, query_3] >>> main_query.execute() {'have_x_many_males':5, ...} -
fetch data from api in ajax indjango
I am really new in ajax. I want to implement a basic ajax get function. However it's not working. I really don't know what went wrong. I just want ajax to work at first then I will work on my html page. my url: from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from rest_framework import routers from . import views app_name = 'tabs' urlpatterns = [ url(r'^api/users/$', views.UserList.as_view(), name='user_list',), my html: <!DOCTYPE html> <html lang="en"> <head> <title>Hospital Dashboard</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3. /js/bootstrap.min.js"></script> <script> $.ajax({ type: 'GET', url: "api/users", success:function(data){ alert(data); } }); </script> </head> <body> </body> </html> -
Django one model to many tables
I am wondering if it's possible to have one base model that can have a type field or something of that nature, where everyone with the same type goes into one table. So for example if I have a type=A and a type=B then I would have an A-Type table and a B-Type table. If someone were to come along at some point in the future and be classified as a C then when their record was saved a C-Type table would automatically be created. Is this possible or am I doomed to having to manually create a new model for each new type that arises. -
NoReverseMatch at / error in Django
I have started to display blog posts on my homepage and making it so you can read the full post when I click the anchor link but when refresh I get a "NoReverseMatch at /" error. Here my main urls.py: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', include("blog.urls")) ] blog/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), ] blog/views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Post def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, "blog/post_list.html", {"posts": posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) and the html file that seems to be linked with the error (blog/post_detail.html): {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <div class="post"> <div class="date"> {{ post.published_date }} </div> <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %} -
How to show automatically include "url available at" in Django project docstrings (via Sphinx)?
When creating docstrings that will be collected via Sphinx in a Django project, how can I show the url a view is available at? Is there any way to automatically append this to docstrings for a series of views? Example: class PasswordChangeView(UpdateView): ''' Allows registered users to change/update their password ''' What I'd like to (essentially) see rendered: class PasswordChangeView(UpdateView): ''' Allows registered users to change/update their password :url: {url(s) this view is available at, found via the urlconf} ''' How can I use the current state of the urlconf to do this on make as opposed to manually tracking? -
Trying to populate <keyword> in urlpattern
So my goal is to populate the keyword <category> in urls.py to make a dynamic url pattern. When I click on a post in BoxesView ,my urlpattern is still http://127.0.0.1:8000/1/1/ and not http://127.0.0.1:8000/news/1/ like I want it to be. What's causing me most of my problems is django forcing me to use a tuple for my CATEGORY_CHOICES, as opposed to a list. And for some reason it only allows the number (e.g. '1', '2') to be used in my arguments and not 'news', 'sport' etc. so in my article function in views.py, name has to be the number, regardless if the number is in the 1st or second part of the tuple brackets. Also with this in my template: <a href="{% url 'article' category=post.category id=post.id %}"> because of the problem I stated above, post.category here will always be the number and not the word. Which I believe is messing with my category keyword in (?P<category>\w+). Here's my code: choices.py CATEGORY_CHOICES = ( ('news', '1'), ('sport', '2'), ('technology', '3'), ('science', '4'), ('cars', '5') ) urls.py BV = BoxesView.as_view() urlpatterns = [ url(r'^news/', BV, name='news'), url(r'^sport/', BV, name='sport'), url(r'^technology/', BV, name='technology'), url(r'^science/', BV, name='science'), url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'), ] views.py class BoxesView(ListView): template_name … -
django-avatar on live apache server
I am using version 2 of djang-avatar and no matter what I do it will not resize my image. The image itself is uploaded but the default size or any other sizes are ignore. My conf.py file is as follows: from django.conf import settings from PIL import Image from appconf import AppConf class AvatarConf(AppConf): DEFAULT_SIZE = 180 RESIZE_METHOD = Image.ANTIALIAS STORAGE_DIR = 'avatars' GRAVATAR_BASE_URL = 'http://www.gravatar.com/avatar/' GRAVATAR_BACKUP = True GRAVATAR_DEFAULT = None DEFAULT_URL = 'avatar/img/default.jpg' MAX_AVATARS_PER_USER = 42 MAX_SIZE = 1024 * 1024 THUMB_FORMAT = 'JPEG' THUMB_QUALITY = 85 HASH_FILENAMES = False HASH_USERDIRNAMES = False ALLOWED_FILE_EXTS = None CACHE_TIMEOUT = 60 * 60 STORAGE = settings.DEFAULT_FILE_STORAGE CLEANUP_DELETED = False AUTO_GENERATE_SIZES = (DEFAULT_SIZE, 80,120,200) def configure_auto_generate_avatar_sizes(self, value): return value or getattr(settings, 'AUTO_GENERATE_AVATAR_SIZES', (self.DEFAULT_SIZE,)) Any help on this would be great as I have had one of those days where I have achieved nothing :( -
Django: Html Request Redirect Logs User out
Im following along with the Tango with Django tutorials for user authentification and I am having this error where after I log the user in using login(request, user) I try to redirect them back to the home page using htmlrequestredirect('/'). This logs the user out, however when I render a template in the directory instead, it keeps the user logged in. Is there some setting that I could have messed up that would cause sessions to reset after a redirect or something? Thanks in advance -
Django static image not displaying
I have looked every where possible, I have not found the answer to the issue I'm having. I spent hours in this and find not avail. My front end was displaying all images and css with a static folder under the project or under the app tree. After I did the changes to use a dynamic url, and created the static folder out of the project folder(one folder down) did collectstatic all of sudden my images have disappeared, css still works either direct path'd or dynamically. I have tried the same with images, direct path(as a copy of the folder still remains in the project folder) the direct path does not work, neither the dynamic path. Its not returning 404 either, on the first load, it returns 200, on second 304 as if the image was there on screen, but it isnt. There is just no errors, but darn image is not there. What puzzles me is that the css works, but image does not display. Bellow is my code. ---|settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") ---|url.py if settings.DEBUG == True: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ---|main.html (template) {% load staticfiles %} <img … -
Django-Avatar: Settings do not seem to be acknowledged
I have installed django-avatar in a virtual enviroment using: pip install django-avatar the instructions then says: python setup.py install Any idea where this setup.py file is? -
Django on EC2 can't reach postgresql on RDS
edited the DATABASES entry in my settings.py to be: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Limbo', 'USER': '<username>', 'PASSWORD': '<password>', 'HOST': '<dbname>.<gibberish>.us-west-2.rds.amazonaws.com', 'PORT': '5432', } } now when I .manage.py runserver 0.0.0.0:800, it says: Performing system checks... System check identified no issues (0 silenced). then after a minute or two: File "/home/ec2-user///local/lib64/python2.7/site-packages/psycopg2/init.py", line 164, in connect conn = _connect(dsn, connection_factory=connection_factory, async=async) django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "..us-west-2.rds.amazonaws.com" (172.rest.of.ip) and accepting TCP/IP connections on port 5432? I have made sure to include the access via 5432 incoming from my ec2's IP (verified with curl ifconfig.co) and the ip listed in the error message (starting with 172 above). perhaps I need to use a larger subnet (than 32)in the 172 source? -
Docker on Windows and django
I have docker on Windows and ubuntu container and when I run django server there i can't see it in my browser under 127.0.0.1. I created docker container with ports exposed. When I created nginx image i could see nginx page in my browser. Why cant I see django page ? When I look at my containers I see ports 0.0.0.0:80->80/tcp -
Defining a field relation with an abstract model
I just surrendered after hours trying to test defining a relation with an abstract model, I tried polymorphic but no luck, I also tried GenericForeignKey .. also no luck, Here is my little code class Attribute(models.Model): name = models.CharField(max_length=50) class TemplateField(models.Model): name = models.CharField(null=True,blank=True,max_length=30) attributes = models.ManyToManyField(Attribute, through='AttributeValue') class Meta: abstract = True class Domain(TemplateField): name = models.CharField(max_length=33) class AttributeValue(models.Model): templatefield = models.ForeignKey(TemplateField) attribute = models.ForeignKey(Attribute) value = models.CharField(max_length=50) When I tried GenericForeignKey, I was not sure what to do with my "Domain" Model and how to modify it, and as you know I am getting the error below [while makemigrate] : wiki.AttributeValue.templatefield: (fields.E300) Field defines a relation with model 'TemplateField', which is either not installed, or is abstract. wiki.AttributeValue.templatefield: (fields.E307) The field wiki.AttributeValue.templatefield was declared with a lazy reference to 'wiki.templatefield', but app 'wiki' doesn't provide model 'templatefield'. wiki.AttributeValue: (fields.E336) The model is used as an intermediate model by 'wiki.Domain.attributes', but it does not have a foreign key to 'Domain' or 'Attribute'. -
Django Avatar Not creating a resize folder
I have deployed my website to the live server. However, whenever I upload a profile picture for the avatar it creates a folder for the user and saves the file in there successfully. However, it does not create the resize folder or any of the respective files. I amended the file permissions to 777 temporarily just to check if it was a permissions issue but no joy. Any help on this would be great as it is driving me insane :( -
Incorrect integer value error on creating IntegerField Django 1.8
Created IntegerField in the class of models.py how_much_new_notifications = models.IntegerField(default=0) Get such error: django.db.utils.InternalError: (1366, "Incorrect integer value: '' for column 'how_much_new_notifications' at row 1") How to handle with it? -
Django Same Model Class Field Relation
I am new in Python and Django. I think this is a simple filtering. My model class code is below. In my Collection class two fields are foreign 'application' which is Cascade by Application class and 'category' which should be filter from Category class by the selected application field. But not filtering. I am not sure could I explained or not. Another question is how I implement Record level security by each creator of apllication, category and collection . Here is my model class code class Application(models.Model): app_title = models.CharField(max_length=30) market_place = models.ForeignKey(Marketplace) app_type = models.ForeignKey(Appicationtype) app_creator = models.ForeignKey(User) app_package = models.CharField(max_length=255, unique=True) app_description = models.TextField(max_length=4000, blank=True) app_popup_dialog = models.CharField(max_length=255, blank=True) app_keywords = models.CharField(max_length=255, blank=True) app_icon = models.FileField(upload_to='images/') app_is_active = models.BooleanField(null=False) admob_banner = models.CharField(max_length=50, blank=True) admob_intertitial = models.CharField(max_length=50, blank=True) app_show_add = models.BooleanField(null=False) app_token = models.CharField(max_length=250, blank=True) created_date = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.app_title class Category(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) parent_category = models.ForeignKey('self', null=True, blank=True) category_title = models.CharField(max_length=255) sort_weight = models.IntegerField() category_is_active = models.BooleanField(null=False) category_icon = models.FileField(upload_to='images/', blank=True) category_token = models.CharField(max_length=250, blank=True) created_date = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.category_title class Collection(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) category = Category.objects.filter(application=Category.application) collection_status = models.ForeignKey(Collectionstatus) collection_description = models.TextField() created_date … -
Django - What is the best way to filter out softly deleted rows?
When my program performs a soft deletion, the softly deleted rows would be marked as inactive or deleted (e.g. person.deleted=True). The question is, what is the best way to make sure that every retrieval of data from this table would only return the active records without having to add the deleted=False argument to the filter method (which is not only repetitive, but also prone to errors). -
How to include/extend Jinja2 template string variable in another variable
Trying to make the code DRYer by nesting templates like this: base = Template(''' - alert: cluster: {{cluster}} role: {{role}} slack: {{slack}} ''') alert = Template(''' {% include base %} description: Critical {{role}} system load threshold: xxx-yyy-zzz ''') print alert.render(cluster='cluster1', slack='alerts', role='database') The above does not work, getting the exception: File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render return self.environment.handle_exception(exc_info, True) File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception reraise(exc_type, exc_value, tb) File "<template>", line 2, in top-level template code TypeError: no loader for this environment specified Please advise. -
What will be a models.py should look like if I want one List to be written by only one User? [ User can have many list created]]
This is models.py: class List(models.Model): ''' This is the database table definition of List objects ''' user=models.ForeignKey(User,on_delete=models.CASCADE) name=models.CharField(blank=False,max_length=255) timestamp=models.DateTimeField(auto_now_add=True) class Meta: unique_together=['name','user'] ordering = ['-timestamp'] def __str__(self): return self.name def __unicode__(self): return self.name This should produce an error: user_obj1 = get_user_obj_by_name('Conor Lalor') user_obj2=get_user_obj_by_name() list_obj = List.objects.create( user=user_obj1, name='demo_list', ) #with self.assertRaises(ValidationError): user_obj2.list_set.add(list_obj) So my question is I how should I design my models.py to get desired error or Validation. I know these can be done be cleaning in forms.py but on this level how should I produce this simple error? Thanks in advance.