Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why don't I see any Django, AngularJs or any templates in my Pycharm IDE?
Pycharm IDE Screenshot As you saw on the screenshot, when I purchased Pycharm Ide, Nothing comes with Django, Angularjs. Actually, There was Django, Angular Js on trial version. Why not autmatically seeing them on my IDE? Thanks in advance! -
Django create table from non-Queryset context data
I need to aggregate data from an Order table to be able to determine the total amount of items sold per date . My order model looks like this: class Order(models.Model): guest = models.ForeignKey('hotel.Guest', on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) amount = models.IntegerField() item = models.ForeignKey('hotel.Item', on_delete=models.CASCADE) price = models.IntegerField(default=1) is_paid = models.BooleanField(default=False) paid_date = models.DateField(blank=True, null=True) I have now created a view that iterates over time and date: def listAllOrders(request): context = {} orders = Order.objects.exclude(item__name = 'Room Rate') item_dates = orders.values('date') item_date = item_dates.order_by('date').distinct('date') item_ids = orders.values('item__name') item_id = item_ids.order_by('item__name').distinct('item__name') inventory = [] for d in item_date: for i in item_id: q=Order.objects.filter(item__name=i['item__name'], date=d['date']) ta=q.aggregate(total_amount = Sum('amount')) tp=q.aggregate(total_price = Sum('price')) inventory.append([d['date'],i['item__name'],ta,tp]) context['inventory'] = inventory #context = Order.objects.all() return render (request, 'hotel/inventory.html', context) how can I now fill this data in a table in my template. If I give a queryset to context I usually do this like this: <table class="table table-condensed table_orders"> <tr> <th>Date</th> <th>Amount</th> <th>Item</th> </tr> {% for Order in inventory %} <tr> <td>{{ Order.date }}</td> <td>{{ Order.amount }}</td> <td>{{ Order.item }}</td> </tr> {% endfor %} </table> This obviously doesn't work here because the data in inventory is not structured.. how can I solve this? -
Django default callable referencing to another field of the model
I have a model that represents pages of a book. class BookPage(models.Model): def getMaximumPageNumber(): page_numbers = (i.page_number for i in BookPage.objects.all()) return max(page_numbers)+1 page_number = models.IntegerField(default=getMaximumPageNumber, validators=[MinValueValidator(1)]) book = models.ForeignKey('Book', on_delete=models.CASCADE) //other stuff I want Django to assign a page number automatically upon creation, so I made getMaximumPageNumber(). It would work fine if I had only one book. But now I want to reference the book from inside this function, so it would be something like page_numbers = (i.page_number for i in BookPage.objects.filter(book=self.book). But the problem is that I can't seem to use self in this function, because if I specify it as def getMaximumPageNumber(self):, then it would show the TypeError: getMaximumPageNumber() missing 1 required positional argument: 'self' when I try to access add page screen in admin. Therefore I cannot specify the book I want to find the maximum page of, and this is what I really need to accomplish here. Is there a way to reference another field of a newly created instance of a model from a default-assigning function? My initial solution was to override the save() of this model, but it breaks down some other things I've already written, so using a dynamic "default" would be … -
Changing callable for upload_to breaks migrations Django
I had a callable for my image uploads which looked like this: @deconstructible class Rename(object): def __init__(self, path): self.path = path def __call__(self, instance, filename): # some stuff and returns path when I changed the __init__ signature to : def __init__(self, path, file_type): self.path = path self.file_type = file_type I can no longer run makemigrations: File "/pathtomyapp/migrations/0001_initial.py", line 59, in Migration ('avatar', models.ImageField(blank=True, null=True, upload_to=myapp.models.Rename(b'profiles'))), TypeError: __init__() takes exactly 3 arguments (2 given) Is there any way to solve this without modifying Rename functions signature in migration files -
django-registration-redux custom user model login only working via /admin/
I am using a custom user model for my Django project and I can log in via /admin/ perfectly fine. But when I go to /accounts/login and try to log in, it just bounces me back to the login page without logging in. I am using django-registration-redux with the simple backend. Via logging I discovered that the error happens in this method in django.contrib.auth.__init__.py: def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `AnonymousUser` is returned. """ from .models import AnonymousUser user = None try: # # EXCEPTION THROWN ON BELOW LINE # user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: request.session.flush() user = None return user or AnonymousUser() Any ideas? /accounts/register/ performs as expected, although I have overridden RegistrationView. Perhaps I have to do the same thing for logging in? Login.html {% extends "base.html" %} {% load staticfiles %} {% block body_block %} <link href="{% static 'css/signin.css' %}" rel="stylesheet"> <div class="container"> <div class="jumbotron"> … -
Conditionals not working properly in Django Template
In the code below, educationData is an zip of a database query result and a range function. I have got a completely similar conditional in the same HTML page. Now the problem is that, every time just one of them works, i.e if the conditional below works then the other one does not. {% if educationData != 'unavailable' %} {% for edu, counter in educationData %} <div class="row"> <div class="circ"></div> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{counter}}" aria-expanded="false"aria controls="collapse{{counter}}" class="collapsed expand-date">{{edu.year}}</a> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="heading{{counter}}"> <h4 class="panel-title"> <span aria-controls="collapse{{counter}}"> <span class="accordion-heading">{{edu.education_type}}</span> </span> </h4> </div> <div id="collapse{{counter}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading{{counter}}"> <div class="panel-body"> <h4 class="timeline-title">Started <span><strong>{{edu.education_type}}</strong></span> at <span><strong>{{edu.institution_name}}</strong></span></h4> <div class="timeline-body"> <p>{{edu.what_did_you_do_there}}</p> </div> </div> </div> </div> </div> {% endfor %} {% endif %} {% if educationData == 'unavailable' %} <p>Not Available</p> {% endif %} Please help. Stuck :( -
Get a user all followers list on twitter using Django framework without using tweepy
I am new python developer working on django framework. I am trying to get a user's all followers list but I don't know how to get this followers list. I have already user access token and access secret token. I don't want to use tweepy in my code. Please help me to resolve this issue. Thanks :) -
Add custom button to django admin panel
I want to add button to admin panel to my model, I have overwrite template (path: templetes/admin/myapp/mymodel/change_list.html) change_list.html {% extends "admin/change_list.html" %} {% load i18n admin_static %} {% block result_list %} <div class="object-tools"> <a href="{% url 'myurl' %}" class="btn btn-high btn-success">Import</a> </div> {{ block.super }} {% endblock %} In admin.py class ImportEvisAdmin(admin.ModelAdmin): change_list_template = 'admin/myapp/mymodel/change_list.html' But I can not see the button. -
CORS during development without Access-Control-Allow-Origin
The server answer with a Access-Control-Allow-Origin value set for the production. Is there a way to be permissive when the requests come from my development server ? Is there a Django setting to disable the cross-origin check when DEBUG=True for example ? I can't modify the Access-Control-Allow-Origin. The request is made with jquery ajax function. -
Django==1.10 redirect from non www to www
In settings of my Django app I have the following: ALLOWED_HOSTS = ["www.example.com", "example.com"] In namecheap dns settings: CNAME Record -> www -> python anywhere app URL Redirect Record -> @ -> http://www.example.com And example.com successfully redirects to www.example.com. But the problem is that the example.com/about and all the other example.com/"path"/ URLs also redirect to www.example.com instead of www.example.com/"path". How can I fix it and make them point to the correct destination? P.s if I remove URL Redirect Record -> @ -> http://www.example.com from dns settings any example.com/"path"/ will return 400 Bad Request. -
Django allauth and rest framework for account signup and login
I need to make custom views for signup and login implementation on django rest framework for doing rest call. I have seen the sign-up view and login view provided by allauth which use loginForm and signupForm. But i do not know how to work them out with restframework for api calls. Also i need csrf token security. Can anyone help me out with this? -
Django unable to connect to MySQL server
I have a Django version (1.10) which is installed on my MacBookPro (El Capitan OS X) and I would like to connect the API to my MySQL Database which is located on a distant server (Ubuntu - same network as my job network). I get this error when I'm running the Django server : django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.30.10.58' (61)") This is my settings.py file from my project : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Etat_Civil', 'USER': 'root', 'PASSWORD': 'password', 'HOST': '172.30.10.59', 'PORT': '3306', } } On my Mac I installed mysqlclient / mysql connector/python I don't work with a virtual environment because I just have one project in my laptop. So it's not necessary to isolate Python. I think that's maybe a permission problem but I don't really know How configure that. I found some tutorials but I get problems each time. Do you have some ideas ? Thank you so much ;) -
Joining unrelated models and filter the queryset
I have the following Models I would like to join: Datapoint class Datapoint(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition', blank=True, null=True) # Field name made lowercase. value = models.IntegerField(db_column='Value') # Field name made lowercase. Composition class Composition(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. DataComponent class Datacomponent(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. composition = models.ForeignKey(Composition, models.DO_NOTHING, db_column='Composition_ID', null=True, blank=True) # Field name made lowercase. components = models.ForeignKey(Components, models.DO_NOTHING, db_column='Components_ID') # Field name made lowercase. componentvalue = models.FloatField(db_column='ComponentValue') # Field name made lowercase. And finally, Component class Components(models.Model): id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=45, blank=True, null=True) # Field name made lowercase. Each datapoint contains a foreign key to the composition table. Datapoint and Composition tables are hence related. Each composition has many components which is linked by composition field in Datacomponent table which also contains components foreign key to the Component table. The end goal is to build a list of Datapoint objects filtered by a particular component value in Datacomponents table. For instance lets say we have a … -
how to package django project to .deb package?
my django project contains multiple applications and running through the project with runserver. i want to give this entire project as a .deb package ? in this project am using MySQL as database. can give me step by step process to .deb conversion and any other best methods to give my entire django project as one package. -
Django 1.9, custom middleware + 404 error
I have written custom middleware which checks invites from users. The idea is to restrict the access to the website for users without invites. Everything is woking fine, except that users can see parts of the site when 404 or any other exception occurs and I don't want it. I am using Django 1.9. In previous versions (as I remember) there was Exception middleware, but now I don't see it. I tried to put my middleware on the top of the stack but it doesn't help. What else can I do? Thanks! -
Django weighted query (annotated values)
I am attempting to created a query and sort it based on a custom calculation of weights. I require some help as the solution I have come to does indeed work but the performance is not where I'd like it to be What I have is a Media object. It has related Comments, Likes and Orders. What currently works but is a complete hacky mess is the following query: products = Media.objects \ .select_related( 'image', 'currency', 'user', 'user__image', ) \ .prefetch_related('category', 'tags') \ .exclude(is_deleted=1) \ .filter(Q(category__category__in=categories) | Q(tags__tag__title=query)) \ .annotate(order_count = Count('orders', distinct=True)) \ .annotate(comment_count = Count('comments', distinct=True)) \ .annotate(like_count = Count('likes', distinct=True)) \ .annotate(weight = Count(0)) \ .distinct() for m in products.iterator(): initial_weight = int(m.order_count)*40 + int(m.comment_count)*4 + int(m.like_count)*4 + int(m.clicks) m.weight = float(float(initial_weight) - float(m.views/50)) As you can see I am separately annotating all the parameters I'll be using and then doing a stupid iteration full of arithmetic operations for EVERY item in the queryset which is very sub optimal. One thing I attempted doing was the following: products = Media.objects \ .select_related( 'image', 'currency', 'user', 'user__image', ) \ .prefetch_related('category', 'tags') \ .exclude(is_deleted=1) \ .filter(Q(category__category__in=categories) | Q(tags__tag__title=query)) \ .annotate(weight = Count('orders', distinct=True) * 40 + Count('comments', distinct=True) * … -
How can I give dynamic timeperiod to periodic task in django celery
I have a task to send remind mails to my users before one hour of specific occasion. How can I set the time of periodic task ? Thanks -
Django-carton work with two Product models
I am using Django-carton (https://github.com/lazybird/django-carton) and I wonder if it is possible to associate more than one model as a Product model. Right now, I have a base class Product which I registered as my product model and I inherited Pub and Restaurant from it. The problem I face is, cart.show() basically returns all product objects in the cart which only have products attributes and not Pub's or Restaurant's, and I can not distinguish which one is Pub and which one is Restaurant. -
How to return all records but exclude the last item
I'm having problem filtering in django-models. I want to return all records of a particular animal but excluding the last item based on the latest created_at value. I have this model. class Heat(models.Model): # Fields performer = models.CharField(max_length=25) is_bred = models.BooleanField(default=False) note = models.TextField(max_length=250, blank=True, null=True) result = models.BooleanField(default=False) # Relationship Fields animal = models.ForeignKey(Animal, related_name='heats', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) I was able to achieved the desired result by this raw sql script. But I want a django approach. SELECT * FROM heat WHERE heat.created_at != (SELECT MAX((heat.created_at)) FROM heat) AND heat.animal_id = '2'; Please help. -
ImportError: No module named 'celery' in proj/proj/celery.py
I have been following the tutorial in Celery: First steps with django proj/proj/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) proj/proj/init.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] sampleapp/tasks.py: # Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers) I'm pretty sure I correctly followed it however i got an error message when I start running python3 manage.py runserver This is the error message: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) … -
Webservice: expensive initial resource aquisition
I am building a webservice which will present a read-only view to a set of binary files in a proprietary format - I have a working library to read and query the content of the files. Schematically I see something like this happening: HTTP GET /file_id/element_id/ Invoke library to load from disk instance = FileLoad( file_id ) Query the instance: value = instance.getElement( element_id ) and return to browser. Now the point is that step two can potentially be quite heavy, and a typical usage pattern will be that the same user has multiple calls to get different elements from the same file instance. Is there a pattern or good practices I should look into to implement a pool of in-memory FileLoad instances? I am using Django - if that matters. -
How to set a default handler for "CSRF verification failed" in django?
According to the Django documentation, we can set the a default error handler like this: handler403 = 'mysite.views.my_custom_permission_denied_view' ... My handler for 404 and 500 is working fine. But in case of access forbidden, I can't trigger it (when I raise HttpResponseForbidden, the triggered handler is the handler for error 500). Anyway, that's not my problem. My problem is when I try to tamper (for testing purposes) the CSRF token, it throws "Forbidden" but again, my handler for access forbidden is not invoked - it invokes the default django template for 403 forbidden. And when I try to access the root directory of static (or media) directory, the invoked page is from the servers default forbidden page (apache httpd in my case) which is fine. My question is: How to set default handler for "CSRF verification failed"? What are the cases that the 403 handler is being called? How can I trigger a 403 forbidden error? Here is my setup: Python 3.4 Django 1.10 (production, debug = False) Server: Apache httpd through mod_wsgi Windows 7 32bit -
Getting "Invalid address" error on gunicorn bind with my server ip . i am trying this within the docker
Getting "Invalid address" error on gunicorn bind with my server ip . i am trying this within the docker . [docker-compose.yml fileerror message[nginx configuration file] -
Django Rest Framework with Multiple Viewsets and Routers for the Same Object
I am having trouble defining different view sets for the same object using Django Rest Framework. Following is a minimal example to reproduce the issue, based on DRF Quickstart. I am using python 3.5 and the latest DRF. tutorial/quickstart/serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email') class UserMinimalSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username') tutorial/quickstart/views.py from django.contrib.auth.models import User from rest_framework import viewsets from tutorial.quickstart.serializers import UserSerializer, UserMinimalSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class UserMinimalViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserMinimalSerializer tutorial/urls.py from django.conf.urls import url, include from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'users-minimal', views.UserMinimalViewSet) urlpatterns = [ url(r'^', include(router.urls)) ] When running the server and GETting the root, you end up with: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "users": "http://127.0.0.1:8000/users-minimal/", "users-minimal": "http://127.0.0.1:8000/users-minimal/" } Note both users and users-minimal point to .../users-minimal/. Also, when accessing http://HOST:PORT/users/ you get: HTTP 200 OK Allow: GET, POST, OPTIONS Content-Type: application/json Vary: Accept { "count": 2, "next": null, "previous": null, "results": [ { "url": "http://127.0.0.1:8000/users-minimal/2/", "username": "user2", "email": "user2@users.com" }, { "url": … -
ValueError: Empty key names are not allowed when using collectstatic django
I am using django-pipeline [S3PipelineManifestStorage][1] with django-storages When I use collectstatic to upload and post-process(minify) my assets, I get an error when post-processing. Earlier, collectstatic worked fine and gave no error. Here's the full traceback Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 168, in handle collected = self.collect() File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect for original_path, processed_path, processed in processor: File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/storage.py", line 26, in post_process packager.pack_stylesheets(package) File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/packager.py", line 96, in pack_stylesheets variant=package.variant, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/packager.py", line 105, in pack paths = self.compile(package.paths, force=True) File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/packager.py", line 34, in paths return [path for path in self.sources File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/packager.py", line 26, in sources for path in glob(pattern): File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/glob.py", line 18, in glob return sorted(list(iglob(pathname))) File "/app/.heroku/python/lib/python2.7/site-packages/pipeline/glob.py", line 29, in iglob if staticfiles_storage.exists(pathname): File "/app/.heroku/python/lib/python2.7/site-packages/storages/backends/s3boto.py", line 445, in exists k = self.bucket.new_key(self._encode_name(name)) File "/app/.heroku/python/lib/python2.7/site-packages/boto/s3/bucket.py", line 623, in new_key raise ValueError('Empty key names are not allowed') ValueError: Empty key names are not allowed Could you please figure out why this error …