Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display my form in template
I'm new to django and I've been following a tutorial to help me create my project. My problem is that I can't seem to display my from on my html page. line of code from my html file <form action="admin/signup/" method="post"> <div class="form-horizontal form-label-left"> {% csrf_token %} {% for field in signupForm %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <div class="ln_solid"></div> <div class="form-group"> <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-4"> <button class="btn btn-primary">Cancel</button> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </div> </form> my signup form class class SignUpForm(UserCreationForm): usertype = forms.CharField(max_length=10) userID = forms.CharField(label="User ID") class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'userID', 'usertype') and my signup page view def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.usertype = form.clean_data.get('usertype') user.profile.userID = form.clean_data.get('userID') user.save() else: form = SignUpForm() context = { 'signupForm' :form } return render(request, 'admin.html', context) any possible solutions and suggestions are appreciated, thanks! -
Unable to get base64 data in POST request
I'm having trouble while reading data from POST request. Request screenshot enter image description here It seems everything is fine from frontend but when I'm getting nothing when trying to read the request data on the backend. request.FILES <MultiValueDict: {}> request.POST <QueryDict: {}> request.body *** RawPostDataException: You cannot access body after reading from request's data stream I'm completely blank, any help would be appreciated. -
Django faceting sub-categories via foreign keys
I have a list of items that have a 'top category' and a 'middle category', eventually there will be a 'lower category' but not right now. For example Electronics > Laptops, respectively. I want to dynamically facet on this categories, so laptops will display under electronics etc. Any thoughts on how I can acheive this? Currenty I have the 'Top Categories' faceting correctly. models.py class mid_category(models.Model): class Meta: verbose_name_plural = 'Mid Categories' name = models.CharField(max_length=500) def __str__(self): return self.name class top_category(models.Model): class Meta: verbose_name_plural = 'Top Categories' name = models.CharField(max_length=500) mid_cat = models.ForeignKey(mid_category, null=True) def __str__(self): return self.name # Item class Product(models.Model): title = models.CharField(max_length=500, db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) retailer = models.CharField(max_length=255) image = models.CharField(max_length=1000) url = models.URLField(max_length=800, unique=True, default='') sku = models.BigIntegerField(default=0) barcode = models.BigIntegerField(default=0) featured = models.CharField(max_length=255, db_index=True, choices=FEATURED_CHOICES, default='NO') timestamp = models.DateTimeField(auto_now=True) top_cat = models.ForeignKey(top_category) mid_cat = models.ForeignKey(mid_category, null=True) def __str__(self): return self.title search_indexes.py import datetime from django.utils import timezone from haystack import indexes from haystack.fields import CharField from decimal import Decimal from .models import Product, top_category class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField( document=True, use_template=True, template_name='/home/wilkinj33/bargainforest/bargainforestenv/motorclass/templates/search/indexes/product_text.txt' ) title = indexes.EdgeNgramField(model_attr='title') retailer = indexes.CharField(model_attr='retailer', faceted=True) price = indexes.IntegerField(model_attr='price', faceted=True) barcode = indexes.CharField(model_attr='barcode') topCat = indexes.CharField(model_attr='top_cat', faceted=True) midCat … -
Django MySQL IntegrityError: ("Field 'created_at' doesn't have a default value")
I am new to Django. IntegrityError: (1364, "Field 'created_at' doesn't have a default value") occurred when I didn't write created_at for models I defined at models.py. Every time I face such error, I add created_at = models.DateTimeField(default=timezone.now, null=True) to models.py and then run makemigrations; migrate --fake. Is that OK? (I mean, does it follow Django best practice or not? ) When I was using Rails, I've never faced such issues. Also, I'd like to know why --fake option removes this error. version Django==1.11.5 mysqlclient==1.3.12 Python 3.6.1 Thanks in advance. -
How to use orderby based on condition in Django?
I have a model called DemoModel and i am querying it i.e; DemoModel.objects.all() I am fetching all the objects but i want to do order_by based on condition i.e; In my models there is a field called demo_field, if that field value is 'Testing' then it should be ordered using that condition DemoModel.objects.all().order_by(demo_field='Testing') Is there anything like this? or we have to create customized order_by? -
ForeignKey relashionship to geojson serializer
I have 2 models, lets call them Model1 and Model2. And I would like to add an image from Model2 as a field, like the featured_image property into the serialized output. But I can't pass in a property since it is not a field. Is there some elegant way of doing this? models.py class Model1(models.Model): model1 = models.CharField(max_length=200, null=True) point = PointField(null=True) slug = models.SlugField(max_length=200, unique=True, default='') def __str__(self): return self.project def get_absolute_url(self): return reverse('model1-detail', kwargs={'slug': self.slug}) @property def featured_image(self): image = self.images.all() return image[0] class Model2(models.Model): model1 = models.ForeignKey(Model1, related_name='images') order = models.PositiveIntegerField(default=1) views.py JSONSerializer = serializers.get_serializer('geojson') json_serializer = JSONSerializer() with open('path/to/file.geojson', 'w') as out: model1 = Model1.objects.all() json_serializer.serialize(model1, geometry_field=('point'), fields=('point', 'model1', 'slug'), stream=out) I've tried writing a simple function that would return the featured_image. JSONSerializer = serializers.get_serializer('geojson') json_serializer = JSONSerializer() with open('path/to/file.geojson', 'w') as out: model1 = Model1.objects.all() def featured_image(): image = Model1.featured_image return image json_serializer.serialize(architecture, geometry_field=('point'), fields=('point', 'project', 'slug', featured_image), stream=out) I've tried fooling around with filters such as, but it return a wrong queryset. model1 = Model1.objects.all() image = model1.filter(images__order=1) model1 = list(model1) + list(image) -
Django custom Func
While tried to find solution for the Django ORM orderby exact i generated custom django Func: from django.db.models import Func class Position(Func): function = 'POSITION' template = "%(function)s(LOWER('%(substring)s') in LOWER(%(expressions)s))" def __init__(self, expression, substring): super(Position, self).__init__(expression, substring=substring) and it's work, but by comment @hynekcer "It crashes easily by ') in '') from myapp_suburb; drop ... expected that the name of the app is "myapp and autocommit is enabled. " The main trouble is: that extra data (substring) putted into the template without sqlescape. I could not found the django way solution. P.S. how this function work: class A(models.Model): title = models.CharField(max_length=30) data = ['Port 2', 'port 1', 'A port', 'Bport', 'Endport'] for title in data: A.objects.create(title=title) search = 'port' qs = A.objects.filter( title__icontains=search ).annotate( pos=Position('title', search) ).order_by('pos').values_list('title', flat=True) # result is # ['Port 2', 'port 1', 'Bport', 'A port', 'Endport'] -
page redirection in django views + reactjs
I am stucked in one Situation that i need to redirect page after user login but i have also used rest-auth for token authentication.Here is my django views.py: @ensure_csrf_cookie def loginform(request,LoginView): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user_data=User.objects.create_user(username=request.POST['username'],email=request.POST['email'],password=request.POST['password']) print (email," ",password) return render(request, 'inventory/index.html', {'email':email,'password':password}) return render(request, 'inventory/index.html', {}) And here is my login component (login.js): import React, { Component } from "react"; import ReactDOM from 'react-dom'; import DjangoCSRFToken from 'django-react-csrftoken'; import { Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap"; var formStyle={margin: '0 auto',maxWidth: '320px'} var loginStyle={padding: '60px 0'} class Login extends React.Component { constructor(props) { super(props); this.state = { email: "", password: "" }; } render() { return ( <div className="Login" style={loginStyle}> <form style={formStyle} method="post"> <DjangoCSRFToken/> <FormGroup controlId="email" bsSize="large"> <ControlLabel>Email</ControlLabel> <FormControl autoFocus type="email" name="email" /> </FormGroup> <FormGroup controlId="password" bsSize="large"> <ControlLabel>Password</ControlLabel> <FormControl type="password" name="password" /> </FormGroup> <Button block bsSize="large" type="submit" > Login </Button> </form> </div> ); } } ReactDOM.render(<Login/> , document.getElementById("login")); Now i need to Redirect on index page after user logged in. What should i do? -
Two ModelForms in one CreateView
This probably have no sense, but it's better to get advice how to implement this behavior properly. I have User model and two others (let it be A and B). Both A and B have ForeignKey to User. On User creation I also create A and B for this User: def save(self, *args, **kwargs): user_id = self.id super(User, self).save(*args, **kwargs) if user_id is None: as_A = A(user=self) as_A.save() as_B = B(user=self) as_B.save() The only required field in A and B is user = models.OneToOneField(User), others are optional. class A(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) x = models.CharField(max_length=100, blank=True) class B(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) y = models.CharField(max_length=100, blank=True) I want to provide two forms for registration: as A or as B. In registration form as A, customer should be able to set fields for A model entity related to User. Similar for B. This is my RegistrationForm: class RegistrationForm(forms.ModelForm): password = forms.CharField( strip=False, widget=forms.PasswordInput, ) confirm_password = forms.CharField( strip=False, widget=forms.PasswordInput ) class Meta: model = User fields = ['email', 'first_name', 'password'] def clean(self): cleaned_data = super(RegistrationForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError("Passwords are not same") return cleaned_data As you can see it contains only … -
django transfer variable between html's
Hi i am trying to create a search engine and i need to make the table id stay in the link. In my CrawledTables have all the tables with the id...and i need to pass that id into the var pk through the links...cause then i request to get that pk and use the pk to get the table name. and then use the table name to get the data inside the table i searched for...and make a search engine inside those table info. This is my views.py def search_form(request): return render(request, 'search/search.html') def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] name = Crawledtables.objects.filter(name__icontains=q) return render(request, 'search/results.html', {'name': name, 'query': q}) else: return HttpResponse('Please submit a search term.') def search_form_table(request): return render(request, 'search/search_table.html', {'tbl_nm': table_name}) def search_table(request, pk): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] table_name = Crawledtables.objects.get(id=pk) print table_name t = create_model(table_name.name) print t title = t.objects.filter(title__icontains=q) print title return render(request, 'search/results_table.html', {'tbl_name': table_name, 'details': title, 'query': q}) else: return HttpResponse("Please submit a search term!") this is my search/urls.py urlpatterns = [ url(r'^results$', views.search, name='search'), url(r'^$', views.search_form, name='form'), url(r'^(?P<pk>\d+)/$', views.search_form_table, name='table_search'), url(r'^(?P<pk>\d+)/results$', views.search_table, name='table_results'), ] this is my search.html <form action="/search/results" method="GET"> <input type="text" … -
Django REST UnitTest No file was submitted
I successfully implement with small cases. Then I started to work with bigger structure. And I got the error. Error: No fie was submitted. import tempfile from unittest import skip from django.conf import settings from django.contrib.auth.models import User from django.core.files import File from django.core.files.uploadedfile import SimpleUploadedFile from model_mommy import mommy from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase, APIClient class CustomerFromExcelViewsetTest(APITestCase): def setUp(self): self.client = APIClient() self.soken_staff = mommy.make(User, username='spearhead') self.user = mommy.make(User, username='Justin') settings.MEDIA_ROOT = tempfile.mkdtemp() def test_upload_file(self): """Expect created_user, and updated_user correct set""" file = File(open('./soken_web/apps/uploaded_files/complete-customer.xlsx', 'rb')) uploaded_file = SimpleUploadedFile('new_excel.xlsx', file.read(), content_type='multipart/form-data') data = { file: uploaded_file, } self.client.force_authenticate(user=self.user) response = self.client.post(reverse('api:customer_from_excel-list'), data, format='multipart') response.render() self.assertEqual(status.HTTP_201_CREATED, response.status_code) Here they are the models, serializers, and viewsets models.py https://gist.github.com/elcolie/52daf2bd144af82b348f7353656be434 serializers.py https://gist.github.com/elcolie/7f097642c4a752e76044c6938c49e097 viewsets.py https://gist.github.com/elcolie/34fa66632209f14624899d997919d3fb After a day I could not figure out where is the that bug. References: DRF APITestCase not use `multipart` with other param -
Django: Basic Auth for one view (avoid middleware)
I need to provide http-basic-auth for one view. I want to avoid to modify the middleware settings. Background: this is a view which gets filled in by a remote application. -
Migrating Django from 1.9 to 1.11: forms.MultiWidget.format_output disappeared
This method was very usefull to render MultiWidget in Django 1.9: format_output(rendered_widgets) I use it in many places, here is an example of use: def format_output(self, rendered_widgets): items = [ '%s %s' % (rendered_widgets[i], f) for (i,f) in enumerate(self.fieldnames) ] if self.aligned: return '<li>' + '</li><li>'.join(items) + '</li>' else: return ' '.join(items) It disappears in Django 1.11, and I don't find a natural replacement. The render method seems to be the unique alternative, but I don't understand how to use it correctly. Does anybody have ideas? -
Django call script in view from template
I have a view, that displays entries from one date to another, about a certain project. The project model is called "DNN" and times on there are in the "Vnos" model. views.py: def po_nalogu(request, dnn = None): dnn = None form = PregledDNNForm( request.GET or None, ) from_date = get_month_start(timezone.now()) to_date = from_date + relativedelta(months=1) if request.GET: if form.is_valid(): from_date, to_date, dnn = form.save() entries_qs = Vnos.objects.filter(dna__dns__dnn = dnn) month_entries = entries_qs.timespan(from_date, to_date=to_date).order_by('start_time') sestevek = 0 for entry in month_entries: sestevek = sestevek + entry.hours template = 'porocila/po_nalogu.html' context = { 'form' : form, 'from_date': from_date, 'to_date': to_date - relativedelta(days=1), 'entries': month_entries, 'sestevek' : sestevek, } return render(request, template, context=context) Now, I want to add a conditional sentence, so I could print PDF. Is there a way to add something like: if request.method == "PDF" do code and in template: <form action="" method="PDF"> <input type="submit" /> </form> I don't want to do a separate view for the PDF file, because of the from and to dates, as it is a lot of computing one more time. Thank you -
Is there any way to separate py and pyc files while building Django project using pybuilder
I was trying to build a Django project using pybuilder where I need to separate the pyc files and resource files. This is regarding protecting the source code, I know we can achieve this by the licencing mechanism. Our requirement is distributed the pyc file to the client instead of actual py file. -
How to allow googlebot to crawl publically visible pages on my django site that are behind login?
I've found several posts about this but can't seem to get a straight answer for my case. I'm using django allauth to make users sign up before posting anything. However, all the pages are visible to the public and don't require login to view. How do I allow google to crawl the pages without having to go through the login? Would a simple sitemap work? I looked into first click free but from what I read it only crawls the first page after the login? Or should I whitelist the IP's? Any direction would be great, thanks. -
I need to paginate results in django using hundreds of thousands of rows without running the query again
I need to paginate a very large result (300,000 rows) but I don't want to run the query again. Is there a way to make two search(request): the first one to give me the list with the data, and the second result(request): to post the queried data from the first request. I'm trying to do this so I don't have to run the query again and again after displaying every page. Any help would be appreciated! -
Call a Django python function from tag script in the template
This is some content of my Django template. ... <a id="ID" href="">Do operation with database.<a/> ... <script type="text/javascript"> window.onload = function () { var a = document.getElementById("ID"); a.onclick = function () { if (confirm("do you really want to perform task?")) { /** call python function in order to perform some operations with database **/ } return; } </script> ... The function is for example(we can imagine the function is in views.py): def performtask(): #do my operation with the database My question is, how it is possibile to call performtask() function from the script tag in my template? -
How can I see my my calculated field from model in the drop down that was dynamically generated with Ajax?
In models I have calculated field total And I want to see this field in my dynamic drop boxes generated with Ajax. But I just get undefined in dropdown. My data flows in following way: 1-I have sterilizer in my api class LeaseTermSerializer(serializers.ModelSerializer): class Meta: model=LeaseTerm fields = '__all__' 2-I have api method in view @api_view(['GET']) @csrf_exempt def get_leaseterm(request, tid): leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True) leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True) response = Response(leaseterm_serializer.data) return Response(response.data,status=status.HTTP_200_OK) 3-In my template I build it like this function getleaseterm() { //get a reference to the select element $select = $('#leaseterm'); //request the JSON data and parse into the select element var l_id = ($("select[name='lease'] option:selected").attr('value')); l_url = "/api/get_leaseterm/"+l_id+"/"; $.ajax({ url: l_url, dataType:'JSON', success:function(data1){ //clear the current content of the select $select.empty(); $select.append('<option value="-1">Select term </option>'); //iterate over the data and append a select option $.each(data1, function(key, val){ $select.append('<option value="' + val.id + '">' + val + val.total + '</option>'); }) }, }); } How can I see my my calculated field from model in the drop down that was dynamically generated with Ajax? -
AppRegistryNotReady after installing django-ckeditor
I added the django-ckeditor to my app but I get the AppRegistryNotReady error. I tried to move the ckeditor app in the INSTALLED_APPS list without any change. Versions: Python==2.7.10 Django==1.8.9 django-ckeditor==5.3.0 The traceback Traceback (most recent call last): File "/Users/karim/dev//myop//manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/karim/Dev/cml/myop/myop/domain/service_filtering/__init__.py", line 1, in <module> from myop.domain.service_filtering.service_filter import ServiceFilter File "/Users/karim/Dev/cml/myop/myop/domain/service_filtering/service_filter.py", line 10, in <module> from myop.domain.buyer.models import BuyerRole File "/Users/karim/Dev/cml/myop/myop/domain/buyer/models.py", line 11, in <module> from myop.domain.core.models import Organisation, OrganisationAssociation File "/Users/karim/Dev/cml/myop/myop/domain/core/models/__init__.py", line 3, in <module> from .organisation import * File "/Users/karim/Dev/cml/myop/myop/domain/core/models/organisation.py", line 6, in <module> from ckeditor.fields import RichTextField File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/fields.py", line 6, in <module> from .widgets import CKEditorWidget File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/widgets.py", line 54, in <module> class CKEditorWidget(forms.Textarea): File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/widgets.py", line 59, in CKEditorWidget class Media: File "/Users/karim/Envs/cml/lib/python2.7/site-packages/ckeditor/widgets.py", line 68, in Media static('ckeditor/ckeditor/'), File "/Users/karim/Envs/cml/lib/python2.7/site-packages/js_asset/js.py", line 14, in static if apps.is_installed('django.contrib.staticfiles'): File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/registry.py", line 231, in is_installed self.check_apps_ready() File "/Users/karim/Envs/cml/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded … -
Redirect page in reactjs and django
I have a question that, i am stucked to redirect my page from signup to login. I have added allauth,rest_auth for token authentication in app and in reactjs i have added one form.js file. I have added views in views.py for get and save data from database. Now my rest-auth/login url works fine. But whenever i hit only login/ url which is calling our django view and form.js that is also works fine separately. Now i want to integrate this both so that at the time of signup i can create token for User. And also redirect from signup to login after user signup. What and Where i need to add these much things to get successful app? -
Django Translation not working and showing trans tags
I have a template I have created to add my project and I am using Django's translation module. I works fine with my already existing pages but on this one the translations are not rendered and instead it shows all the raw tags. I've compiled messages etc and still nothing. How do I fix this? I've looked at the following questions but no dice: django - how to make translation work? django internationalization and translations issue How to setup up Django translation in the correct way? http://askbot.org/en/question/8948/weve-edited-djangopo-files-but-translations-do-not-work-why/ See picture: html: {% load static %} {% load staticfiles %} {% load i18n %} {% block bonos %} <div class="container" > <div id='titleb' class="container"> <h2 style= "color:black; align=center">MILINGUAL BONO</h2> </div> <div id='titleb' class="container"> <h1 style= "color:black; align=center">MILINGUAL BONO</h1> </div> <div> <p>{% trans 'The Milingual Bono offers you more classes for much lesser. It saves you the hasslse of pasying each time you book a class, at the same time offering you the flexibilty of attending any Milingual class or event, anytime you want. Pick the 3 class bono if you would like to give it a try firt or book the <b>season bono</b> for unlimited access for 3 months.' %} </p> </div> … -
Parse date from json in Django
I try to parse date field inside JSON object : { "year": 1, "name": "marko", "date": "2015-10-1 3:00 PM GMT+1:00" } I try to something like: db_object.date = datetime.datetime.strptime(dictionary.get('date'), '%Y-%m-%d %I:%M ') but I get error... I know that %d is should be a zero based like: 01 but I get 1 in JSON. -
Celery task will not execute
I've followed the instruction process to installing and setting up celery, now I'm trying to execute my task. My project tree looks like this: bin app ----- | -------app -------- | --------celery.py --------tasks.py --------views.py -------manage.py -------templates include lib Here's my code: settings.py CELERY_BROKER_URL = 'amqp://localhost' #not exactly sure what this does celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py from celery import shared_task @shared_task def print_this(): print('ONE MINUTE') app.views add_question.delay() So my celery function doesn't work, it doesn't execute the print statement. What I want to do is execute the function every minute. Any idea what the problem is? -
Use Kinect on web app
I want to create a web app that display my motion using my Kinect. Question Is there a possible programming language like PHP, Python(Django), .Net or JSP to deal with Kinect on browser?