Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read a JSON file Django
How do I read a JSON file in Django, iterate through it, and display it? Any ideas would be helpful. -
Using signal to index a model
I have followed many examples and docs, but cannot get this right. I'm trying to make my Elasticsearch index whenever I update a model. Using the 'autoindex' does not log M2M's. It should update the when I change a Tag field (eg rename, or delete one). It should update when I add or remove a Tag from Item I am using django-elasticsearch (here) which is a wrapper around elasticsearch-py. How is this correctly achieved? class Tag(models.Model): name = models.CharField(max_length=500, blank=True) taglevel = models.IntegerField(null=True, blank=True) class Item(EsIndexable, models.Model): title = models.CharField(max_length=100, blank=True) tag = models.ManyToManyField('Tag', blank=True) class Elasticsearch(EsIndexable.Elasticsearch): serializer_class = TaskEsSerializer fields = ['title', 'tag'] @receiver(post_save) def index_elastic(sender, instance, *args, **kwargs): Item.es.do_index(instance) print(instance) -
Anyway to stop form.fields['level'].choices=[(q,q)] from logging me out in django?
I have a choice field that is populated dynamically thru jquery. Hence, to validate it, I need to add the selected option to the form before validation. Following this SO tip, tried the following but I get logged out automatically. I suspect the request object, which I pass to my form is the cause. if request.method=='POST': form=NewForm(request,request.POST) q=request.POST.get('level') #the line below automatically redirects me to my client login page form.fields['level'].choices=[(q,q)] if form.is_valid(): It is important that I pass request object to the form. How can I fix that while keeping it, since I am guessing it is the problem? How can I of -
Combining QuerySets based on a shared column - django
Models.py class sells(models.Model): #unimportant stuff here type = ... supplier = ... user = ... item_id = models.AutoField(primary_key=True) class sale_items(models.Model): item_id = models.OnetoOneField(sells, on_delete=models.CASCADE, null=True) item_name = ... description = ... #other unimportant stuff So I'm trying to implement search, and right now I have it so that search returns any information found in sale_items such as name and description. But I also need to output an items type and supplier which is in the sells model. Essentially I am trying to do something like this: SELECT A.item_id, A.item_name ... B.type, B.supplier ... FROM sale_items A, sells B WHERE A.item_id = B.item_id Views.py def SearchView(request): query_results = sale_items.objects.filter(Q(item_name__icontains=search) Q(description__icontains=search)) return render(request, 'db/search_results.html', {'query_results':query_results}) I did not include the code for the variable search, but it is the text that was entered into the search bar. query_results is correct and in my template (search_results.html) I use a for loop to print out the item name and description. I would like to somehow also include the information in the sells model that corresponds to the same item_id. I've been trying a lot of different things to try and get this to work and cannot figure it out. -
Using geoip2 for timezone look up
The django.contrib.gis.geoip2 framework expose a high level geolocation api. I want to use it to look up the user timezone, but the queries do not return the timezone, although the maxmind documetion says that their databases include them. Am I missing something or how could this be done? -
How to upload an image through copy / paste using django modelform?
I'm pretty new with django, and trying to migrate a google apps script (GAS) webapp to django. One feature I had on google website was to capture a pasted image from clipboard and submit it through a form. That was done through a hidden field in the form: <input type="hidden" name="summaryImage" id='summaryImage' value=''> and then I capture the paste event to populate this hidden form field /* Handle paste events */ function pasteHandler(e) { if (e.clipboardData) { // Get the items from the clipboard var items = e.clipboardData.items; if (items) { // Loop through all items, looking for any kind of image for (var i = 0; i < items.length; i++) { if (items[i].type.indexOf("image") !== -1) { // We need to represent the image as a file, var blob = items[i].getAsFile(); var URLObj = window.URL || window.webkitURL; var source = URLObj.createObjectURL(blob); var reader = new FileReader(); reader.onload = function(e) { document.getElementById("summaryImage").value= reader.result; } reader.readAsDataURL(blob); } } } } } The above form when submitted through google, can be parsed on the server side google apps script (GAS) from the summaryImage field in the form, like below: var splitBase = form.summaryImage.split(','), var type = splitBase[0].split(';')[0].replace('data:',''); var byteCharacters = Utilities.base64Decode(splitBase[1]); var blob … -
Confirming SNS subscription request using Django(boto3)
I am trying to make a Django Application which subscribes to the SNS and displays the messages published. I am currently working on first part. I made a view function in which if there is any post data then the function should send confirm subscription to the arn using boto3.Currently i am working incrementally and for all http post requests it returns the subscription confirmation. I have tied this function to a url test. Now I deploy the application on ELB and give the HTTP endpoint as xyz.com/test where xyz.com is link given by Elastic bean stalk. But subscription request is never confirmed on aws console. Below is the code,can somebody point out the error or any other way. Code: client = boto3.client('sns',region_name='us-east-2') @csrf_exempt def test(request): if request.method =='POST': header = json.loads(request.body) token=header['Token'] arn=header['TopicArn'] response = client.confirm_subscription( TopicArn=arn, Token=token, AuthenticateOnUnsubscribe=False ) In urls.py: url(r'^test',test) -
Django Celery Elastic Beanstalk supervisord no such process error
My celery_config.txt in file script in .ebextensions #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A wellfie --loglevel=INFO directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv [program:celeryd-beat] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery beat -A wellfie --loglevel=INFO --workdir=/tmp -S django directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-beat.log stderr_logfile=/var/log/celery-beat.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send … -
JQuery autocomplete text search with results from remote source
I'm trying to implement an input field with an autocomplete feature. I'd be using Google Books API to autocomplete names of books based on the keyword that the user enters in the input text field. I'd be using Django as my framework to implement this feature. This is what I have been able to do so far: JS $( document ).ready(function() { $("#id_book_name").on("change paste keyup", function() { var app_url = document.location.origin; var book_name = $('#id_book_name').val(); var url = app_url+'/book-search/'; if(book_name.length > 4) { var data = { 'book_name': book_name, 'csrfmiddlewaretoken': document.getElementsByName('csrfmiddlewaretoken')[0].value, }; console.log(data); $.post(url, data).done(function(result) { for(var book_title of result) { console.log(book_title); } console.log(result); }).fail(function(error) { console.log(error) }); return false; } }); }); Here, #id_book_name is the id of my input text field. As soon as the length of the keyword entered by the user exceeds 4, I'm sending a POST request to /book-search which is mapped to the following Python function where I hit Google Books API's endpoint and return the book titles in a specific JSON format: def book_search(request): book_results = {'titles':[]} key = 'XXXXXXX' url = 'https://www.googleapis.com/books/v1/volumes?q=' + request.POST['book_name'] + '&maxResults=5&key=' + key result = requests.get(url) json_result = json.loads(result.text) if 'items' in json_result: for e in json_result['items']: … -
don't understand Usercreation form in django
class UserCreationForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = User fields = ("username",) field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) self.instance.username = self.cleaned_data.get('username') password_validation.validate_password(self.cleaned_data.get('password2'), self.instance) return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user I get completely lost with Class Meta: and init method. What I think: Class Meta: Class Meta calls models.Model(USER), where all the fields are made. And then it select field ('Username')?? For what reason? Does Class Meta in this case means: "Look, we need password1 and password2, however we can call username from models.model(USER) and use username(max_length) as form object? I am really confused. __init__ if self._meta.model.USERNAME_FIELD in self.fields: I think I am just looking at alien. What this suppose to mean … -
The clickable-row doesn't affect a button
The .html file is <tbody> {% for row in results %} <tr class="{% cycle 'row1' 'row2' %} clickable-row" data-href="{% url "perception:detail" pk=row.object.pk %}"> {% for item in row.cols %} {{ item }} {% endfor %} {% if row_actions_template %} <td class="row-actions">{% include row_actions_template with object=row.object %}</td> {% endif %} </tr> {% endfor %} </tbody> The .js file is $(function(e){ $(".clickable-row").click(function() { window.location = $(this).data("href"); }); }); The views.py file is class PerceptionIndexView(StaffRestrictedMixin, FrontendListView): page_title = _('Perception') model = Perception template_name = 'loanwolf/perception/index.html' pjax_template_name = 'loanwolf/perception/index.pjax.html' # row_actions_template_name = 'loanwolf/perception/list-actions.inc.html' url_namespace = 'perception' def active(self, obj): if obj.is_active: return icon(obj.get_icon(), css_class='green-text', tooltip=_('Active')) else: return icon(obj.get_icon(), css_class='red-text', tooltip=_('Inactive')) def notes_count(self, obj): return obj.notes.count() notes_count_label = _('Notes') def get_change_url(self, obj): return obj.get_absolute_url() class Meta: ordering = ('-created', '-modified') sortable = ('start_date', 'end_date', 'created', 'state', 'modified') list_filter = ('state', 'is_active', customer, error) list_display = ( '__unicode__', 'context_menu', 'state', 'start_date', 'end_date', 'current_balance', 'operation_error', 'modified', 'created', 'notes_count', 'active' ) The part of the models.py file is @python_2_unicode_compatible class Perception(xwf_models.WorkflowEnabled, TimeStampedModel): loan = models.ForeignKey('loans.Loan') state = xwf_models.StateField(PerceptionWorkflow) start_date = models.DateField(_('Start date')) end_date = models.DateField(_('End date'), blank=True, null=True) current_balance = models.DecimalField(_('Current balance'), default=0, decimal_places=2, max_digits=11) operation_error = models.SmallIntegerField(_('Operation error'), default=0) notes = GenericRelation(Note) def get_absolute_url(self): return reverse('perception:detail', kwargs={'pk': … -
how to save TaggableManager with post and render it with get? django
I have read some threads and still confused how I can save taggableManager using post in view.py? My model.py class Profile(models.Model): tags = TaggableManager(blank=True) In my view.py profile = Profile() request.POST['tags'] // this would give me the tag value which I think should be correct for example "hello" or "hello,yellow" profile.tags = request.POST['tags'] profile.save() // saves the profile but when I try looking in the admin dashboard, it's not saved though. I tried rendering the tags out using a get method for example profile_obj = Profile.objects.get(pk=pk) // which returns my profile obj print(profile_obj.tags) // this would give me an error of no name attribute I am quite confused now. Can someone please give me a hand? Thanks in advance -
django - use chunk to read uploaded file will break down some row
I want to use for chunk in f.chunks() to read a huge csv file. It works well in first record, but I found it will break the row when the rows reach chunk's size As I know the chunk's default size is 64KB. For example, I have three rows in csv file: 'this is first row' 'this is second row' 'this is third row' when I use for chunk in f.chunks(), I expect to get chunk1 contains 'this is first row', chunk2 contains ('this is second row', 'this is third row' ) or chunk1 contains ('this is first row','this is second row'), chunk2 contains ( 'this is third row' ) but the real result will be: chunk1 contains ('this is first row', 'this is'), chunk2 contains ('second row', 'this is third row') That it is, it will break second row 'this is second row' into different chunks. Is it possible to prevent chunk breaking the row? Thanks. -
Django Chat (Communication bewteen Django and Python)
I want to create chat in Django. Scheme is like Server must be on Django Server and Clients will be installed on PCs. I want to know is there any way to create Django Chat Server on web and Client Software for PCs? -
What is the best way to handle functional django model field defaults?
Sometimes a ForeignKey field needs a default. For example: class ReleaseManager(BaseManager): def default(self): return self.filter(default=True).order_by('-modified').first() class Release(BaseModel): default = models.BooleanField(default=False) ... class Server(models.Model): ... release = models.ForeignKey(Release, null=True, default=Release.objects.default) All is well and good with the above code until the time comes for db migration whereupon the functional default causes big problems because the default function cannot be serialized. Manual migration can work around this but on a large project where migrations are perhaps squashed periodically this leaves a time bomb for the unwary. A common workaround is to move the default from the field to the save method of the model but this causes confusion if the model is used by things like the rest framework or in creating forms where the default is expected on the field. -
How to view a JSON file in Django
So I have a JSON file and I want to iterate over it and display the information using Django. How do I do that and do I need to set up a Model like normal? How do I transfer this data to the database model using SQLite? I found this code on a similar stackoverflow question but I don't know how to show the data like via HTTPResponse so the user can view the data: import json json_data = open('/static/prices.json') data1 = json.load(json_data) // deserialises it data2 = json.dumps(json_data) // json formatted string json_data.close() -
models not showing on django admin
I'm just starting my first project using Django 1.11. I followed the same steps I've used on multiple Django 1.10 projects, but for some reason my models are not showing up on my localhost/admin site. My INSTALLED_APPS from settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] My admin.py: from django.contrib import admin from home.models import Home # begin Admin Class Definitions class HomeAdmin(models.ModelAdmin): fieldsets = [ ('Title', {'fields': ['title']}), ('Publication Date', {'fields': ['pub_date']}), ('Home Page Text', {'fields': ['header', 'sub_header', 'link_text']}), ] list_display = ('title', 'pub_date') list_filter = ['pub_date'] admin.site.register(Home, HomeAdmin) My [main_app]/urls.py: from django.conf.urls import url, include from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('home.urls')) ] But when I go to localhost:8000/admin the only things present are Groups and Users as if I hadn't registered any models at all. I have run makemigrations and migrate, and I have tried putting admin.py within the app directory instead of the project directory. It's currently in the [project_name]/[project_name] directory (the one with settings.py, urls.py, and wsgi.py files). Any suggestions? -
'Post' object has no attribute 'COOKIES'
I have Mezzanine up and working, and another forum app works fine as a standalone project. Now when I try to plug in the forum app to the existing Mezzanine project, I get this error message and cannot figure it out. AttributeError at /forum/post/1/ 'Post' object has no attribute 'COOKIES' Request Method: GET Request URL: http://localhost:8000/forum/post/1/ Django Version: 1.10.5 Exception Type: AttributeError Exception Value: 'Post' object has no attribute 'COOKIES' Exception Location: /Users/jc/Desktop/ppp36/cjc/lib/python3.5/site-packages/mezzanine/generic/forms.py in __init__, line 106 Python Executable: /Users/jc/Desktop/ppp36/cjc/bin/python Python Version: 3.5.3 Python Path: ['/Users/jc/Downloads/All-About-Books-master', '/Users/jc/Desktop/ppp36/cjc/lib/python35.zip', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5/plat-darwin', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/Users/jc/Desktop/ppp36/cjc/lib/python3.5/site-packages'] Server time: Tue, 18 Apr 2017 17:27:49 +0000 The template error page: 'Post' object has no attribute 'COOKIES' 135 </ul> 136 </div> 137 </div> 138 </li> 139 {% endfor %} 140 </ul> 141 <div class="card"> 142 <div class="card-header">reply</div> 143 <div class="card-block"> 144 {% if user.is_authenticated %} 145 {% render_comment_form for post %} 146 {% else %} 147 <a href="{% url 'account_login' %}?next={{ request.path }}">log in</a> 148 {% endif %} 149 </div> 150 </div> 151 </main> 152 {% endblock main %} 153 154 {% block script %} 155 <script> This is where the error occurs: enter image description here -
How to parse to an int? Django
The user can select two objects to compare against. This is the where the ID's are retrieved ids = [id for id in request.GET.get('ids') if id != ','] aircraft_to_compare = Aircraft.objects.filter(id__in=ids) However it throws the IndexError at /delta/ - list index out of range error. I'm getting the list with ['5','6'] instead of [5,6] I have a feeling I need to parse it to an int, but I don't know how to do that. Any help? -
Edit related DB entries in different tables
I'm working on simple expenses managing app. Every user has number of Accounts and Operations related to him. Newly added operation has influence on the specific account's current_balance field. I want user to have a possibility of editing already added Operations. I have created edit_operation view which takes back changes made to current_balance field and then calculates new value based on new operation's amount provided by the user. Here is my edit_operation method code: def edit_operation(request, operation_id): instance = get_object_or_404(Operation, pk=operation_id) previous_account = instance.account previous_type = instance.type previous_amount = instance.amount if request.method == "POST": form = OperationForm(request.POST, instance=instance) if form.is_valid(): # restore the account balance account = Account.objects.get(name=previous_account) account.current_balance -= previous_type * previous_amount account.save() # apply new operation operation = form.save(commit=False) operation.user = request.user account = Account.objects.get(name=operation.account) account.current_balance += operation.type * operation.amount account.save() operation.save() return redirect('index') else: form = OperationForm(instance=instance) return render(request, 'expenses/operation.html', {'form': form}) It works just fine but I'm wondering why my previous solution didn't work as expected. With my original approach I didn't use previous_account, previous_type and previous_amount helping variables. I just used instance attributes directly: # restore the account balance account = Account.objects.get(name=instance.account) account.current_balance -= instance.type * instance.amount account.save() However it seemed like at this point … -
Removing fieldsets from a form
I've installed django-betterforms to simplify form templates and put an end to {% if field.name == 'blah' %} in templates to include arbitrary content. So I've got fieldsets defined, but need to remove a fieldset under a certain condition. The trouble I'm having is the form fieldsets seem to have been setup before I'm able to modify things. class EntrantForm(BetterModelForm): class Meta: fieldsets = ( Fieldset( 'details', ('first_name', 'surname', 'dob'), legend=_("Section 1") ), Fieldset( 'address', ('address_1', 'address_2', 'city', 'county'), legend=_("Address") ), Fieldset( 'section2', ('facts', ), legend=_("Section 2"), ), Fieldset( 'section3', ('needs', ), legend=_("Section 3"), additional_content=mark_safe("<p>Hello world</p>") ), Fieldset( 'terms', ('photo_accepted', 'terms_accepted') ) ) model = Entrant For certain users, we don't need to show section 3, so I've tried to remove it from the form fieldset and the meta fieldset, but it's a bit stubborn! class EntrantForm(BetterModelForm): """ Entrant form """ def __init__(self, *args, **kwargs): region_type = kwargs.pop('region_type', None) if int(region_type) != int(Manager.RegionTypes.REGION): self.Meta.fieldsets = tuple_without(self.Meta.fieldsets, 'section3') # returns a tuple without the Fieldset for 'section3' self.fieldsets.rows.pop('section3') -
Django : Checking if user exists, not showing validationerror
(New at Django)I've tried everything and spent the whole day trying to get this to work. I am trying to check if user exists and display ValidationError if it already exists. Right now, i am using views.py to show template that says account not created because the validation error that forms.py should be taking care of is not showing. forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['email'].required = True password = forms.CharField(widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError("That user is already taken") return username class Meta: model = User fields = ['username', 'password', 'email'] labels = { "email": "Email" } # including my login form too just in case class LoginForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'password'] labels = { "email": "Email" } views.py from django.shortcuts import render, redirect from .forms import UserForm def index(request): if request.user.is_authenticated: return redirect('/myaccount') else: title = "welcome" form = UserForm() context = { "template_title": title, "form": form } return render(request, "index.html", context) def new_user(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") form.save() return … -
Django's FileField open(mode='r') opening as bytestring instead of string
I have a model with a FileField that saves a text file, here's how I'm accessing it: report = MyMoodel.objects.get() document_report = report.document document_report.open(mode='r') print(type(document_report.read())) The resulting "type" is <class 'bytes'> Shouldn't I be receiving a string instead of bytestrings? Am I using open incorrectly? -
Django formset return empty instances
I have a class that inheirts from BaseInlineFormSet, where I override the save() method: class CustomBaseModelFormSet(BaseInlineFormSet): def save(self, something=None, commit=True, *args, **kwargs): instances = super(CustomBaseModelFormSet, self).save(commit=False) but when I call formset.save() to create new objects with a bound and valid formset, the variable instances is an empty list! Why the the save() of the parent class is not saving? there's no trace of any error. I'm using Python 3 and Django 1.10.5. -
Form control in Django ForeignKey
My Models: class Faculty(models.Model): name = models.CharField(max_length=30) class Program(models.Model): name = models.CharField(max_length=30) faculty = models.ForeignKey(Faculty) class Student(models.Model): name = models.CharField(max_length=30) faculty = models.ForeignKey(Faculty) program = models.ForeignKey(Program) Let I have Two Faculty: Science Management And I have 3 Programs in each: Science B. Computer B. Software B. Civil Management BBA BBS BBI And What I want is When A studen Is Filling up a Form They can Select Faculty and Programs. So When a user select Science as Faculty. Then How to make django Gives Only Programs From That selected Faculty? That means when users select Science in Faculty Field Then in program field Computer, Software and Civil should be Shown. Is it possible? then how? I think I make a clear question. (easy to understand what I mean)