Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filter against date in djangorestframework
I'm filtering against date in my get_queryset parameter, I found something similar in official djangorestframework documentation, and I'm getting the result. Now how can I limit this filter so I can only display data per date, so for example when you select date it will show you some data for selected date, but it should not show you data from future dates, for now I'm showing all my contacts for today and that is fine, but I'm also showing all my contacts from the future and that is not fine, they should not be displayed, bottom line data should be visible per date so how can I do that. Currently I'm doing this: filter_date = self.request.query_params.get('filter_date', None) if filter_date is not None: queryset = queryset.filter(next_action_date__gt=filter_date) return queryset next_action_date is a DateField: next_action_date = models.DateField(blank=True, null=True) -
How to let website admin save new content
I'm starting to develop a web page for my friend's band using Django and sqlite, deploying to nginx server. However, this question is probably for web development in general. I want to allow him to save new content for the pages through the web site itself, probably in html-format. How should I implement it? Saving to a database seems to me misuse of database, because the data is not relational and there's very limited amount of it. What approach should I take? -
how to find intersection of django models?
I have three models universities,user type and user.University model contain list of all university and user type contain two type of user type faculty and student and user model contains all the users. Now, what I want to achieve is get all the users which belongs the university intersections of user type. Suppose I selected abc university and user type faculty then how can i get all the user from that abc university with faculty type. May my models help you to understand better:- university model:- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # WE ARE AT MODELS/UNIVERSITIES class Universities(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") name = models.CharField(db_column="name", max_length=255, help_text="") abbreviation = models.CharField(db_column="abbreviation", max_length=255, help_text="") address = models.CharField(db_column="address", max_length=255, help_text="") status = models.BooleanField(db_column="status", default=False, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="") updatedBy = models.ForeignKey(User,db_column="updatedBy",help_text="Logged in user updated by ......") class Meta: managed = False get_latest_by = 'createdAt' db_table = 'universities' my user type model:- from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models # WE ARE AT MODELS/MASTER USERS TYPES class MasterUserTypes(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") userType = models.CharField(db_column='userType', max_length=255, help_text="") description = models.CharField(db_column='desciption', max_length=255, help_text="") status … -
Error in included django template is not rendered
I have this simple template that uses the imgix plugin like so: // template_b.html {% get_imgix project.picture %} This line causes an error and should be replaced by {% get_imgix project.picture.url %} This piece of code is inside a template that is included: // template_a.html {% include "template_b.html" %} It seems that when the template tags fails, in the first case (an AttributeError is raised), the template is simply ignored. No error is raised if the DEBUG setting is False. While this is certainly useful to prevent any user-facing errors, it's still concerning to not have any kind of feedback. Do you know where I can find more information related to this behavior and if there are ways to still be informed of the failure? -
invalid literal for int() with base 10: '1,303'
I get get error invalid literal for int() with base 10: '1,303' and it shows the blow code at fault. The old data works fine, its just for new stuff i add to the database. Any ideas? def get(self, request, *args, **kwargs): cart = self.get_object() item_id = request.GET.get("item") delete_item = request.GET.get("delete", False) flash_message = "" item_added = False if item_id: item_instance = get_object_or_404(Variation, id=item_id) ... qty = request.GET.get("qty", 1) try: if int(qty) < 1: delete_item = True except: raise Http404 -
google maps to trace the location and calculate distance using python django
i want to include google map in my project to calculate the distance between the current location and destination. My project is python django based project to provide the distance mapping . -
Wagtail: Add support for other image file formats
I'm using Wagtail as a simple image library, and have the requirement to support TIFF and BMP. I dug around the source code of Wagtail, and it feels like it should be possible. I mainly looked at the AbstractImage and Filter class - but so far I have failed to get it working. Has anybody succeeded in adding support for another file format? And if not, how would I go about converting images when they're uploaded? -
How to display calculated data in template
I need to get values from model fields, multiply and display the product in template. For example, I have this code: models.py class Product(models.Model): field1 = models.IntegerField() field2 = models.IntegerField() def multiply(self): return self.field1 * self.field2 views.py def home(request): products = Product.objects.all() #something goes here? context = { 'products': products } return render(request, 'home.html', context) template {% for product in products %} {{ product.field1 }} {{ product.field2 }} here goes the value of field1/field2 {{ }} {% endfor %} How it's better to achieve this? -
Latency issue in Python plus Django application
I have developed an application in Python 2.7.13 with Django 1.9.7 MYSQL . The application works fine. We deployed the same application in another server of higher hardware configuration but with Python version 2.7.5 with Django 1.9.7 & same version of MySQL. But this new deployment sometimes has severe latency issues but runs fine most of the time. I have compared the services running on the new server are same at the time of latency with when it runs fine. Log file does not show any unusual thing. Can someone provide some clue what we should look for? -
Ajax GET/POST Django, not really sure what to do with data
Im trying to perform a query on a page with AJAX. Backend is using Django. My javascript is like so: $(function(){ $("#form").submit(function(event){ event.preventDefault(); var query = ($("#input-field").val()); $.ajax({ type: "GET", url:"{% url 'search_building' %}", data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', 'q': query }, success: function(data) { $("#search-results").html(data); } }); }); }); The whole page is coming through and appending #search-results, where as I just want the results to come through from a table. Im also a little confused about whether I should use a GET or POST with Ajax, and whether I should be using csrf token. Much appreciated. -
How to use text type as primary key in Django
I'm learning Django but the ORM doesn't give a way to have a text primary key.I would like to have a primary such as 00RTTIN223.Is there any other way to bypass that limite? -
Filtering based on field in through model in with Treebeard
Asking this question on a high level makes it even more complex than I already believe it to be, so lets give the situation I specifically have. I have an application where I have groups with subgroups for the users, each group has members and staff users. When a user is a member of a group it is also member of all subgroups. Same goes for staff users, if you are staff in a group, you are also staff in all subgroups. I have basically the following models: class User(AbstractUser): pass class Group(MP_Node): # Some fields users = models.ManyToManyField(User, through='GroupMembership', related_name='groups') class GroupMembership(models.Model): group = models.ForeignKey(Group, related_name='group_memberships') user = models.ForeignKey(User, related_name='group_memberships') is_staff = models.BooleanField(default=False) Now on the "Add User to a Group" page I want a QuerySet of all Users that can be added to this group. This should exclude the users that already have a GroupMembership for this Group (I know this kan be done with Users.objects.exclude(group_membership__group=group)), but I also want to exclude Users that are already staff members on a higher group. Currently getting all groups for which a user is staff (including descendants) I do something like: paths = self.groups.filter( group_memberships__user=user, group_memberships__is_staff=True ).values_list('path', flat=True) query = reduce(operator.or_, … -
How to download an image from Django
I build a django application that generates an image and places it in a folder on the server. I want to download that image, located on the server at example.com/generatedimages. How do I send this image to the client? What does it have to do with static files? Do I need to generate a URL for that image temporarily? I do not use Django templating. Technical information: Django 1.10 Django Rest Framework ReactJs in the font-end jQuery for API calls image types: .png and .svg Thanks in advance. -
NoReverseMatch Defining keyword arguments in reverse not working
I have two Django views, one that loads a formset and one that submits it. This is to avoid form resubmission or having to change to a different view after POST. And after submit I redirect back to the view that loads the formsets. But I can't get the URLs/reverse to work. Here are my views and URLs def view(request, model1_id): #load formsets #pass information to submit view request.session['model1_session'] = int(model1_id) return render(request, 'app/view.html') def view_submit(request): #get the session model1_object = request.session.get('model1_session') ... if request.method == 'POST': #save formset #error!!!! return HttpResponseRedirect(reverse("app:view", kwargs={"model1_id": "model1_object"})) url(r'^(?P<model1_id>[0-9]+)/model1/something/$', views.view, name='view' ), url(r'^model1/something/submit/$', views.view_submit, name='view_submit' ), But when I press submit, everything saves just fine, but the reverse doesn't work.... Internal Server Error: /app/model1/something/submit/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/username/Documents/Database/project/app/views.py", line 412, in view_submit return HttpResponseRedirect(reverse("app:view", kwargs={"model1_id": "model1_object"})) File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 600, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/Library/Python/2.7/site-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) NoReverseMatch: Reverse for 'view' with arguments '()' and keyword arguments '{'model1_id': 'model1_object'}' not found. 1 pattern(s) tried: [u'app/(?P<model1_id>[0-9]+)/model1/something/$'] I don't understand why … -
Changing the app's label in the admin interface: ModuleNotFoundError
From the docs here here's what I've done: My whole project is called 'qualee'. I have one application called 'app'. In the file qualee/app/__init__.py I've put this: default_app_config = 'qualee.apps.QualeeConfig' In the file qualee/apps.py I've put this: from django.apps import AppConfig class QualeeConfig(AppConfig): name = 'app' verbose_name = "Rock ’n’ roll" In the file qualee/qualee/settings.py I have my apps declared like this: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.forms', 'app', 'compressor', 'django_markdown', ) And when I try to start the web server I get this error: ModuleNotFoundError: No module named 'qualee.apps' What am I missing? -
Django: m2m on a subclassed object
I am using cartridge and mezzanine in my project for products and categories and I am trying to add a ManyToManyField to my custom model. from cartridge.shop.models import Product, Category class BaseProduct(Product): (...) related_categories = models.ManyToManyField(Category, blank=True, through='CategoryLink') class CategoryLink(models.Model): category = models.ForeignKey(Category) product = models.ForeignKey(BaseProduct) For completeness their models are: Category: https://github.com/stephenmcd/cartridge/blob/master/cartridge/shop/models.py#L341 Product: https://github.com/stephenmcd/cartridge/blob/master/cartridge/shop/models.py#L105 However this gives me the following error when I try to perform a migration: Operations to perform: Apply all migrations: admin, auth, blog, brochures, case_studies, conf, contenttypes, core, django_comments, forms, galleries, generic, mezzanine_blocks, pages, quotes, redirects, services, sessions, shop, sites, stevensons_shop, stevensons_user, twitter, utilities Running migrations: Applying stevensons_shop.0057_baseproduct_related_categories...Traceback (most recent call last): File "/home/vagrant/virtualenvs/mezzanine/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: there is no unique constraint matching given keys for referenced table "stevensons_shop_baseproduct" What am I doing wrong? Is it even possible to add a m2m on an subclassed object? Do I need to make modifications to Category model? -
ID Attribute Error Django Admin in Change Form
I want to pass Nation model id to Django admin change_form so I can show a button or two when editing. I tried passing the id to the render_change_form function and finish up in the template, but I'm getting the below error. 'NationAdmin' object has no attribute 'nation_id' N:B This works fine when editing but it will throw this error when I want to add a new model object via Django Admin dashboard. Methods under NationAdmin #this method is to get the id def change_view(self, request, nation_id=None, form_url='', extra_context=None): self.nation_id = nation_id return self.changeform_view(request, nation_id, form_url, extra_context) #for form def render_change_form(self, request, context, *args, **kwargs): if self.nation_id: #django is telling me this line is causing error nation= self.get_object(request, self.nation_id) context.update({'nation':nation}) return super(NationAdmin, self).render_change_form(request, context, *args, **kwargs) Change_form.html {% if not nation.is_moderated and not nation.is_rejected %} <a href="{% url 'activate_moderation' nation.id %}"> <input type="button" value="{% trans 'Approve' %}" name="_approvebutton" /></a> {% endif %} -
How to format datetime to string just as django does it
I have a DatetimeField that I highlight in django admin based on how old it is compared to now(). def valid_up_to_column(self): now = datetime.datetime.now(datetime.timezone.utc) delta = (now - self.valid_up_to).seconds if delta > 900: colour = '#FF0000' # red else: return self.valid_up_to return format_html('<span style="background-color: {}">{}</span>', colour, self.valid_up_to) When format_html is used the datetime is rendered as raw 2017-01-01 00:00+00:00 UTC format, but for the other case, Django's regional settings take over and format it based on locale e.g. Jan 1 2017, midnight. How can I format the datetime to be in the same format as Django before passing it into format_html() ? I've tried using strftime(settings.DATETIME_FORMAT) but this is the django DATETIME_FORMAT, not the same as Python's string formatting. -
I want to run a server with existing django project on ubuntu 14.04
I am beginner with Python and Django. I have got a Django project from someone and I want to run a server with it on my computer. I can run a server creating new Django project through the python&django installing manual, but I can't with the existing project. What shall I do to run it? If you have any ideas, please let me know. Sincerely. -
Please help me about python&django error on Ubuntu 14.04
I am fairly new to Django. I am going to run a server with existing django project on virtual env, but I am facing an error - "ImportError: No module named celery". So I entered a command - "sudo pip install celery" and the result was "Successfully installed celery billiard pytz kombu amqp vine". So I re-enter the command "python manage.py runserver 0.0.0.0:8000", but the result is the same. Why is that? What shall I do in order to run server with my existing django project? My manage.py file is like: !/usr/bin/env python import os import sys if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vex.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) My django-admin version is 1.11. Please help me urgently and I will thank you enough. Best regards. -
Google authentication with django
Im using Django-registration redux to currently allow registration and login , however I want to implement third party login such as google login. Whats the best way to approach this , preferable a technique which i can use alongside django-registration redux. Thanks! -
Generating 4 web optimized images + keep the original image
Django==1.11 django-imagekit==4.0 I'd like to create images for Bootstrap's .col-xs- .col-sm- .col-md- .col-lg-. And also keep the original image uploaded by the user. In other words: user has one field for choosing an image file. And that original image is saved. And 4 more files are generated. ImageSpecField can do that. But what I don't like in ImageSpecField: It puts the produced image to another directory (under CACHE directory). It is lazy. That is extra images will not be generated at the time of image uplolading. They will be generated at the first usage. What I'd like to do: just create images and let their paths are stored in the database. It will not overburden the application. Now I have this: class Image(GeneralModel): pic = models.ImageField(verbose_name=_("Image"), upload_to=get_upload_path_original) pic_xs = ProcessedImageField(upload_to=get_upload_path_xs, processors=[ResizeToFit(width=500)], format='JPEG', options={'quality': 60}) ... But this is garbage as such model generates a ModelForm offering to choose a file for every image size (pic_xs, pic_md etc.). Could you help me understand: whether it is possible to do what I'd like to do? Or is it absolute nonsense and I should keep to ImageSpecField as it is with the lazy processes in CACHE directory? -
Django with jquery-fileupload ui throws error with "This field is required."
I have a Django project features uploading file for analysis. I reference and transplant the UI part from sigurdga/django-jquery-file-upload, specifically, the upload form and buttons, including the static css, js files and some of python scripts. Everything was set, but it just keep telling me "This field is required." after "Start" button was clicked. views.py import json from django.views.generic import CreateView, DeleteView, ListView from django.views import View from django.shortcuts import render from django.http import HttpResponse from .models import File from .response import JSONResponse, response_mimetype from .serialize import serialize class FileCreateView(CreateView): model = File fields = "__all__" def form_valid(self, form): self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') models.py from django.db import models class File(models.Model): file = models.FileField(upload_to="files") slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('profiler-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(File, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(File, self).delete(*args, **kwargs) urls.py from django.conf.urls import url from .views import Example, FileCreateView, FileDeleteView, FileListView urlpatterns = [ url(r'^new/$', FileCreateView.as_view(), name='profile-new'), ... file_form.html ... <div class="container" … -
PyMongo and Django
I'm new to Django and I'm making a Django app where I'm supposed to use MySQL and MongoDB through py-mongo. (I'm trying to use only py-mongo, not with mongoengine) I created an app 'test-app' with a model 'Books' and a CRUD views which seem to work fine (all books are saved and retrieved). However, for some reason I can't seem to find the Books back neither in the MySQL db nor the MongoDB. I'm not sure which database the model is using. There are also settings for Redis, but even after restarting the server the model entries are there, so I guess it is not in the cache. my settings are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.10.0.1', 'NAME': 'test_db', 'USER': 'test_user', 'PASSWORD': 'test_pass', } } CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '127.10.0.1:6379', 'OPTIONS': { 'DB': 0, }, }, } MONGODB = { 'default': { 'HOST': '127.10.0.1', 'PORT': '27017', 'NAME': 'django', } } And my requirements.txt: Django>=1.8,<1.9 docker-compose>1.11 django-redis-cache>1.7 pymongo>=3.4 MySQL-python>=1.2 -
Producing broken image in template, using python 2.7, django 1.10 and pillow 3.0.0
I basically want to produce 3 kinds of thumbnails in different sizes at the time of uploading the Image. and then reference them in the templates models.py def thumbnail_location(instance, filename): return "%s/%s" %(instance.productimage.product.slug, filename) THUMB_CHOICES = ( ("hd", "HD"), ("sd", "SD"), ("micro", "Micro"), ) class Thumbnail(models.Model): productimage = models.ForeignKey(ProductImages) type = models.CharField(max_length=20, choices=THUMB_CHOICES, default='hd') height = models.CharField(max_length=20, null=True, blank=True) width = models.CharField(max_length=20, null=True, blank=True) media = models.ImageField( width_field = "width", height_field = "height", blank=True, null=True, upload_to=thumbnail_location) def __unicode__(self): # __str__(self): return str(self.media.path) import os import shutil from PIL import Image import random from django.core.files import File def create_new_thumb(media_path, instance, owner_slug, max_length, max_width): filename = os.path.basename(media_path) thumb = Image.open(media_path) size = (max_length, max_width) thumb.thumbnail(size, Image.ANTIALIAS) temp_loc = "%s/%s/tmp" %(settings.MEDIA_ROOT, owner_slug) if not os.path.exists(temp_loc): os.makedirs(temp_loc) temp_file_path = os.path.join(temp_loc, filename) if os.path.exists(temp_file_path): temp_path = os.path.join(temp_loc, "%s" %(random.random())) os.makedirs(temp_path) temp_file_path = os.path.join(temp_path, filename) temp_image = open(temp_file_path, "w") thumb.save(temp_image) thumb_data = open(temp_file_path, "r") thumb_file = File(thumb_data) instance.media.save(filename, thumb_file) shutil.rmtree(temp_loc, ignore_errors=True) return True def product_post_save_receiver(sender, instance, created, *args, **kwargs): if instance.media: hd, hd_created = Thumbnail.objects.get_or_create(productimage=instance, type='hd') sd, sd_created = Thumbnail.objects.get_or_create(productimage=instance, type='sd') micro, micro_created = Thumbnail.objects.get_or_create(productimage=instance, type='micro') hd_max = (500, 500) sd_max = (350, 350) micro_max = (150, 150) media_path = instance.media.path owner_slug = instance.product.slug if hd_created: …