Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django haystack partial search for IntegerField
I am using Django-haystack 2.4.1. I am trying to do a partial search for IntegerField. I have a item_id filed in my searchindex. For example I want to search 23456, 2345, 234, 23, 2 all of these. This is not working with the query SearchQuerySet().filter(item_id__icontains=234).models(MyModel) Can anyone help me with this please. -
AWR ALB health check fails when redirecting http request to https on django nginx server
First, I use the server environment django + nginx + uwsgi AWS ECS + ALB loadbalencer AWS ACM ssl credentials I want nginx to redirect http requests to https requests Before that, I tested whether I could receive http and https requests. Both http and https will normally receive the request. etc/nginx/nginx.conf user root; worker_processes 5; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; daemon off; events { worker_connections 768; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_names_hash_bucket_size 512; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } /etc/nginx/sites-enabled/app.conf server { listen 80; listen 443 ssl; server_name ~^(.+)$; charset utf-8; client_max_body_size 128M; location / { uwsgi_pass unix:///tmp/app.sock; include uwsgi_params; } } To return an http request as an https request I modified the app.conf file. But I can not pass the ALB health check. As a result, the server returns a 502 error. /etc/nginx/sites-enabled/app.conf server { listen 443 ssl; server_name ~^(.+)$; return 301 … -
django allauth custom messages: Styling messages with html/css
Allauth's the messages are stored as text files in the templates directory by default and these look something like: {% load i18n %} {% blocktrans %}You cannot remove your primary e-mail address ({{email}}).{% endblocktrans %} These use django's template tags but aren't 'HTML friendly'. I would like to style these and have something like: {% load i18n %} <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> {% blocktrans %}You cannot remove your primary e-mail address ({{email}}).{% endblocktrans %} </div> But the code above simply renders the HTML as text. I cannot put this HTML in a template and just do {{ message }} within the template because I would like to change some of it on a per message bias (at least the color!). How could I accomplish this? Thank you! -
Validate model instance from python using Django admin validators
I'm working on the importing script that saves data from CSV to Django database. Saving process looks like this: instance = ModelName(**kwargs) instance.save() # No errors reported But when I try to edit and save some items using admin panel it shows me a message that some of the field values (like URL fields and custom validators) is not valid. Question: Is there any way to validate model instance from the python code using Django admin validators? -
Django import error -- No module named core.management
I am trying to run python manage.py on a Django app and I am getting this error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management Brocks-Mac-mini:firstdjango BrockMorrison$ I have Django installed on my system. Using pip freeze | grep -i django I get the following: Django==1.11.1 When I search for the path that Django is installed it gives me: /usr/local/lib/python2.7/site-packages I have tried updating to the latest version of Django and when I try running pip install django in the folder it tells me that the requirement is already satisfied. I have tried looking on other stack overflow posts, but none of the other solutions have helped me. Any help would be appreciated. -
Django: made error in models.py and migrated, tried to fix the error but django doesnt see any change in models.py
So I made the following silly error in models.py: caption_on = models.BooleanField(default='true') which gave me the following error when i ran 'makemigrations' and 'migrate' django.core.exceptions.ValidationError: ["'true' value must be either True or False."] So I fixed my mistake by changing my models.py line to caption_on = models.BooleanField(default=True) but this gave me again the same django.core.exceptions.ValidationError. It's like my models.py doesn't get updated. Even when I delete the line in models.py the error appears. Anyone any idea on how to fix this? -
How translate humanize django
I need translate humanize to portuguese (pt-BR). How? Import: from django.contrib.humanize.templatetags.humanize import naturaltime Using: _question['pub_date'] = naturaltime(question.pub_date) Settings: LANGUAGE_CODE = 'pt-BR' TIME_ZONE = 'America/Sao_Paulo' USE_I18N = True USE_L10N = True USE_TZ = True And in my template show this: 2 hours ago -
RewriteRule django, displaying h1 text in url
Here is my article urls.py app_name = 'articles' urlpatterns = [ url(r'^(?P<article_id>[0-9]+)/$', views.detail, name='detail'), ] And my article models.py class Article(models.Model): heading_text = models.CharField(max_length=150) I can access the article by this link: www.example.com/articles/7/ but I would like the user to see the heading text of the article in his url, for example: www.example.com/articles/how-to-do-this or to still have the heading text and the article id in the url if it's necessary: www.example.com/articles/7/how-to-do-this . How can I achieve this? -
Pip install cryptography on EC2 fails with no error
I seem to have run into an error after trying to install additional requirements from my requirements.txt file. The server is a AMI image, running apache/mod_wsgi, and python 2.7. The offending pip package is cryptogrpahy. I'm able to install the package using pip: (venv)[root@serv main-site]# pip install cryptography==1.8.2 Collecting cryptography==1.8.2 Using cached cryptography-1.8.2.tar.gz Requirement already satisfied: idna>=2.1 in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Requirement already satisfied: asn1crypto>=0.21.0 in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Requirement already satisfied: packaging in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Requirement already satisfied: six>=1.4.1 in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Requirement already satisfied: setuptools>=11.3 in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Requirement already satisfied: enum34 in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Requirement already satisfied: ipaddress in ./venv/lib/python2.7/dist-packages (from cryptography==1.8.2) Collecting cffi>=1.4.1 (from cryptography==1.8.2) Using cached cffi-1.10.0-cp27-cp27mu-manylinux1_x86_64.whl Requirement already satisfied: pyparsing in ./venv/lib/python2.7/dist-packages (from packaging->cryptography==1.8.2) Requirement already satisfied: pycparser in ./venv/lib/python2.7/dist-packages (from cffi>=1.4.1->cryptography==1.8.2) Installing collected packages: cffi, cryptography Running setup.py install for cryptography ... done Successfully installed cffi-1.10.0 cryptography-1.8.2 (venv)[root@serv main-site]# However, after installing, it doesn't appear in pip freeze: (venv)[root@serv main-site]# pip freeze | grep cryp asn1crypto==0.22.0 (venv)[root@serv main-site]# Also, if I try to downgrade the package, pip gives me this strange output: (venv)[root@serv main-site]# pip install cryptography==1.4 Collecting cryptography==1.4 Using cached cryptography-1.4.tar.gz Requirement already satisfied: idna>=2.0 in ./venv/lib/python2.7/dist-packages (from … -
What's better performance-wise, Django TemplateView or explicit url/view statements?
For the less interesting pages on my Django site I've set up simple urlpatterns like: url(r'^somepage/', views.somepage), url(r'^anotherpage/', views.anotherpage), and corresponding function views of: def somepage(request): return render(request, 'page1.html') def anotherpage(request): return render(request, 'page2.html') I'm wondering if importing a generic class-based view into urls.py is preferable, or if there's some hidden cost to climbing through inheritance, etc. that I'm missing: from django.views.generic import TemplateView urlpatterns = [ ... url(r'^somepage/', TemplateView.as_view(template_name='page1.html')), url(r'^anotherpage/', TemplateView.as_view(template_name='page2.html')), ... ] -
'ListSerializer' object is not callable Request Method
Unfortunately I'm facing the same problem as mentioned in this post. But it didn't solve the problem in my case. My model: class AppointmentCategory(models.Model): name = models.CharField(max_length=100, default='General') My Serializer: class AppointmentCategorySerializer(serializers.ModelSerializer): class Meta: model = AppointmentCategory fields = ('id', 'name',) My View: class AppointmentCategoryViewSet(viewsets.ModelViewSet): queryset = AppointmentCategory.objects.all() serializer_class = AppointmentCategorySerializer(many=True) I'm passing the post data in this format: [ { "name": "Emergency" }, { "name": "General" } ] It does work when I send only one element. However the above mentioned list fails to create two objects in the database. The error says: 'ListSerializer' object is not callable I'm not sure how to solve this. Any ideas? -
JavaScript/Jquery doesn't recognise newly added elements [duplicate]
This question already has an answer here: Event binding on dynamically created elements? 18 answers I am using jquery to build a website. I have this html code: <div class="parent">{{ username }} <a class="edit-username"><span class="glyphicon glyphicon-save"></span></a></div> On click of ".edit-username", .parent div shuld change: $(".edit-username").on("click", function(){ $(".parent").html("<div class='col-xs-2 edit-username-wrap'> <input class='edit-username-input form-control'value='{{ username }}'></input> </div><a class='btn save-username'><span class='glyphicon glyphicon-ok'></span> Save</a>") }) This works just fine, but when i make: $(".save-username").on("click", function(){ alert("works"); }) It just doesnt work. Why is that? -
Django: Update Page Information Without Refreshing
i've been trying to make this portion of my website update whenever a button is pressed.: In my template, I access this information through {{ request.user.profile.coins }}. I was looking into the process and I attempted to use an AJAX function to call this view: The AJAX function is as follows: How can I get this to work? -
HTTPS Doesn't work directly, only loading http and redirecting does?
I'm using Django, Godaddy for domain, and Heroku for hosting with SSL set up. I'm using forwarding from Go Daddy, settings as to forward to https, permanent forward, forward only (No Masking). When I load example.com, the page loads and redirects to https://example.com and is correct/secured. When I load https://example.com I get 'This site can’t be reached' after a long timeout. Is this a DNS issue or possibly Django/Heroku related? -
compare strings/unicodes django template
{% ifequal commment.user.username user.username %} Delete{% endifequal %} why are they not getting compared though on checking they print same values.I have checked there type in django shell these both values are unicode. -
linking to a js file from django
I am trying use the <script src=""> tag to link to EasyAutocomplete. I am using django, and can't seem to figure out how to load it. I downloaded it and tried to link to it using static, but no matter what I did, i got an error saying undefined. How do you link to a downloaded js file with django? -
Django makemigrations 1.8.18 ValueError: Lookup failed for model referenced by field
Recently upgraded Django to 1.8 from 1.7. Taken a dump of the PRD DB into DEV. Don't care about any of the migrations in the DB for dev, so: Delete migrations folders in my apps. Delete all rows from django_migrations table. OK, all good. Now, I just want to make a fake migration for the apps, and away we go. So I start with the top level app 'website'. Running this: python manage.py makemigrations website Gives the file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='HistoricalStock', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('period_date', models.DateField()), ('close', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('open', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('day_high', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('day_low', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('change', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('average_gain', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('average_loss', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('rsi', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('true_range', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('average_true_range', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('price_average_true_range', models.DecimalField(default=0.0, max_digits=20, decimal_places=10)), ('thirty_day_constant_maturity_vol_skew', models.DecimalField(default=0.0, null=True, max_digits=20, decimal_places=10, blank=True)), ], options={ 'ordering': ['period_date'], }, ), migrations.CreateModel( name='Industry', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('group', models.CharField(unique=True, max_length=40, verbose_name=b'name')), ('slug', models.SlugField(unique=True)), ], ), migrations.CreateModel( name='Sector', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('group', models.CharField(unique=True, max_length=40, verbose_name=b'name')), ('slug', models.SlugField(unique=True)), ], … -
Django Cannot assign "x'": "y" must be a "z.`
I am receiving the following error: Internal Server Error: /change_chosenCharity/ ValueError at /change_chosenCharity/ Cannot assign "19L": "Profile.chosenCharity" must be a "Charity" instance. From the following view: @login_required def change_chosenCharity(request): if request.method == 'POST': form = updateCharity(request.POST) if form.is_valid(): currentUser = request.user currentUserID = currentUser.id chosenCharityQuery = Charity.objects.filter(id=request.POST['currentCharities']) charity_id = chosenCharityQuery[0].id created = Profile.objects.update_or_create( user_id=currentUserID, defaults={'chosenCharity': charity_id}, ) messages.success(request, 'Your chosen charity has been updated.') return redirect(reverse('profile')) else: form = updateCharity() return render(request, 'meta/changechosencharity.html', {'form': form}) The post result from Django shows: POST: currentCharities = u'19' 19 is definitely an instance of the charity. I have had this issue before and always solved it relatively quickly. I have searched on here but can't find a solution for my issue. Any help would be appreciated. Additional Info: HTML FORM: <form class="form-horizontal" role="form" method="post" action=""> {% csrf_token %} <fieldset> <div class="form-group"> <label class="col-sm-4 control-label">{{ form.currentCharities.label }}:</label> <div class="col-sm-8"> {{ form.currentCharities }} <div class="text-danger"> {% for error in form.currentCharities.errors %}{{ error }}<br/>{% endfor %} </div> </div> </div> <div class="form-group"> <div class="text-right col-sm-12"> <button type="submit" class="btn btn-primary">Change Charity</button> </div> </div> </fieldset> </form> DJANGO MODEL: class Charity(models.Model): name = models.CharField(max_length=50, unique=True) website = models.URLField() enabled = models.BooleanField(default=True) def __unicode__(self): return self.name class Meta: ordering = ['name'] … -
Display number of views for each article on a table
I have a homepage for my blog where I list all the articles available in a table. There is several columns (informations) for each article (row of the table) like the date, the author and the number of views. But I encounter an issue to display the number of views of each article. First my models.py from django.db import models # Create your models here. class Categorie(models.Model): nom = models.CharField(max_length=30) def __str__(self): return self.nom class Article(models.Model): titre = models.CharField(max_length=100) auteur = models.CharField(max_length=42) contenu = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie') def __str__(self): return self.titre class Page(models.Model): url = models.URLField() nb_visites = models.IntegerField(default=1) def __str__(self): return self.url I made a middleware to increment the counter : from django.db.models import F from blog.models import Page def stats_middleware(get_response): def middleware(request): # Avant chaque exécution de la vue, on incrémente # le nombre de page vues à chaque appel de vues try: # Le compteur lié à la page est récupéré et incrémenté p = Page.objects.get(url=request.path) p.nb_visites = F('nb_visites') + 1 p.save() except Page.DoesNotExist: # Un nouveau compteur à 1 par défaut est créé p = Page.objects.create(url=request.path) # Appel de la vue Django response = get_response(request) # Et on … -
Download button for model data in django admin panel
I'm not sure, but this should be simple. Confusingly, googling for the ways doesn't seem to return clear and concise answers. I shouldn't need to change any forms. All I want is a custom action in the model page where all the data is listed. This button should allow me to download the table as a .csv file for example. How do I do that? -
In Django, what's the meaning of allow_blank and style = {'base_template' : 'textarea.html'} as CharField attribute?
I have just started leaning Django REST framework step by step in the Tutorial. In the Tutorial, I declare serializers that work very similar to Django's form in order to provide a way of serializing and deserializing the snippet instances into representation such as json. Here is snippets/models.py. from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) Here is snippets/serializers.py. from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance In Django document, I can't find allow_blank, style = {'base_template' : 'textarea.html'} as CharField … -
Django 1.10 Manually Commit to Database from CSV file record
I have a need to load to my model 11,000 sites with hourly temperature data for 7 days (so 7*24*11,000 data records) worth of data. I need to do this twice a day. Using autocommit is very slow. I would like to commit after loading data from each site. I have two model classes, Lake and Tempdat. The essence of the code is below. I appreciate any help you can provide. I have been looking at atomic in the Django docs and other examples on this site, but I need more straightforward instruction (thanks!) with open('iowa.csv', 'r+') as lakefile: lakes = csv.reader(lakefile) for lake in lakes: gnis = lake[0] temp_dat_filename = "T"+str(gnis)+".txt" nameanddir=os.path.join(tempdatdir,str(temp_dat_filename)) f = open(nameanddir, 'r+') c = Lake.objects.get(GNIS=gnis) #Lake is the Class name print(c) for line in f: list_of_line = line.rstrip().split() date_pieces = list_of_line[0].split('-') dateob = datetime.datetime(int(date_pieces[0]), int(date_pieces[1]), int(date_pieces[2]), int(list_of_line[1]), 0, 0) temperature = list_of_line[2] #NOTE: instead of commiting here for each record, I would to go through all the records (7days worth, then commit) c.tempdat_set.create(LakeTemp = temperature, ModelDate = dateob)` -
How to generate the __pycache__ paste in pycharm
I've downloaded an app from github but my Pycharm can't run it, I set up the project interpreter but it still doesn't work. I guess it's not running because there isn't the pycache paste , as in the other projects, how do I generate that paste from pycharm ? Any help is appreciated. -
Django FileSystemStorage.url is wrong
Code: company = Company.objects.get(pk=pk) if request.POST: company_name = request.POST['company_name'] company_logo = request.FILES['company_logo'] fs = FileSystemStorage(location='/home/ubuntu/mywebsite/media/company/' + str(company.pk) + '/') filename = fs.save(company_logo.name, company_logo) uploaded_file_url = fs.url(filename) fs.url returns: /media/thefilename.png which is wrong ... apparently the .url method doesn't take in to account what you've set your location attribute to? How do I ensure that the correct path is being returned? -
Django: How to use AJAX to update my database?
I would like to use AJAX to asynchronously update the coin balance displayed on a user's screen. I think I have the views.py working correctly because I get the correct JSON, I'm just not sure how to increase the coin balance using AJAX. So far: function update_coins(){ $.ajax({ method: "POST", url: "/coins" }) };