Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding the Update method of Django queryset
As part of one of the requirement, we are overriding the Update method in the custom Queryset. Sample code is as follows. from django.db.models.query import QuerySet class PollQuerySet(QuerySet): def update(self, *args, **kwargs): # Some Business Logic # Call super to continue the flow -- from below line we are unable to invoke super super(self, kwargs) class Question(models.Model): objects = PollQuerySet.as_manager() question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') It is unable to invoke update in base Queryset from the Custom Queryset. TypeError at /polls/ must be type, not PollQuerySet Any solution is much appreciated. -
django max and groupby together
I have a model which looks like this player_info, game, score, creation_date I want to fetch the records with the highest score of each player for a particular game. Any help is appreciated. -
Django - can't run makemigrations: "no such table" even after running reset_db
I am unable to run makemigrations, migrate, or anything else (flush, reset_db from django-extensions) if I have a certain app in my INSTALLED_APPS. The app is called issues and has one model: class Issue(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=1000) sent = models.BooleanField() And it was working before (makemigrations and migrate ran fine and I could use the app/model correctly), until I tried adding: severity = models.IntegerField() and tried to run makemigrations. I don't have the error or remember it anymore, but since then everything is broken, even after removing severity from the model. Everything works if I remove the issues app from my settings.py. The error I get: madjura@madjura-E6228:~/workspace/budget/src$ python3.5 manage.py makemigrationsTraceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 337, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: issues_issue The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.5/dist-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/madjura/workspace/budget/src/issues/apps.py", line 16, in ready issues.models.Issue.objects.check_and_send_unsent_issues() File … -
How to make infinite threaded comments
My current code allows me to render a queryset of Comments (parent comments) as well as replies to those comments. But i'm unable to render replies to those replies. My goal is to have an infinite reply system. Here's my code: class Comment(models.Model): user = models.ForeignKey(User, blank=True, null=True) destination = models.CharField(default='1', max_length=12, blank=True) parent_id = models.IntegerField(default=0) parent_comment = models.ForeignKey('self', related_name='replies', related_query_name='replies', blank=True, null=True) comment_text = models.TextField(max_length=350, blank=True, null=True) timestamp = models.DateTimeField(default=timezone.now, blank=True) children = models.IntegerField(default=0) def __str__(self): return str(self.comment_text) my parent comment view: def user_comment(request): if request.is_ajax(): comment = CommentForm(request.POST or None) ajax_comment = request.POST.get('text') id = request.POST.get('id') comment_length = len(str(ajax_comment)) if comment.is_valid() and request.user.is_authenticated: comment = Comment.objects.create(comment_text=ajax_comment, destination=id, user=request.user) username = str(request.user) return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username, 'id': comment.id}) else: return HttpResponse() and my reply view: def comment_reply(request): if request.is_ajax(): comment = CommentForm(request.POST or None) reply_text = request.POST.get('reply_text') id = request.POST.get('id') parent_id = request.POST.get('parent_id') parent = Comment.objects.get(id=parent_id) parent.children += 1 parent.save() if comment.is_valid() and request.user.is_authenticated: comment = Comment.objects.create(comment_text=reply_text, destination=id, user=request.user, parent_id=parent_id, parent_comment=parent) username = str(request.user) return JsonResponse({'reply_text': reply_text, 'username': username}) else: return HttpResponse() ajax calls var str = window.location.href.split('?')[0]; var path = str.split("/")[4]; $('.comment_form').on('submit', function(e) { e.preventDefault(); var c = $(this).find('.comment_text').val() console.log('this:', c); $.ajax({ type: 'POST', url: … -
How to mix Sum and arithmetic with Django queryset
I 've got this in my code : forcasting_order = ProductLine.objects.values('product_name', 'product_id')\ .filter(delivery_date__date__in=ref_days, order_date__date=Func(F('delivery_date'),function="date"))\ .annotate(quantity_to_order=Sum('quantity'))\ .order_by('product_id') for x in forcasting_order: x['quantity_to_order'] = round(x['quantity_to_order'] / Command.avg_on_x_week) Is there a way to divide Sum('quantity') by a constant integer (Command.avg_on_x_week here) inside the query ? -
Django receive e-mails and their attachments
In the app I am working I want to get the my e-mails ,let's say from my gmail account. So I setted up with a class that stores the e-mail adress,port, server and password. I created a function where I get the Subject,Body and From sections, from the gmail account e-mails and I am backing up the mails in a backup folder with ".eml" extension. Also, I have a "mail-list.html" template where a list is being displayed with the above headers and content. All good till here. Now how can I get the attchment,if any of a message,so I can show in my "mail-list.html" template if there is one. This stuff with the e-mail is completely new to me so any example code or even pointing me to a direction would be great! I have checked out some pluggins such as django mailbox, but I want it to be my last resort. -
Static files do not load when deployed to Heroku (but does in local server) when DEBUG = false?
I've been scouring all over StackOverflow searching for a solution, but none of them seems to be working. I can't get my static files for my Django web app to load when I deploy it to Heroku. It works fine in localhost:8000 though. This is only when I set DEBUG = False . It works fine when DEBUG = True. My static files basically consist of several images for the home page and 1 CSS file. My main project directory is mynotes. My app directories are mynotess and users settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'w2!3r+pgqz6yhwi_+aw_!-yra7#h69z-n3-ni$gs2v+!!k^2$b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'mynotess', 'users', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mynotes.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mynotes/templates')], #originally empty 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, … -
Swagger Implemetation in Djnago
I have completed the setup of the swagger API, but the problem I am facing is, the parameter which I want to give to the API view are not coming in the Swagger UI. The image showing the Swagger UI -
Django Chart.js 1.1
I didnt find any information about tooltips in chart.js 1.1. Does anyone know how to show them? It looks like there are no tooltips in chart.js 1.1. If so - how to implement them? Does anyone had same problem? Thanks for answers. -
Django dumpdata Unable to serialize database: Could not decode to UTF-8 column
I have a sqlite db which I want to dump. I use the command $ python manage.py dumpdata > dump.json But I get the following error: CommandError: Unable to serialize database: Could not decode to UTF-8 column 'sm s_data' with text '[{"body": "Amarnath Dutta 70229989899", "date": "Thu Feb 16 18:08:52 GMT+05:30 2017", "direction": "SENT", "address": "9845370953"}, {"body": " How do I dump the data? -
Django Query with conditional function When (?)
I have a database of a diner: class Product(models.Model): name = models.CharField(max_length=250) sides = models.ManyToManyField(Sides, blank=True) price = models.DecimalField(max_digits=5, decimal_places=2) def __unicode__(self): return '%s %s %s' % (self.name, self.sides, self.price) def __repr__(self): return unicode(self).encode('utf-8') class Menu(models.Model): date = models.DateField() product = models.ForeignKey(Product) def __unicode__(self): return '%s %s' % (self.date, self.product) def __repr__(self): return unicode(self).encode('utf-8') class Order(models.Model): date = models.DateField() user = models.ForeignKey(User, null=True) def __unicode__(self): return '%s %s' % (self.date, self.user) def __repr__(self): return unicode(self).encode('utf-8') class OrderItems(models.Model): order = models.ForeignKey(Order) product = models.ForeignKey(Menu, null=True, blank=True) quantity = models.IntegerField(default=0) take_away = models.BooleanField(default=False) def __unicode__(self): return '%s %s %s %s' % (self.order, self.product, self.quantity, self.take_away) def __repr__(self): return unicode(self).encode('utf-8') I need to search the database for the cost of dishes ordered by my users in a given period, so the first query is quite simple: report = OrderItems.objects.filter(Q(order__date__range=(strfrom, strto)), ~Q(order__user_id=None)) The problem begins when it comes to calculation of total cost per user in this period, because I have to add 1 to each item that has been marked as take away (boolean field). My query so far, that ignores the boolean field, is like that: per_person = report.values('order__user').annotate(per_capita=Sum(F('quantity')*(F('product__product__price')), output_field=DecimalField())) My question is: how can I add 1 to each item price … -
"Sorry, something went wrong." message when sharing on facebook using share dialog
I am using django to share a page on facebook. I use the below code to url var link = 'https://www.facebook.com/dialog/feed?app_id=1234567890&display=popup&name=' + name + '&description=' + description + '&picture=' + picture + '&link=' + caption + '&caption=' + caption + '&redirect_uri=' + redurl; window.open(link, "Share", windowFeatures); The url that finally gets formed is as below https://www.facebook.com/dialog/feed?app_id=1234567890&display=popup&name=GameStore:%20come%20and%20play!&description=Hey%20!!!%20I%20am%20playing%20to%20Breakout&picture=https://res.cloudinary.com/dma8tn6ge/image/upload/c_fill,h_75,w_75/profile-picture.png&link=http%3A//localhost%3A8000/game/player/1/&caption=http%3A//localhost%3A8000/game/player/1/&redirect_uri=http://localhost:8000/fb_redirect This is triggered from a button click event in javascript. But when I click it the window opens with the message : Sorry, something went wrong. We're working on getting this fixed as soon as we can. p.s. I obviously use the correct app id in my code and not 1234567890. Could somebody guide me what am I dong wrong -
Update parent model from fake Inline model in django admin
The Number model is fake model without table and i shouldn't save it. All i need is save all inlines Number.number as Message.receiver. But save_model calls first and after saving Message cals save Number which just pass. I need to acces parent Message model from Number inline model. I tried to overload save_model() from NumberAdmin but wit no success. I know what design is bad but it is legacy. models.py class Message(models.Model): receiver = models.BigIntegerField() text = models.TextField(blank=True, null=True) class Meta: db_table = 'messages' def __str__(self): return "{}".format(self.text) class Number(models.Model): message = models.ForeignKey("Message", related_name='receivers') number = models.BigIntegerField() class Meta: verbose_name = "ReceiverNumber" verbose_name_plural = "ReceiverNumbers" managed = False def __str__(self): return self.number admin.py class NumberInline(admin.TabularInline): model = Number extra = 0 fields = ('number',) class NumberAdmin(admin.ModelAdmin): class Meta: model = Number class MessageAdmin(admin.ModelAdmin): inlines = (ReceiverNumberInline,) class Meta: model = Message -
Django button with javascript alert
I'm improving my Django website and I would like to add javascript button with window alert when users clicked on this button. I made that in my HTML template but I'm not sure How I have to write this. My script looks like : <button onclick="myFunction()"> <form class = "col-sm-10" method='POST' action="{% url "PDF" birthcertificate.id %}"> {% csrf_token %} <input class = "button" type ="submit" value="Générer le PDF des acte de naissance" /> </button> <script> function myFunction() { alert("Votre PDF a été généré"); } </script> </form> But I get this kind of display : I got 2 buttons, but I want to display only the bootstrap style. Do you have any idea ? Thank you ;) -
how to select boolean fields in django model
I have 2 models in different apps: class Stock(models.Model): vsej_seti = models.BooleanField(default=False, verbose_name=_('Все сети')) and class Hotel(ServioResource): stock_all = models.ForeignKey('content.Stock', related_name='st', null=True, blank=True) Please help me to write a method which sort all booleanfields with true parametr. In sql it looks like "SELECT * FROM content_stock WHERE vsej_seti=1". I wrote smth like this, but it doesn't work. Thanks def qqq(self): f = False if self.stock_all.vsej_seti == f: return self.stock_all.vsej_seti -
How can I call a function within a DRF view?
I am using Djano REST Framework for constructing APIs .I want something like below def addTwoNumber(a,b): return a+b class MyView(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): my_result=addTwoNumber(request.data.get('firstnum'),request.data.get('secondnum')) return Response(data={"my_return_data":my_result}) That is , I want a view that doesn't deals with the queryset &serializer_class attributes. Is it possible ? Can anyone help me ? -
Python library for portfolio management [on hold]
I'm currently developing a stock market application. The server side being implemented in Django, the client side is in Android. I am aiming to complete a very basic Portfolio Management/Tracking feat in a week. Hence I was looking after an already implemented code available for the same. Right now, I'd only want APIs to BUY/SELL stocks & profit/loss reporting which I can tweak to fetch data from my saved data sources instead of yahoo/google. I'm sure reusing the already implemented code would be a better idea instead of re-inventing the wheel of defining data models for Stock, an engine which makes required calculations in case of BUY or SELL. Maintains the data in database efficiently and provides easy APIs to retrieve the current portfolio. Profits/Losses etc. Is anyone aware of any such simplistic libraries in python? I'm using django 1.10.1 & python 3.5, Thanks. -
AttributeError: 'FileField' object has no attribute 'model'
I get AttributeError: 'FileField' object has no attribute 'model' whenever i run python manage.py makemigrations and python manage.py migrate models.py from __future__ import unicode_literals from django.db import models #Create your models here. class Slider(models.Model): slider = models.FileField() slider_title = models.CharField(max_length=20) def __str__(self): return self.slider_title class ShopCategories(models.Model): category = models.CharField(max_length=50, unique=True) def __str__(self): return self.category class NewShop(models.Model): category = models.ForeignKey(ShopCategories) main_image = models.FileField() name = models.CharField(max_length=100, unique=True) tagline = models.CharField(max_length=50, default='Enter tagline here2') description = models.TextField(default='enter shop description') shop_image = models.FileField() def __str__(self): return self.name -
How to scrape an image list in detail pages with django-dynamic-scraper?
(Sorry, my English is not very well, but I'm working on it.) I can scrape the full news list and their contents, but most content pages(detail page) have an image list,how can I scarpe each list and save the images? -
Django: How do I know what the file uploaded is renamed to when multiple files with the same filename are uploaded
I have set up a Django service to perform some operations on an image uploaded using a function myFunction(). When two users upload a file called file.jpg, one gets renamed by get_avaiable_name(). I am not able to figure out the new filename and the function performs the operation on file.jpg twice. How can I print this filename or obtain the new filename so that I can send it to another function. My set-up: models.py UPLOAD_PATH = 'uploads/' class RequestModel(models.Model): file = models.ImageField(upload_to=UPLOAD_PATH, blank=False) class RequestForm(ModelForm): class Meta: model = RequestModel fields = ["file"] error_messages = { NON_FIELD_ERRORS: { 'unique_together': "%(model_name)s's %(field_labels)s are not unique.", } } view.py: def run_for_image(request, name=None): if request.method == 'POST': print request.FILES form = RequestForm(request.POST, request.FILES) if form.is_valid(): form.save() content = myFunction("uploads/" + request.FILES['file'].name) response = HttpResponse(content, content_type='application/json') response['Content-Length'] = len(content) return response What can I send as the first parameter to myFunction() so that it runs on the correct image. -
Django Admin: row in list view links to related list view
I have 2 related models: model Building(models.Model): name = models.CharField(max_length=20) model Appartment(models.Model): field1 = models.CharField(max_length=20) building = models.ForeignKey(Building) In the admin list view of Building I want in each line a link to the Appartment list view with activated filter for the respective building. Is that easily doable with the Modeladmins? -
TypeError at /accounts/tcresults
I got an error, TypeError at /accounts/tcresults 'ImageAndUser' object is not iterable . I wanna show user's data from database in tc.html,but this error happen. I wrote in views.py def tc(request): d = { 'tcresults': ImageAndUser.objects.filter(user=request.user), } return render(request, 'registration/accounts/tc.html', d) in tc.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>tc</title> </head> <body> <h2> {% for result in tcresults %} {{ result.tc }} {% endfor %} </h2> </body> </html> I wanna show the data in this part {% for result in tcresults %} {{ result.tc }} {% endfor %} I can understand this error meaning, because I designated latest user data ,so the data is only one and it cannot be repeated.But I cannot know how to fix this.How should write it? -
Python: learning multiple web frameworks?
I was wondering if there was any benefit to learning 3 different frameworks with python? (flask/pyramid/django). I am familiar with their differences and why we would use one over the other, but assuming that all the applications i will end up building can be done equally as easily... is there any point to learn multiple frameworks? I feel i could just be wasting time learning different web frameworks, where i should probably spend more time learning about Containers or something i dont know much about. Would definitely like a reason to learn multiple frameworks other than just writing it on a resume. -
Django: Importing a view from another app
I have a project and an app. I am trying to use the urls.py in the project to activate a view held in the app. The error message: import homepage.index ModuleNotFoundError: No module named 'homepage.index' In the project urls.py I have this import statement: project/urls.py from homepage.views import index Then in the project's urls.py, the urlpatterns[] array includes this reference to the app's view: `urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', homepage.views.index, name='index'),` ] homepage/views.py def index(request): return HttpResponse("My Homepage") Where might be the error? -
Django on Heroku : OperationalError at / could not connect to server: Connection refused
When I try to open my heroku app I get the following error: OperationalError at / could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I'm running on Windows 10, I'm assuming this is an error with my Postgres Database, but I'm not sure. Here are my django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'campus', #'NAME': os.path.join(BASE_DIR, 'db.postgresql'), 'USER': 'djangomigrator', 'PASSWORD': 'migratorpass', 'HOST':'localhost', 'PORT': '5432', } } Heroku logs: 2017-02-20T04:59:22.817966+00:00 app[web.1]: Internal Server Error: / 2017-02-20T04:59:22.817984+00:00 app[web.1]: Traceback (most recent call last): 2017-02-20T04:59:22.817985+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner 2017-02-20T04:59:22.817985+00:00 app[web.1]: response = get_response(request) 2017-02-20T04:59:22.817986+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response 2017-02-20T04:59:22.817987+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2017-02-20T04:59:22.817988+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response 2017-02-20T04:59:22.817989+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2017-02-20T04:59:22.817989+00:00 app[web.1]: return render(request, 'app/index.html', context) 2017-02-20T04:59:22.817989+00:00 app[web.1]: File "/app/app/views.py", line 13, in index 2017-02-20T04:59:22.817990+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/shortcuts.py", line 30, in render 2017-02-20T04:59:22.817993+00:00 app[web.1]: content = loader.render_to_string(template_name, context, request, using=using) 2017-02-20T04:59:22.817994+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/template/loader.py", line 68, in render_to_string 2017-02-20T04:59:22.817994+00:00 app[web.1]: return template.render(context, request) 2017-02-20T04:59:22.817995+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/template/backends/django.py", line 66, in render 2017-02-20T04:59:22.817995+00:00 app[web.1]: return self.template.render(context) 2017-02-20T04:59:22.817996+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py", line …