Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django to prod on Dreamhost with Passenger: 500 internal server error
I have recently been experimenting with setting up Django on Dreamhost using Passenger and have come across a problem I can't seem to fix. My steps: Setup a subdomain sub.domain.com on dreamhost.com Enabled Passenger for the subdomain in order to take advantage of WSGI Installed Python 2.7.7 into my $HOME/opt/python-2.7.7 directory Installed virtualenv in order to create a separate environment for the django project Created a virtualenv in $HOME/sub.domain.com/env/ Downloaded and installed Django 1.8 Started a djangoproject called myproject Created a passenger_wsgi.py file in the subdomain root directory: sub.domain.com passenger_wsgi.py code: import sys, os INTERP = "/home/me/sub.domain.com/env/bin/python" if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/myproject') #You must add your project here sys.path.insert(0,cwd+'/env/bin') sys.path.insert(0,cwd+'/env/lib/python2.7/site-packages/django') sys.path.insert(0,cwd+'/env/lib/python2.7/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "myproject.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() With DEBUG=True, I start my server python manage.py runserver sub.domain.com:8080 and everything is fine at sub.domain.com. If I set DEBUG=False and touch tmp/restart.txt, I get a 500 internal server error at that same address. Content of log file: [Fri Mar 24 15:10:47 2017] [error] [client 184.161.139.38] Premature end of script headers: [Fri Mar 24 15:10:47 2017] [error] [client 184.161.139.38] Premature end of script headers: internal_error.html Any idea/hint/solution someone? I am … -
Include GET parameters in django rest framework JS client library action
In the latest version of Django REST framework the is interactive docs and a JS client libraru included. My question is how do i pass query parameters to a url or 'action'? I got the example from the docs working, where you define your POST data like this: let action = ["users", "create"] let params = {user:'user', password:'password'} client.action(schema, action).then(function(res) { console.log(res) }) But lets say I want to list users and filter them with my action ["users", "list"] and a couple of query parameters. How do I do that? -
Field activation based on choice field in Django Admin
Hello smart people of SO. I am trying to make a dependent Django admin form. Where if a user selects Channel as a sku type, then he just has to add service category and product category and remaining fields become inactive for him and it has null values stored in them. If a user select direct then all fields become active and he can add data into all fields. In a nutshell, I am looking for column activity based on the values in the sku type field. Not sure if we can do it in Django at this point or not. I am using Django 1.10. I have a model of my app as following from django.db import models from decimal import Decimal class Sku(models.Model): sku_type = ( ('Channel', 'Channel'), ('Direct', 'Direct'), ('Warranty', 'Warranty'), ('SECA', 'SECA'), ) sku_type = models.CharField("SKU Type", choices=sku_type, default='Channel', max_length=20) sku = models.CharField("SKU", primary_key=True, max_length=20) date_added = models.DateTimeField("Date when Added", auto_now=False, auto_now_add=True) date_updated = models.DateTimeField("Last Updated Date", auto_now=True, auto_now_add=False) service_category = models.CharField(max_length=200, blank=True, null=True) product_category = models.CharField(max_length=200, blank=True, null=True) product_description = models.TextField(blank=True, null=True) sap_description = models.TextField(blank=True, null=True) def __str__(self): return self.sku -
How is 'role does not exist' error possible, when the role actually exists
how is this error possible after migrate command : File "/Users/TheKotik/tick-tock/denv/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: role "TheKotik" does not exist if the role is actually created and has all right on that? At psql everything is correct grant all privileges on database tick to TheKotik; GRANT -
How do I pass django context variables into javascript?
I'm using highcharts and it requires me to pass into it variables such as this series: [{ name: 'Brands', colorByPoint: true, data: [{ name: 'Microsoft Internet Explorer', y: 56.33 }, { name: 'Chrome', y: 24.03, sliced: true, selected: true }, { name: 'Firefox', y: 10.38 }, { name: 'Safari', y: 4.77 }, { name: 'Opera', y: 0.91 }, { name: 'Proprietary or Undetectable', y: 0.2 }] How would I represent this in python(I was thinking to make it a string, use .format and then somehow convert it back) and how would I pass this into my javascript? -
Use Custom Filter with Django ModelChoice Filter
I am trying to create use the filter method with django-filters See an example of the models below: class Chicken(TimeStampedModel): eggs = ForeignKey(Egg) class Egg(TimeStampedModel): hatched = BooleanField(default=False) See an example of my current set up for the filter: class ChickenFilter(FilterSet): eggs__contains = ModelChoiceFilter(name="eggs", method='hatched_eggs', queryset=Eggs.objects.all()) def hatched_eggs(self, queryset, name, value): print "We got eggs" return queryset.filter(eggs__hatched=True) The problem is that the method doesnt even print We got eggs when I hit the url. It just returns an empty queryset. -
Celery loses some tasks
I am using Celery for my test django application on macOS. Celery task bg_job does background API call. When I save a TestModel in database, I call bg_job.delay() (I overrode save method). When I create just 6 TestModel instances and I want to save them (by using bulk_create), I see max 3 or 4 API call log and celery queue is empty!! celery settings: CELERY_BROKER_URL = 'redis://127.0.0.1:6379/1' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/1' CELERY_BROKER_POOL_LIMIT = 10 CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 43200} CELERY_TASK_ACKS_LATE = True CELERY_TASK_QUEUES = ( Queue('default', Exchange('default'), routing_key='default'), Queue('bg_job', Exchange('bg_job'), routing_key='bg_job'), ) CELERY_TASK_DEFAULT_QUEUE = 'default' CELERY_TASK_DEFAULT_EXCHANGE = 'default' CELERY_TASK_DEFAULT_ROUTING_KEY = 'default' CELERY_TASK_ROUTES = { 'test.tasks.bg_job': {'queue': 'bg_job'}, } tasks.py: @shared_task(bind=True, ignore_result=True, autoretry_for=(Exception,), max_retries=None, default_retry_delay=240) def bg_job(self, job_id: int): # API CALL... Celery: 4.0.2 Django: 1.10.6 Redis: 3.2.5 Python: 3.5.2 -
type object 'Blog' has no attribute '_default_manager'
I have been trying to understand my mistake about Detail Page of my blog. Like any other blog pages in the world I have got a list page which retrieves the results, and it works, but when I click for the Detail of any entry I keep getting almost the same error, no matter what I try: type object 'Blog' has no attribute '_default_manager' my Models : from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): item_title = models.CharField(max_length=250) item_text = models.TextField(max_length=5000) item_date = models.DateTimeField(auto_now_add=True) item_author = models.ForeignKey(User) def get_absolute_url(self): return reverse('main:blog', kwargs={'pk': self.pk}) def __str__(self): return self.item_title my url : #blog/detail url(r'^blog-detail/(?P<pk>\d+)/', views.BlogDetail.as_view(), name='blog-detail'), my views : class BlogDetail(DetailView): model = Blog def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(BlogDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['blog_list'] = Blog.objects.all() return context my link to entry detail : <a href="{% url 'main:blog-detail' blog.id%}">read more</a> I will appreciate any help. -
How i can include new middleware class
Got myself middleware class. Try include that. But have errorn MIDDLEWARE = [ 'fun.middleware.AuthMiddleware', ] File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) django.core.exceptions.ImproperlyConfigured: WSGI application 'fun.wsgi.application' could not be loaded; Error importing module: 'No module named middleware' How i can include that? -
Django: prevent saving empty form in formset
this should be a fairly easy one, but I am really struggling to figure it out by my self. I am doing a real estate app and I need my users to be able to upload their images of houses. Each image is related to a House and each House is related to a User. The way it is it works, but if the user submits an empty form with my formset the whole thing breaks, because it registers a non existent image to a User and a House. How can I prevent that? Heres my View: def photos_formset(request, *args, **kwargs): pk = kwargs['pk'] ImovelPhotosModelFormset = modelformset_factory(ImovelPhotos, form=ImovelPhotosForm) formset = ImovelPhotosModelFormset( request.POST or None, request.FILES or None, queryset = Imovel.objects.get(pk=pk).imovelphotos_set.all(), ) if formset.is_valid(): for form in formset: if not request.FILES: break if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.imovel = Imovel.objects.get(pk=pk) obj.save() return HttpResponseRedirect('/lares/{pk}/'.format(pk=pk)) context = { "formset": formset, } return render(request, "imovel_photos.html", context) The thing that looked more like a potential answer was this, but it didn't work, if I do this nothing happens: if form.is_valid() and not form.empty_permitted: -
Django @cached_property
I'm trying to understand how Django's @cached_property decorator works behind the scenes. Model: class PersonTest(models.Model): name = models.CharField(max_length=100) @cached_property def friends(self): return "sindhu" My question is in cached_property class based decorator, how does this line gets evaluated? res = instance.__dict__[self.name] = self.func(instance) In the django shell I'm able to see that cached attribute(friends) value is being returned Line1 pt = PersonTest() // instance Line2 res = pt.__dict__[PersonTest.friends.name]=PersonTest.friends.func(pt) Out[23]: 'sindhu' Please explain how line 2 works. Thanks from django.utils.functional import cached_property class cached_property(object): """ Decorator that converts a method with a single self argument into a property cached on the instance. Optional ``name`` argument allows you to make cached properties of other methods. (e.g. url = cached_property(get_absolute_url, name='url') ) """ def __init__(self, func, name=None): self.func = func self.__doc__ = getattr(func, '__doc__') self.name = name or func.__name__ def __get__(self, instance, type=None): if instance is None: return self res = instance.__dict__[self.name] = self.func(instance) return res -
Django DateTimeField TypeError: expected string or bytes-like object
I know there are many posts about this error. Such as: this and this one But I knew already that. And that's why I'm getting crazy. When I create an instance and try to save it, I don't have problems: per_detail.preview_title = per_detail.details_sample.preview_title per_detail.icon = per_detail.details_sample.icon per_detail.content = fill_content(per_detail) per_detail.save() easy. But when there's already the instance, and I try to save it again (updated it). Then I get this error: match = datetime_re.match(value) TypeError: expected string or bytes-like object whit this code: personal_detail_sample = kwargs['instance'] personal_details = PersonalDetail.objects.filter(Q(details_sample=personal_detail_sample)) for per_detail in personal_details: per_detail_updated = fill_updated_content(personal_detail_sample, per_detail) per_detail_updated.save() I gotta say, it doesn't matter where I try to update that instance, I get always the same error. (so, it's not because the kwargs['instance']) And here's the field, that is giving troubles: sent_date = models.DateTimeField(_('sent_date'), null=True, auto_now_add=False, blank=True) As you maybe noticed, I never filled the field "sent_date", but it should be null. So it shouldn't be a problem. And for just being safe, I also tried to do: per_detail.sent_date = *a date* per_detail.save() And I'm getting the same error. I don't have any idea what could it be. Maybe someone can help me. -
Custom label for instance with django-filter
I have Observer model which extends User model via OneToOneRelation. I made filtering for model Checklist which has foreign key to Observer. This is the models.py code: class Observer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) rating = models.IntegerField(default=0) bird_ratings = models.ManyToManyField('BirdName', through='BirdRatings') class Checklist(gismodels.Model): date = models.DateField() time_start = models.TimeField(null=True) time_end = models.TimeField(null=True) site_name = models.CharField(max_length=200) municipality = models.CharField(max_length=200) observer = models.ForeignKey(Observer, null=True, default='') other_observers = models.CharField(max_length=150, default='') note = models.CharField(max_length=2000) location_note = models.CharField(max_length=2000, default='') position = gismodels.PointField(null=True, srid=4326) created = models.DateTimeField(db_index=True, null=True) rating = models.IntegerField(default=0) Then I made ChecklistFilter class in filters.py: class ChecklistFilter(django_filters.FilterSet): date = DateFromToRangeFilter(label='Datum pozorování', widget=RangeWidget(attrs={'display': 'inline'})) #groups = django_filters.ModelMultipleChoiceFilter(queryset=User.objects.filter(), widget=forms.CheckboxSelectMultiple) created = DateFilter(label='Datum vložení') observer = ModelChoiceFilter(queryset=Observer.objects.filter(), label='Pozorovatel') municipality = CharFilter(label='Obec') oblast = CharFilter(label='Oblast') rating = NumberFilter(label='Hodnocení') class Meta: model = Checklist fields = ['date', 'created', 'observer', 'municipality', 'site_name', 'rating'] This is a part of my code from template, where I am using observer field: <div class="col-sm-2"> {{ filter.form.observer.label_tag }} {% render_field filter.form.observer class="form-control" %} </div> But the problem is that I dont't need get observer object but I need last_name from User model which is linked to Observer model. In forms I just extend ModelChoiceField and override label_from_instance() method. But this is not working here. Django-filter … -
How to change stylesheet with Jquery and Django
Hello I've been trying to solve this problem for quite a while. Back when I was using vanilla html this code seems to work. (Changing from tile view to list view). Now that I have incorporated it in django and the hrefs contains static tags, I dont know how to refer to it in jquery and change its href. Pls help HTML <link rel="stylesheet" type="text/css" href="{% static "Stylesheets/tileVersion.css" %}"> I want to change it to this css href <link rel="stylesheet" href="../Stylesheets/listVersion.css"> JQUERY $('#listicon').click(function () { $('link[href="static/Stylesheets/tileVersion.css"]').attr('href', 'static/Stylesheets/listVersion.css'); }); $('#tilesicon').click(function () { $('link[href="static/Stylesheets/listVersion.css"]').attr('href', 'static/Stylesheets/tileVersion.css'); }); I want to be able to switch between them if possible. Any kind of help would be appreciated -
accessing products in a single division Queryset in a ChainedForeignKey
src/ |-- grouping | |-- __init__.py | `-- models.py | `-- products |-- __init__.py `-- models.py grouping/models.py from django.db import models class Category(models.Model): title = models.CharField(max_length=120) class ProductDivisions(models.Model): categories = models.ForeignKey(Category) products/models.py from django.db import models class Product(models.Model): Pdt_category = models.ForeignKey(Category) Pdt_division = ChainedForeignKey(ProductDivisions, chained_field="Pdt_category", chained_model_field="category", show_all=False, auto_choose=True, sort=True) I tried this but its not producing anything, I wanted to get the products specific to a given division in products/Views.py def division(request, slug=None): single_div = get_object_or_404(ProductDivisions, slug=slug) spec_products = Product.objects.filter(Pdt_division=dept) -
Group by / aggregation on an aggregated field in Django
I am trying to translate an SQL query into Django, but am getting an error that I don't understand. Here are the models I have: class Publisher(models.Model): publisher_id = models.AutoField(primary_key=True) publisher_name = models.CharField(max_length=40, blank=True, null=True) class Title(models.Model): title_id = models.CharField(primary_key=True, max_length=12) title = models.CharField(max_length=80) publisher = models.ForeignKey(Publisher, blank=True, null=True) price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) class SaleDetail(models.Model): quantity_shipped = models.SmallIntegerField(blank=True, null=True) title = models.ForeignKey('Title') The data look like publisher table: publisher_name publisher_id -------------------- -------------- New Age Books 736 Binnet & Hardley 877 Algodata Infosystems 1389 title table: title_id publisher_id price ---------- -------------- ------- PC8888 1389 20 PS2091 736 10.95 PS2106 736 7 MC3021 877 2.99 TC3218 877 20.95 BU1032 1389 19.99 ... sale_detail table: title_id id quantity_shipped ---------- ---- ------------------ PS2091 1 75 PS2091 2 10 PS2091 3 20 MC3021 4 20 MC3021 5 15 BU1032 6 3 PS2091 7 3 BU1032 8 5 .... So, there is an N:1 relation between sale_detail and title, and also N:1 between title and publisher. I am trying to compute the total income (price * total-shipped-items) and average income per published book (the same divided by the total books published), for all 3 publishers. The working SQL query is as follows: SELECT P.publisher_name, … -
Patch of module global variable not working
I have a python module - specifically, a Django views module. The module looks something like this (package/views.py): import foo import bar SOME_GLOBAL = 5 def some_view: print(SOME_GLOBAL) I want to unit test some_view, so I create a test like so: # a bunch of imports and test setup -- snip -- @patch(package.views.SOME_GLOBAL, 1) def test_some_view: # some code that uses the django http client to get the response from the view # assert that '1' was printed to the screen, not '5' But the patch doesn't seem to take - the value is still 5, not 1. I've patched other objects in package.views, in the same test even, and they work fine. I just can't see why this one is different. -
How to prefetch a count and use it to annotate a queryset in Django ORM
I’m trying to perform an advanced SQL query but I can’t figure out how to do this. My goal is to implement a read/unread system for a Forum, so i have the followings models (incomplete for : succinctness) class ReadActivity(models.Model): content_object = GenericForeignKey('content_type', 'object_id') reader = models.ForeignKey(User, null=False, blank=False) read_until = models.DateTimeField(blank=False, null=False, default=timezone.now) class Meta: unique_together = (("content_type", "object_id", "reader"),) class Readable(models.Model): read_activities = GenericRelation(ReadActivity) class Meta: abstract = True class Forum(models.Model): pass class Topic(Readable): pass I think this is quite self explanatory : Both topics and forums can be marked as read. A user has zero or one ReadActivity per topic and per forum. So : I want to be able to fetch a forum list, and for each forum determine if it is read or unread (for a given user) My approach is : For each forums, if any topic do not have any ReadActivity or a ReadActivity where read_until < last_message, mark the forum as unread. Speaking SQL, I would do that this in the following way : SELECT COUNT("forums_topic"."id") FROM "forums_topic" LEFT JOIN "reads_readactivity" ON ("forums_topic"."id" = "reads_readactivity"."object_id" AND "reads_readactivity"."content_type_id" = '11') WHERE (("reads_readactivity"."id" IS NULL OR ("reads_readactivity"."reader_id" = '1' AND "reads_readactivity"."read_until" < "forums_topic”."last_message_date")) AND … -
Amazon Elasticbeanstalk deploy django
I'm trying to deploy a django app, then suddenly the following error are throwing on the deploy. Invalid option value: '9.4.5' (Namespace: 'aws:rds:dbinstance', OptionName: 'DBEngineVersion'): Engine Version 9.4.5 not supported for postgres db -
Cant get my queries to show when calling them
I am trying to get the items to show that Im adding to my data base. The problem is I think i have the right code to show but I cant tell if its adding to the database for me to check. Need someone to look at code in question tell me how to fix so i can show stuff or if mabye create function is broke. if I take out the forloop in the index it will show the other html but when forloop is up it doesnt. new.html part that is submitting <form class="" action="{% url 'blackbelt:create' %}" method="post"> {% csrf_token %} <p>Product: <input type="text" name="product" value=""></p> <input type="submit" name="" value="Create"> </form> index.html part that is showing <h2>Your Wish List</h2> <table class="table"> <tr> <th>Item</th> <th>Added By</th> <th>Date Added</th> <th>Remove From Wish List</th> <th>Delete</th> </tr> {% for dog in wishlist%} <tr> <td>{{dog.item}}</td> <td>{{dog.name}}</td> <td>{{dog.created_at}}</td> <td><a href="">Show</a></td> <td><a href="">Edit</td> <td><form action="" method="post">{% csrf_token %}<input class="btn btn-default" type="submit" value="Remove"></form></td> {% endfor%} </tr> </table> views.py def index(request): context = { 'wishlist':Myblackbelt.objects.all() } return render(request, 'blackbeltapp/index.html', context) def create(request): return redirect ('blackbelt:index') from __future__ import unicode_literals from django.db import models from ..logReg.models import User class ProductManager(models.Manager): def add_product(self, postData): user = self.create(item = … -
Can I use existing the existing oscar oscar-api object model to implement a single-item only basket?
I'm working on a modified checkout view that accepts a SINGLE product/price/quantity, customer info (name, address, email) and shipping charges. QUESTION: Can I use the existing django-oscar-api methods for this? In other words, I'd like to enforce a basket model that contains only a single product and uses (LIFO) last in first out when making updates. Here is my first attempt at it: # This method is a hybrid of two oscarapi methods # 1. oscarapi/basket/add-product # 2. oscarapi/checkout # It only allows one product to be added to the # basket and immediately freezes it so that the # customer can checkout def post(self, request, format=None): # deserialize the product from json p_ser = self.add_product_serializer_class( data=request.data['addproduct'], context={'request': request}) if p_ser.is_valid(): # create a basket basket = operations.get_basket(request) # load the validate the product product = p_ser.validated_data['url'] # load the validated quantity quantity = p_ser.validated_data['quantity'] # load any options options = p_ser.validated_data.get('options', []) #validate the basket basket_valid, message = self.validate( basket, product, quantity, options) if not basket_valid: return Response( {'reason': message}, status=status.HTTP_406_NOT_ACCEPTABLE) # add the product to the validated basket basket.add_product(product, quantity=quantity, options=options) # apply offers operations.apply_offers(request, basket) ###### from oscarapi.views.checkout # deserialize the checkout object and complete the order … -
why can't I log in to django admin
So yesterday I installed Python/Django on to my computer using these commands ls cd desktop ls Sudo easy_install pip Sudo pip install virtualenv Virtualenv tryTen Ls Cd tryTen Source bin/activate Pip freeze Ls pip install Django==1.10 pip freeze django-admin.py startproject tryTen ls cd tryTen ls python manage.py migrate python manage.py createsuperuser Ls python manage.py runserver The admin page eventually popped up and I was able to log in successfully. After I was done I pressed control + c and closed the window. I figured I would just start off from where I finished yesterday. But to my surprise when I tried to log in a few minutes ago using python manage.py createsuperuser I was told the file does not exist on my computer, but the file is right here. I also entered http://127.0.0.1:8000/admin/ into the search bar, but it can't be reached. I must be doing something wrong, but what is it? I'm confused. Do I have to write in all those commands again just to log in? Please help. -
Generic forms in Django
I'm trying to create a generic form flow, as in, you give it the model you want and it adapts to it, as seen in the answer here How to create generic forms in Django) Code from the question : def get_custom_form(model, fields): class _CustomForm(forms.ModelForm): class Meta: model = model fields = fields return _CustomForm My questions is, I'm not sure how Django handle modules instances and sessions, so would it be better to create an generic model object during execution, or create a procedure that will write python classes in the forms.py file, creating a form for each model in your models.py? -
Django - Model with lists in a CharField
Small dilemma here; I want to allow users to create a list of tasks (via a model form) which will be stored in the database for them to read or update each of the fields in future (so to mark a task as completed for example). In the model I've created something like this... tasks_to_do = models.CharField(max_length=300, null=True) However, I want users to be able to add as many or as few different tasks as they want. Should I do something like... task_1 = models.CharField(max_length=100, null=True) task_2 = models.CharField(max_length=100, null=True) task_3 = models.CharField(max_length=100, null=True) etc., which seems quite tedious/wasteful of code. Or should I somehow try to store a series of strings as a list? Apologies for the lack of code; very unsure about how to approach this problem as I haven't come across anything like this before. Thanks in advance! -
Why can my Django server only be visited locally?
So I have run my server with python manage.py runsslserver xx.xx.x.xx:443 Now I can visit the site on the server itself, but if I try to visit it from another machine, it times out. Looking at the command prompt, the server doesn't seem to even know about my request from the other machine. But if I run the server with python manage.py runserver xx.xx.x.xx:80 I can visit it from both machines no problem. With the ssl, I've tried a number of ports, it makes no difference.