Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove inline styles from django-tinymce html content
When I save content through django-tinymce it adds its own inline styles. However I'd like to remove this behaviour and just save the content in plain html. Can you please help me on this issue? -
TastyPie custom API key authorization
I am new TastyPie guy, I would like to ask some questions about TastyPie API. post/models.py class Tweet(models.Model): PRIVACY_CHOICES = ( ('0', 'Public'), ('1', 'Private'), ) name = models.CharFile(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) privacy = models.SmallIntegerField(choices=PRIVACY_CHOICES) I would like to create some APIs to: Get all posts with privacy is public (0) api/v1/post/ Owner can see/update/devete private posts (need api_key - api/v1/post/1/) User can create new post with all fields not empty (need api_key) Thanks all -
Python post forms error for manytomany relationship
My approach to creating a new instance of a new Media_Group object is: (views.py) #pk=="-1" is what i passed in as a URL parameter group_instance = None if(pk=="-1"): #Create new group group_instance=Media_Group() else: #If we're selecting an existing group from the list group_instance=get_object_or_404(Media_Group, pk = pk) #If we are editing or creating a new page we will need to submit a form... Lets do that: form = GroupForm(request.POST,pk) if form.is_valid(): group_instance.members = form.cleaned_data['members'] group_instance.name = form.cleaned_data['group_name'] group_instance.save() return HttpResponseRedirect(reverse('edit_group') ) #if pk =="-1" then lets create a new Media_Group and create a title and members if (pk == "-1"): return render( request, 'edit_group.html', context={'form': form, 'group_instance':group_instance,'all_user_groups': all_user_groups, 'user': user, 'group_members': group_members,'no_group_selected':False}) (forms.py) class GroupForm(forms.Form): group_name = forms.CharField(label='group_name',max_length=50) members = forms.ModelMultipleChoiceField(label='group_name', queryset=Member.objects.all()) class Meta: model = Member fields = ['name'] When I attempt to submit a form I get an error "<Media_Group: >" needs to have a value for field "id" before this many-to-many relationship can be used. From my understanding I need to create an id field to identify this new object and allow it to be reference but I'm not sure how to go about doing that. I also may be entirely wrong and if anyone has a suggestion … -
Deleting a table in django 1.11
How to delete an entire db table including its structure and data of a particular app? I already tried python manage.py flush. But I think it just deletes the data. I want to delete the entire table. I am using Django 1.11.4 and sqlite3 database. -
Serializing Django M2M
I am trying to serialize a django model with a many to many field in order to get them into Elasticsearch. I am not using DRF: #! usr/local/bin/python3.6 # coding: utf-8 from django.db import models from django.core.urlresolvers import reverse from .aw_search import EntryIndex class Tag(models.Model): tag = models.CharField(max_length=100, default='') slug = models.SlugField(max_length=100) class Meta: verbose_name = "Tag" verbose_name_plural = "Tags" def __str__(self): return self.slug def get_absolute_url(self): return reverse('list', kwargs={"slug": self.slug}) class Entry(models.Model): title = models.CharField(max_length=100, blank=False, null=False) slug = models.SlugField(max_length=100) content = models.TextField() posted_date = models.DateTimeField(auto_now=True) chron_date = models.DateField(auto_now=False, auto_now_add=False, blank=True) clock = models.TimeField(auto_now=False, auto_now_add=False, blank=True) ALIGN = "Align" CULTURE = "Culture" EXPENSE = "Expense" INCOME = "Income" HUMAN_RELATIONSHIPS = "Human Relationships" CATEGORY_CHOICES = ( (ALIGN, "Align"), (CULTURE, "Culture"), (EXPENSE, "Expense"), (INCOME, "Income"), (HUMAN_RELATIONSHIPS, "Human Relationships"), ) category = models.CharField(max_length=25, choices=CATEGORY_CHOICES, default=INCOME) tags = models.ManyToManyField(Tag) class Meta: verbose_name = "Diary Entry" verbose_name_plural = "Diary Entries" ordering = ["-chron_date", "clock"] def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', kwargs={"slug": self.slug}) def indexing(self): obj = EntryIndex( meta={'id': self.id}, title=self.title, chron_date=self.chron_date, text=self.content, category=self.category, tags=(self.tags.values_list('tag',)) # this is my ongoing stumbling block ) obj.save() return obj.to_dict(include_meta=True) An 8 year old bug report https://code.djangoproject.com/ticket/11310 indicates that: when you have a through relationship, you need to … -
Django RF, React, Heroku & Amazon S3 - Correct file storage
I'm using a django backend, which merely serves as an api server (no templates and HTML files are rendered). On the frontend I use react and redux to access this api and render content. The question is, should I use Django to connect to Amazon S3 and have corresponding FileField() or should I instead use React to connect to Amazon S3 and then in my django models use a CharField() to store the URL to the file? -
How to write a custom exception for TemplateView and APIView in Django which will return custom error for request.
I have written class CustomApiException(APIException): #public fields detail = None status_code = None # create constructor def __init__(self, status_code, message): #override public fields CustomApiException.status_code = status_code CustomApiException.detail = message CustomApiException.message = message which is working for APIView but for TemplateView it gives error. What is the proper way to write custom API Exception which will work for both views. -
Django UpdateView and ChoiceField issue. Django 1.11 python 3.6
I am facing a strange problem while implementing ChoiceField and UpdateView in django. I have made a small clip showing the problem that I am facing. Please watch it with subtitles/cc enabled. It will give an idea about the problem I am facing. https://youtu.be/M36TnlJvrZs. The problem goes like this..... During CreateView, I set the 'gender' ChoiceField as 'Female'. But in UpdateView it pre-populates the 'gender' ChoiceField as Male. However, The ListView renders the 'gender' field properly as 'Female'. And strangely, the django admin panel, displays no value at all for the 'gender' field. Here are all the codes: models.py: from django.db import models from django.core.urlresolvers import reverse gender_choices = (('Male', 'Male'), ('Female', 'Female')) class Birth(models.Model): full_name = models.CharField(max_length = 100) gender = models.CharField(max_length=6, choices=gender_choices) date_of_birth = models.DateField() place_of_birth = models.CharField(max_length = 50) mother_name = models.CharField(max_length = 50) father_name = models.CharField(max_length = 50) address_at_time_of_birth = models.TextField(max_length = 500) permanent_address = models.TextField(max_length = 500) registration_no = models.CharField(max_length = 50) remarks = models.CharField(max_length = 200) registration_date = models.DateField() issue_date = models.DateField() def get_absolute_url(self): return reverse('birth:birth_update', kwargs={'pk':self.pk}) #return reverse('birth:birth_home') def __str__(self): return self.full_name forms.py: from django import forms from .models import * class BirthForm(forms.ModelForm): full_name = forms.CharField() gender = forms.ChoiceField(choices = gender_choices, widget=forms.Select()) date_of_birth … -
Gunicorn 'Worker failed to boot' when running Dockerized Django application
I have a distributed Dockerized application, with four services: Django, Postgres, Caddy. All three are hosted privately on Docker Hub. I am attempting to get them running via Docker Cloud with a DigitalOcean node. The problem is with the Django service, which runs with Gunicorn. When I attempt to start the service, I get the following error: [django-1]2017-11-27T05:58:33.944903048Z Postgres is unavailable - sleeping [django-1]2017-11-27T05:58:35.176033131Z Postgres is up - continuing... [django-1]2017-11-27T05:58:36.023305930Z DEBUG 2017-11-27 00:58:36,023 base 8 140468605011712 Configuring Raven for host: <raven.conf.remote.RemoteConfig object at 0x7fc15b2b59b0> [django-1]2017-11-27T05:58:37.755913984Z 0 static files copied. [django-1]2017-11-27T05:58:38.117470416Z [2017-11-27 05:58:38 +0000] [12] [INFO] Starting gunicorn 19.7.1 [django-1]2017-11-27T05:58:38.118213362Z [2017-11-27 05:58:38 +0000] [12] [INFO] Listening at: http://0.0.0.0:5000 (12) [django-1]2017-11-27T05:58:38.118423391Z [2017-11-27 05:58:38 +0000] [12] [INFO] Using worker: sync [django-1]2017-11-27T05:58:38.122410705Z [2017-11-27 05:58:38 +0000] [15] [INFO] Booting worker with pid: 15 [django-1]2017-11-27T05:58:38.127667063Z [2017-11-27 05:58:38 +0000] [16] [INFO] Booting worker with pid: 16 [django-1]2017-11-27T05:58:38.131574049Z [2017-11-27 05:58:38 +0000] [17] [INFO] Booting worker with pid: 17 [django-1]2017-11-27T05:58:38.219843431Z [2017-11-27 05:58:38 +0000] [18] [INFO] Booting worker with pid: 18 [django-1]2017-11-27T05:58:38.702716621Z [2017-11-27 05:58:38 +0000] [23] [INFO] Booting worker with pid: 23 [django-1]2017-11-27T05:58:38.876025732Z [2017-11-27 05:58:38 +0000] [24] [INFO] Booting worker with pid: 24 [django-1]2017-11-27T05:58:39.063798754Z [2017-11-27 05:58:39 +0000] [26] [INFO] Booting worker with pid: 26 [django-1]2017-11-27T05:58:39.312288894Z [2017-11-27 05:58:39 +0000] [28] [INFO] … -
Why is Django not taking the integer in the DB and displaying it in the HTML template?
I have the following basic code, which is meant to get number X, add a simple value "+1" just as proof of concept, then save that number back into the database. Also, I require a Django based, jinja template to pull that number and render it onto a website. My question is, why is the number failing to show up? I only get a blank space where the number is supposed to be rendered and if I remove the [:1] filter, the div is generated 3x; this tells me that the issue might be somewhere in that line but I am at a loss. The code is: /views.py: from django.shortcuts import render from django.http import HttpResponse from django.template import Context, loader from home.models import DeathNum def index(request): counter = DeathNum.objects.get(pk=1) fj = counter.deaths t = loader.get_template('home/basenum.html') c = {'number_post': str(fj)[:1]} return HttpResponse(t.render(c)) def increment(request): counter1 = DeathNum.objects.get(pk=1) counter1.deaths += 1 counter1.save() t = loader.get_template('home/basenum.html') c = {'number_post': str(counter1)[:1]} return HttpResponse(t.render(c)) /models.py: from django.db import models class DeathNum(models.Model): deaths = models.IntegerField() def __str__(self): return "{0}/{1}\n".format(self.id, self.deaths) /basenum.html: {% extends "home/index.html" %} {% block content %} <br /> <div class="banner"> <div class="bannerNum"> <p div class="numberOf"> Number of deaths in Blank since 1999: … -
annotate a label to query based on thresholds that it falls within
I am trying to label my results based on two properties of my query set which falls within each combination of two threshold of another query. Here is a piece of code for clarification: threshold_query = threshold.objects.all() main_query = main.ojbects.values( 'Athreshold', 'Bthreshold' ).annotate( Case( When( Q(Avalue__lte=threshold_query['Avalue']) & Q(Bvalue__lte=threshold_query['Bvalue']), then=Value(threshold_query['label']) ... ) ) ) the model for thresholds is like: class threshold(models.Model): Avalue = models.FloatField(default=0.1) Bvalue = models.FloatField(default=0.3) label = models.CharField(default='Accepted') so there is a matrix that decides the labels. Is it possible to obtain what is in my mind using one query? my purpose is to minimize the number of queries due to enormity of Data. -
Error - NoReverseMatch
I am stuck with this : < a href="{% url 'newapp:home' %}" > revWaves< /a> Error message is : "NoReverseMatch" Reverse for 'home()' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I have created namespace for 'newapp' and url path is also correct i.e. /static/newapp/home.html and above < a href="{% url 'newapp:home' %}"> revWaves< /a> goes into header.html So i am not able to figure out what is the error. Kindly help. -
How can I get JSON from request?
How can I get JSON from request?I wrote codes, @csrf_exempt def get_json(request): print(request) return HttpResponse('<h1>OK</h1>') I post data to POSTMAN like but print(request) print out <WSGIRequest: POST '/app/get_json'> . I wanna get json in this part.So I wrote print(request.text) but error happens.Why can't I get it?I think request has json data,but is it wrong?How can I do it? -
How to convert String "[7, 9]" to Array in Javascript
I'm getting this string. (I'm getting Comma Separated Character String from Backend) "seasons": "[7, 9]" I want to iterate the array of Array like this. // example this.props.data.seasons.map((element) => console.log(element)); How do we convert "[7, 9]" to Array [7, 9]? Is it usual for you guys to handle array string? -
how to make unicode \\r\\n to \r\n
I have a Object named Post in Django. I used get_object_or_404() to get this object. And there is a TextField named text. this text Field has some string like this This is the some content.\r\n\r\nThis is another line. But when I call print funcition, this string still have no format. I want this: This is some content. This is another line. But that is : This is the some content.\r\n\r\nThis is another line. I feel so puzzled. So I run debug -> post.text is unicode, when print called, it change \r\n\r\n to \\r\\n\\r\\n. I don't know how to solve this problem. Any help will be appreciated. -
How to render Django template to show on Nginx server error message
I have done up a false system for Error 502 and linked my django HTML template, however django shows the plain html and not rendered django HTML template. unable to render Django HTML template How to configure my server setting(Nginx) so that django html template can be shown? error_page 500 502 503 504 /500.html; location = /500.html; { alias /home/user/myapp/myapp/templates/500.html; } -
Django | ORM | Get records that are divisible by an integer
Using Django's ORM, is it possible to query the db for records that has a column with value that is divisible by an integer? For example, get only records that their num column is divisible by 2 (num % 2 == 0). I hope that this is clear enough. THANKS!! -
Inexplicable, simple, 'list index out of range' -- Python
I keep trying to use this for loop. Actually a variety of for loops. I keep getting the error, 'list index out of range'. No idea. for q in range(0, len(list(package_ids))-1): if (q==0): query = 'Zero' + package_ids[q] else: query = 'More' + package_ids[q] -
ansible django deploy permission denied pip packages
I am trying to deploy my django to aws ubuntu machine. However, I keep getting this permission denied on my packages. How can I solve this ? Thanks. Here is the error: Downloading from URL https://pypi.python.org/packages/a6/1c/72a18c8c7502ee1b38a604a5c5243aa8c2a64f4bba4e6631b1b8972235dd/futures-3.1.1-py2-none-any.whl#md5=61a88f749eb3655042f95d198f783ef3 (from https://pypi.python.org/simple/futures/) Installing collected packages: boto3, botocore, certifi, cffi, chardet, coreapi, coreschema, cryptography, Django, django-bootstrap3, django-countries, django-datatable, django-rest-swagger, django-storages, djangorestframework, docutils, gunicorn, idna, itypes, Jinja2, jmespath, MarkupSafe, olefile, openapi-codec, paramiko, Pillow, psycopg2, pyasn1, pycparser, PyNaCl, python-dateutil, python-decouple, pytz, PyYAML, requests, s3transfer, simplejson, six, sorl-thumbnail, uritemplate, urllib3, dj-database-url, asn1crypto, bcrypt, futures Cleaning up... Removing temporary dir /tmp/pip_build_deploy... Exception: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run requirement_set.install(install_options, global_options, root=options.root_path) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install requirement.install(install_options, global_options, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install self.move_wheel_files(self.source_dir, root=root) File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files pycompile=self.pycompile, File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files clobber(source, lib_dir, True) File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber os.makedirs(destsubdir) File "/usr/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/boto3-1.4.7.dist-info' Below are some other related code: requirements/production.txt https://gist.github.com/anonymous/79f4d0b43f39fc317d33e09dbd1c58ba deploy.yaml https://gist.github.com/anonymous/02f68f05dab3f6858ab6aa10c89f5e09 Ubuntu: 14.04 -
Django : How to query users based on latest post
The question is simple. im building a recipe website with multiple users to submit their recipes. i want to build one page listing all the users and arrange the user hierarchy based on their latest post. what is the best way to query the users in the views.py and pass to the context? the code snippet is something like this; models.py class UserRecipe(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) so in order to query users and arrange them based on their UserRecipe created_date what is the best way to do it? -
How can I use non-Python dependencies for my Django Zappa project?
I'm using a Python package called natto-py which requires a non-python Japanese tokeniser called MeCab. Is it possible to use this for my Zappa project? How can MeCab be installed on Lambda (since pip does not work)? Django 1.10 & Python 3.5 -
How to capture HTML5 data attribute when form is submitted to views.py of Django
As you can probably tell from the nature of my question, I'm a little new to this. I have read similar post on this subject matter but most of it went right past my head and I did not feel like it was 100% applicable to the circumstance that I was facing so I thought I'd ask the question in a simplified way. The question: let's say I'm running the below HTMl form and a user submits the form to my views.py as shown in the views section below, I would able to store the value of the user selection by using: car_selection = request.POST.get('car') . My question is, how would I be able to capture the HTML5 data of " data-animal-type="spider" " ? I know there are Gurus out there but please do not explode my head. I would really need simplified help. Thanks for helping. Example HTML Form: <select name="carlist" > option data-car-type="premium" name= "car" value="audi">Audi</option> </select> Example Django View Function def getcar(request): ... if request.method == 'POST' ... selected_carn = request.POST.get('car') -
GeoDjango equivalent of ST_GeomFromGeoJson?
What is the equivalent of ST_GeomFromGeojson() in GeoDjango? I'm looking for it in GeoDjango's documentation but there's only AsGeoJSON as its output format. This can be done both using annotate and serialize. But what if I want to have a GeoJson object that I need to turn back to Geom? Use Case: geom_test = Geom.objects.filter(poly__within = [ST_GeomFromGeoJSON(d)]) -
ModelForm field attrs
According to the django docs, a modelform field accepts attrs. When I attempt to apply attrs I get TypeError: init() got an unexpected keyword argument 'attrs' The form I'm attempting to make is pretty simple, I just want to apply style to it. What am I doing wrong? forms.py from django import forms from .models import ServiceReportModel class ServiceReportCreateForm(forms.ModelForm): class Meta: model = ServiceReportModel fields = [ 'request_number', 'request_reason', 'actions_taken', ] class ServiceReportUpdateForm(forms.ModelForm): class Meta: model = ServiceReportModel fields = [ 'report_number', 'request_number', 'request_reason', 'actions_taken', ] widgets = { 'report_number': forms.CharField(attrs={'class': 'form-control'}), 'request_number': forms.CharField(attrs={'class': 'form-control'}), 'request_reason': forms.CharField(attrs={'class': 'form-control'}), 'actions_taken': forms.Textarea(attrs={'class': 'form-control'}), } views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .forms import ServiceReportCreateForm, ServiceReportUpdateForm from .models import ServiceReportModel class ReportCreateView(CreateView): form_class = ServiceReportCreateForm model = ServiceReportModel class ReportCreateView(UpdateView): form_class = ServiceReportUpdateForm model = ServiceReportModel class ReportDeleteView(DeleteView): model = ServiceReportModel success_url = reverse_lazy('reports-list') models.py import uuid from django.urls import reverse from django.db import models from django.forms import ModelForm from main import models as main_models from customers import models as customers_models class ServiceReportModel(models.Model): report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) request_number = models.ForeignKey(ServiceRequestModel, on_delete=models.PROTECT, null=True, related_name='s_report_number' ) reported_by = models.ForeignKey(main_models.MyUser, editable=False, related_name='reports') reported_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(main_models.MyUser, editable=True, blank=True, … -
Sort queryset using two columns then paginate efficiently
I've a queryset which I want to sort using one of the columns, say date1, and if the value of date1 is None then use another column date2 for sorting and if date2 is also None then use datetime.max. So, this is what I came up with : queryset = sorted(queryset, key= lambda row: row.date1 if row.date1 else row.date2 if row.date2 else datetime.max) and then for paginating (with say 20 in one page) I'm sending back the id of last record of previous request and using that to get the next 20 items (since after sorting ids are now in in random order). Also the entries can be deleted by the users so, using Paginator.page and just fetching the consecutive pages in requests won't work. This is how I find the index of the lastRecord for getting the next 20: lastRecordIndex = next(i for (i, d) in enumerate(queryset) if d.id == lastRecord) queryset = queryset[lastRecordIndex+1: lastRecordIndex+20+1] So, the problem is that this approach works, but is way too slow. Is there anything better I can do? using raw query or something else in django?