Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with __range function in Django
What I need to do is filter all the sales objects from a particular zone and region and within a date range. So, I used the __range function in the query something like this start = start_date.strftime('%d-%b-%y') end = end_date.strftime('%d-%b-%y') Sales.objects.filter(zone_code=zone_code_, region_code=region_code_, sales_date__range(start,end)) All my dates are stored as characters in my models, so I changed the input dates to that format using strftime(). But this query is giving me objects beyond the specified range, and sometimes a null set. -
django deployed app refused to connect
i am working on a url shortening service. Deployed app on heroku servers successfully https://kwargs.herokuapp.com this url is getting accessed over all browsers supported via mobile phones. but on desktop its not getting accessed each time it shows "this site can't be reached refused to connect". i am using django hosts. from django.conf import settings from django.http import HttpResponseRedirect DEFAULT_REDIRECT_URL = getattr(settings,"DEFAULT_REDIRECT_URL","https://kwargs.herokuapp.com") def wildcard_redirect(request,path=None): if path is not None: new_url = DEFAULT_REDIRECT_URL + "/" + path return HttpResponseRedirect(new_url) #sttings.py ROOT_URLCONF = 'kwargs.urls' ROOT_HOSTCONF= 'kwargs.hosts' DEFAULT_HOST = 'kwargs' DEFAULT_REDIRECT_URL="https://kwargs.herokuapp.com" PARENT_HOST = "herokuapp.com" ALLOWED_HOSTS = ['kwargs.herokuapp.com'] #models.py def get_short_url(self): url_path = reverse("scode",kwargs={'slug':self.shortcode}, host='kwargs',scheme='https') return url_path #host.py file host_patterns = patterns('', host(r'kwargs',settings.ROOT_URLCONF,name='kwargs'), host(r'(?!www)','kwargs.hostconf.urls',name='wildcard'), ) this is everything that's related to url_config in my code i tried every tweak but still nothing worked. Is there any way to access it on desktop also. i also tried all sorts of things like adding browser to firewall... any help would be appreciable thanks. -
Writing subquery expression in django ORM to use alias
I want to write something similar using Django ORM. SELECT Count(*) AS total_count, (SELECT Count(*) FROM core_subscriber WHERE ( core_subscriber.os = 'Mac OS X' AND website_id = 1 )) AS count1, (SELECT Count(*) FROM core_subscriber WHERE ( core_subscriber.os = 'iOS' AND website_id = 1 )) AS count2 FROM core_subscriber WHERE core_subscriber.website_id = 1; The query result should be something like below total_count | count1 | count2 -------------+--------+-------- 3 | 2 | 1 But I am having hard time writing this query using django ORM. I have tried the below things query_set1 = Subscriber.objects.filter(Q(os='Mac OS X')).filter(website_id=1) query_set2 = Subscriber.objects.filter(Q(os='iOS')).filter(website_id=1) Subscriber.objects.annotate(count1=Count(query_set1), count2=Count(query_set2)).values('count1', 'count2').filter(website_id=1).count() and Subscriber.objects.annotate(count1=Count(Subquery(query_set1)), count2=Count(Subquery(query_set2))).values('count1', 'count2').filter(website_id=1).count() Extra Information Why to use Django ORM? Why not use RawSQL? The subqueries that are creating count1 and count2 are being created at run time using Q objects. Example: count1 ~ Subscriber.objects.filter(Q(os='Mac OS X')).filter(website_id=1).count() count2 ~ Subscriber.objects.filter(Q(os='iOs')).filter(website_id=1).count() and I am creating Q objects in runtime after parsing some query from my client. So, I NEED to be able to generate the query using ORM for simplicity. -
how to track submission of forms?
I am relatively new to Django. I have multiple forms available in my application. I have created those forms and the forms are getting processed successfully. Now I want a functionality that when user logs in, he/she sees a table or list of forms that he/she submitted. Like keeping a track of forms that user submitted. The data could look something like this: |------------|----------------|----------------|-----------|------------| | Project ID | Type | date submitted | Requester | Staus | |------------|----------------|----------------|-----------|------------| | 1 | Seminar speaker| 07/25/2018 | Amey . | In process | |------------|----------------|----------------|-----------|------------| Can someone please suggest me a starting point or a blog that I can refer to tackle this functionality? Or is there any library available in Django or compatible with Django that I can use to achieve my functionality? Any Advise or help is appreciated? As of now I am not pasting any code, but in case you need any I would be more than happy to share that piece of code. -
'module' object has no attribute 'lru_cache'
I'm getting this error in my logs with django app. I thought such errors occur when using Python 2.x, but in my virtual env Python - 3.6.5. Django - 2.0.7. VESTA Control Panel with wsgi. I will be grateful for the help. -
Migration from Angular1 to Angular5 (parallel run)
My current AngularJS application is being served by django. Now our team in a position to migrate Angular1 to Angular5. It should run parallelly. Our application is very big and legacy. I checked angular doc, which has ngupgrade which will help us to migrate things. I am here just looking for a repo or example to run both Angular1 and Angular5. -
RGBA Error with Django while uploading a photo
now, I have a simple model defined with a photoupload feature using django thumbnails plugin. but when i try to upload it gives me the following error: OSError at /admin/photo/album/add/ cannot write mode RGBA as JPEG Traceback /home/DH.Park/Django/vDjBook/lib/python3.5/site-packages/PIL/JpegImagePlugin.py in _save rawmode = RAWMODE[im.mode] SO, should i fix code into python3.5/site-packages/PIL/JpegImagePlugin.py? -
Usage of Tarantool and MySQL with Django
How can I use Tarantool in conjunction with Django and MySQL for caching (instead of i.e. Redis) and/or in the sense that all read transaction go to Tarantool (after insured MySQL replication) and all writes go into MySQL (preferred option) Would anyone have a sample? -
Django. Can i use RawQuerySet into Prefetch?
I want to pass RawQuerySet into Prefetch as 2nd argument. prefetch_qs = Image.objects.raw(raw_sql) prefetch = Prefetch( 'images', prefetch_qs, to_attr='images' ) But i get error AttributeError: 'RawQuerySet' object has no attribute '_iterable_class' I can make dirty hack from django.db.models.query import ModelIterable prefetch_qs._iterable_class = ModelIterable But i'm afraid some undefined behaviour. Maybe there is some workaround or another right way? -
Can I use Django's gettext_lazy in DictField?
I've got an error using gettext_lazy in such a way. It works fine without gettext_lazy checkboxes = DictField(default = {'key1': [True, gettext_lazy('blablabla')], 'key2': [True, gettext_lazy('blablabla')], 'key3': [True, gettext_lazy('blablabla')], 'key4': [True, gettext_lazy('blablabla')]}) -
How to check if instance of an object of a model is in another model?
I have two models File and ReviewList. File contains the excel files and ReviewList contains the files to be reviewed. Adding file to review list is simple. But where I'm stuck is how to check if a file is in the review list in django language template. Look below for what I tried. Models.py class File(models.Model): ..... class ReviewList(models.Model): aFile = models.ForeignKey(File) Views.py def fullList(request): allFiles = File.objects.all() allReviews = ReviewList.objects.all() context = {'allFiles': allFiles, 'allReviews': allReviews' return render ...... The real issue. The template {% for f in allFiles %} <li>{{ f.name }}</li> {% if f in allReviews %} <i>Already in the review List</i> {% else %} <a href="#">Add to review list</a> {% endif %} {% endfor %} I tried: {% if f in allReviews %} But it doesnot work. Am I doing something wrong here? -
Django: Queryset distinct clause performance issue
I'm trying to remove duplicates from a database query. Here are my models: class Restaurant(models.Model): name = models.CharField(db_index=True) class InformationSheet(models.Model): owner = models.ForeignKey(Restaurant, related_name='sheet') latitude = models.DecimalField(max_digits=10, decimal_places=6) longitude = models.DecimalField(max_digits=10, decimal_places=6) class Meta: indexes = [ models.Index(fields=['latitude', 'longitude', 'owner']), ] class Availability(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, db_index=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) class Meta: indexes = [ models.Index(fields=['restaurant', 'supplier']), ] I need to select InformationSheet between gps coordinates when restaurants availability is defined for given suppliers. suppliers = [1, 2, 3] sheets = InformationSheet.objects.filter( latitude__gte=lat_start, latitude__lte=lat_end, longitude__gte=long_min', longitude__lte=long_max, owner__availability__supplier_id__in=suppliers ).distinct() The table has several hundred thousand entries.The SQL query generated was initially fast but adding the "distinct" clause to remove duplicates made the query too slow for my needs. Because the distinct prevents the use of indexes How can I proceed? -
login() missing 1 required positional argument: 'user'
def login_view(request) : if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=email, password=password) if user is not None: form = LoginForm() login(request, user = user) I get an error : login() missing 1 required positional argument: 'user' I even tried login (request, user = user) and I am using a custom user model -
Javascript copy to clipboard doesn't preserve newlines
I need to create a button which copies it's data-cp attribute into the clipboard. Everything works correctly except newlines. It looks like something replaces newlines to ''. This is how it looks in inspector: And this is how I create the text: string = '' for row in lists_of_strings: string += '\t'.join(row) + '\n' Then I send it through the context to the template and: <input type="button" class="copy_to_cb_input" data-cp="{{ string|safe }}" value="Copy"> JS $('.copy_to_cb_input').click(function () { var $temp = $("<input>"); $("body").append($temp); $temp.val($(this).attr("data-cp")).select(); document.execCommand("copy"); $temp.remove(); }) Copying to clipboard works but I get something like string.replace('\n','') I need to copy and paste this into the excel sheet and txt. Do you know where is the problem? -
Django Wagtail Custom web pages in Admin
I'm sure i can create a frontend website to do what I'm trying to achieve on top of wagtail. However because this is purely a backend system for a client I would prefer if they could have this functionality fit in natively on wagtails CMS. I have a couple of related snippets. Driver,Trip,Stops and items. Driver 1-Many Trips Trips 1-many Stops Stops 1-many items Now I can edit these just fine but, I would like to say display all the trips a driver makes. As well as select a trip and see all the stops they made, etc The gist is that it is related data that I would like to view in a single page and navigate through various levels of data through links. As far as I have read wagtail backend was not designed to do this. However I am sure the must be away i can simply create a page that feels like the backend and is only visible from "the backend". I'm just not sure how to go about it. I would imagine I would create a custom view and model to populate it just as though it was frontend but have it fitted to be … -
bcrypt not working in Django
this is my settings.py: Django settings for kotha project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ 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/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6om5hw4^(asx(kk=t$*4asqxz5jf!4e-!lwdosd=%#!176_%l0' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["bc65ce1d.ngrok.io", '127.0.0.1' ] # Application definition PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "rest_framework", "kotha_app", "bcrypt", ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'kotha.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , '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', ], }, }, ] WSGI_APPLICATION = 'kotha.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'kotha', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'sql_mode': 'traditional', } } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', … -
Form field not getting stored in Django User model
I have a signup form which I have defined below forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django import forms class SignUpForm(UserCreationForm): display_name = forms.CharField(max_length=30, required=True, help_text='Please provide a display name for your profile') class Meta: model = User fields = ('username', 'password1', 'password2', 'display_name') In the views.py, I handle the signup process views.py from django.contrib.auth.models import User from django.contrib.auth import login, authenticate from .forms import SignUpForm from django.shortcuts import render, redirect @csrf_exempt def signup_users(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data.get('username') display_name = form.cleaned_data.get('display_name') raw_password = form.cleaned_data.get('password1') user.set_password(raw_password) user.display_name = display_name user.save() user = authenticate(username=username, password=raw_password) print("signup authencticate", user) login(request, user) return render(request, 'index.html') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) The user is able to signup successfully however their display_name doesn't get stored in the django User model.Even in the django admin, I do not see the field display_name.I have even performed a query like serializers.serialize("json",User.objects.filter(username=username)) but even here it shows every other field except the display_name. What am I doing wrong? -
Breaking the content of a page after certain height in creaating pdf from html
I am using wkhtmltopdf to pdf from the html template created using Python and Django.The data which i want to display is like every page is for 1 client and the page consists of a table . In some cases the table data is large , and I have fixed the height of each page as 700px. Issue is when the table is large for some specific clients then the table crosses over to the next page and overlaps with the table data of other client. i want to achieve something like if the table data is large for a client then the next page should have the data for the same client and then for other clients next page onwards. Is there any way to achieve this? -
How do I add an incremental ID to my td?
My html file generates a table: {% for resp in results %} <tr style="counter-increment: count"> <td>{{ resp }}</td> <td>{{ resp.Question_id.Statement }}</td> </tr> {% endfor %} How do I assign an id to the first td every time a new row is generated? -
django-cms_text_ckeditor error of static loading with Amazon S3 static storage
After deploying django + django-cms project on server using amazon S3 (STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' ), static files not loading for django-cms_text_ckeditor, bundle of ckeditor is trying to load static from local storage and it's doesn't working, obviously. All other static files is loading from s3 bucket without any problems. On localhost ckeditor bundle is requesting to local static, and it's work, other static files loading from s3 bucket. Maybe somebody have an idea how to make bundle load static with s3, or just take files from project server(like a localhost behavior)? This plugin used only in admin, so it's not critical to load server static with it. Doesn't working with ckeditor default settings, as with custom setting and loaded bundle from ckeditor official site. Google of it, obviously, wasn't successfull, although i spent a lot of time on it. Loading failed for the <script> with source “http://myproject.herokuapp.com/static/cms_modules/ckeditor/config.js?t=G87E”. config:1 Loading failed for the <script> with source “http://myproject.herokuapp.com/static/cms_modules/ckeditor/skins/moonocolor/skin.js?t=G87E”. config:1 Loading failed for the <script> with source “http://myproject.herokuapp.com/static/cms_modules/ckeditor/lang/en.js?t=G87E”. config:1 TypeError: c[a] is undefined -
Django: HttpResponse in RetrieveAPIView giving an AttributeError
Trying to Create API for likeing a post, this works for liking a post but i get error when adding the return HttpResponse/Response statements gives a Error AttributeError at /api/posts/like/4/ 'HttpResponse' object has no attribute 'model' Request Method: GET Request URL: http://127.0.0.1:8000/api/posts/like/4/ Django Version: 2.0.7 this is views.py class LikeDetailAPIView(RetrieveAPIView): serializer_class = PostSerializer def get_queryset(self): user = self.request.user post_id = self.kwargs['pk'] like = Like(post=Post.objects.get(id=post_id), user=user) user_like = Like.objects.filter(post=post_id, user=user) if user_like.exists(): user_like.delete() content = {'message': 'unliked'} return Response(content, status=status.HTTP_202_ACCEPTED) else: like.save() content = {'message': 'like'} return Response(content, status=status.HTTP_202_ACCEPTED) In urls.py url(r'^like/(?P<pk>.+)/$',LikeDetailAPIView.as_view(), name='likeapi'), What i am intending to do is return a success message. In serializer.py class LikeListSerializer(serializers.ModelSerializer): class Meta: model = Like fields = [ 'user', 'post', 'time', ] Any links that i can refer? -
How to call CreateApiView and ListApiView using same url conf in django-rest-framework?
I am trying to build a GET and POST method to get and save some objects. I have views.py like this class QuestionList(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer class QuestionSave(generics.CreateAPIView): queryset = Question.objects.all() serializer_class = QuestionSerializer Then I have url conf, urls.py like this urlpatterns = [ url(r'^questions/$',views.QuestionList.as_view()) ] In my understanding, we have to have a generic class with CreateApiView for POST methods and ListApiView for GET method and so I have created classes like that. My question is, how should I configure them so that on POST QuestionSave will be called and on GET QuestionList will be called? -
Retrieve articles with multiple specified tags(m2m to article)
I have an article model which share ManyToMany relationships with model Tag, I'd like to retrieve articles which have multiple tags for one tag: In [162]: articles = Article.objects.filter(tags__name="python") Out[162]: <QuerySet [<Tag: python>, <Tag: django> As for multiple tags I tried In [168]: articles = Article.objects.filter(tags__name="python", tags__name="django", tags__name="queryset") It reported error: SyntaxError: keyword argument repeated How could I get the articles which have the specified tags. -
Django: Unicode, MySQL and Encodings (latin1, koi8-r)
Django version 2.0. Python 3 My database charset and collation: mysql> SELECT @@character_set_database, @@collation_database; +--------------------------+----------------------+ | @@character_set_database | @@collation_database | +--------------------------+----------------------+ | latin1 | latin1_swedish_ci | +--------------------------+----------------------+ Old developer inserted data in KOI8-R encoding using Perl :( To get correct values from database I used ugly construction str(username).encode('latin1').decode('koi8-r'). And what? I need to use it in all my project to send data to output? Or write function to encode context dictionary, but i also need to encode/decode all data. Without this i get something like ëÏÚÌÑÎËÏ òÏÍÁÎ éÏÓÉÆÏ×ÉÞ How to globally set encoding in Django to prevent encode/decode operation in every place? I changed encoding different ways and nothing happens. In settings.py I tried to set DEFAULT_CHARSET into different encodings (if I set default_charset to KOI8-R i get an error: UnicodeEncodeError: 'charmap' codec can't encode characters in position 6228-6235: character maps to . Whith other encodings no errors but no result). I tried to set in Database section of settings.py different values to charset and collation. 'OPTIONS': { 'charset': 'latin1', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', character_set_connection=latin1, collation_connection=latin1_swedish_ci", } I added <meta http-equiv="Content-type" content="text/html; charset=koi8-r (or other)" /> to <head> tag in index.html template. No result. Why in Perl i can send header … -
Show image from path by python django
I have this code in my django project. it will uploads a file in a path outside django' root in server. now I want an function that can retrive that file and show the client. It's nondirect link and is like http://example.com/uploads/{ID}. now how it's possible. note that uploaded files are image. def upload(request): if request.method == 'POST' and request.FILES['file1']: myfile = request.FILES['file1'] fileType = request.GET.get('type',None) if fileType==None: return json_response(65,400) if myfile.size > 5*1024*1000: return json_response(85,400) elif not (myfile.content_type.startswith('image') or myfile.content_type == 'application/pdf'): return json_response(185,400) fs = FileSystemStorage('../uploads') filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) request.user.file_set.create(name = uploaded_file_url, type = fileType, createdAt = datetime.now())