Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DataTables Refresh Django Ajax Data on CRUD Operations
I have a Django project with an Analytic model. This model is a list of analytics. It has a ForeignKeyField and a ManyToMany Field. The end goal is to have the user go to a URL where they can view a list of Analytics in a DataTable, create a new analytic, edit analytics, and delete analytics. Using this tutorial: https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html, I accomplished all of these objectives in a regular Bootstrap HTML table (i.e. not in a DataTable). When I attempted to introduce a DataTable to the mix, I discovered that my DataTable was pulling from the HTML/DOM source, so it was not updating unless the page was refreshed. So I then realized that I need to either configure the DataTable to initially pull from HTML/DOM and then pull from AJAX, or I need to initially use Ajax as the source. It turns out, regular Django does not do a good job of serializing ManyToMany fields, so I opted to use DRF to serialize my Analytic model. This works to a degree: the JSON output looks decent, and the results show up in my DataTable. However, the data is still not updating when an Ajax call is made. In addition, DataTables … -
How to construct url suitable for django from html form action
I have django site which I can query with various combinations of parameters. I am trying to write a html form for selecting the various combinations like so : <form action="http://mydjangosite.com/summaryReports/" target="_blank"> <input type="radio" name="reportType" value="messageSummary" checked> messageSummary<br> <input type="radio" name="reportType" value="countSummary"> countSummary<br> <select name="period"> <option value="today">Today</option> <option value="yesterday">Yesterday</option> <option value="thisWeek">This Week</option> <option value="lastWeek">Last Week</option> <option value="thisMonth">This Month</option> <option value="lastMonth">Last Month</option> </select> <br> <input type="radio" name="reportFormat" value="html" checked> html<br> <input type="radio" name="reportFormat" value="pdf"> pdf<br> <input type="radio" name="reportFormat" value="csv"> csv<br> <input type="radio" name="reportFormat" value="email"> email<br> <input type="radio" name="reportFormat" value="debug"> debug<br> <input type="submit" value="Submit"> </form> When I press button the url generated is : mydjangosite.com/summaryReports/?reportType=messageSummary&period=today&reportFormat=html whereas what I require is : mydjangosite.com/summaryReports/messageSummary/today/html How to do it? Thanks in advance -
Difference between mongoengine and django-mongo-engine and pymongo
Can anyone explain me the difference between mongoengine and django-mongo-engine and pymongo. I am trying to connect to mongodb Database in Django2.0 and python3.6 -
Django oscar sandbox editing or django oscar documentaion
Is it okay to edit the existing django-oscar sandbox project as my project or is it better to follow the django-oscar documentation? -
Tango with Django 1.9 on Django 2.0 - "list indices must be integers or slices, not str"
I am, probably stupidly, attempting to go through Tango with Django 1.9 on newly released Django 2.0. I am up to chapter 6 and am getting the following error. The error pertains to my views.py file (below) with the lines, context_dict['pages'] = pages context_dict['category'] = category seemingly the culprits. Has the way in which variables are assigned to dictionaries changed in Django 2.0 or is this a Python issue? Can provide code from all other application files. Views.py from django.shortcuts import render from rango.models import Category, Page def index(request): category_list = Category.objects.order_by('-likes')[:5] context_dict = {'categories':category_list} return render(request, 'rango/index.html', context=context_dict) def about(request): return render(request, 'rango/about.html') def show_category(request, category_name_slug): context_dict = [] try: category = Category.objects.get(slug=category_name_slug) pages = Page.objects.filter(category=category) context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: context_dict['category'] = None context_dict['pages'] = None return render(request, 'rango/category.html', context_dict) Models.py from django.db import models from django.contrib import admin from django.template.defaultfilters import slugify # Create your models here. class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category,self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) title = models.CharField(max_length=128) url = models.URLField() views = … -
CSRF verification failed. Request aborted. Django 2.0
def order_view(request): if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): return HttpResponseRedirect('Order Submitted') else: form = OrderForm() return render_to_response('home/order.html', {'form': form}) order_view function in views.py <form class="form form-table" method="post"> {% csrf_token %} {{ form|crispy }} <input class="btn br-green" type="submit" value="Submit"/> </form> There is still a CSRF error in it. Have tried most of the solution but they are not working.Have tried adding RequestContext(request) as well. -
Use Django with MongoDB
I have a large mongo database with documents and i want to make Django website that is going to be a client to this mongo database but it can only filter (aggregate) and view information from database without any edit/update operations. I don't want to put other web site data (users' data, comments, other information) to mongo db. I'm new to django framework and i wonder if it is better to connect mongodb and django using, for example, mongoengine and use two databases (one for the web site data, and the second one for external documents in mongodb) or use pymongo inside django to fetch data from external db and somehow transform it to djungo models? -
Get variables from server(django) and use in javascript
I'm new in django. I want to use the variables return from my python code, to create a map of the input city.(realise the request and response between server and client) But it does work in showing the map. (I use {{Latitude}} in html and get the right number.) Here is my python code: def searchMap(request): latitude =40 longitude=50 return render(request,'WebPage1.html,{'Latitude':latitude,'Longitude':longitude}) And my HTML code is like : <!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } #floating-panel { position: absolute; top: 10px; left: 25%; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; text-align: center; font-family: 'Roboto','sans-serif'; line-height: 30px; padding-left: 10px; } </style> </head> <body> <div id="map"></div> <div id="floating-panel"> <form method="POST" action="/searchMap/"> {% csrf_token %} <input name="city" type="text"> <input type="submit" value="Geocode" onclick="myMap()"> </form> </div> <p>{{Latitude}}</p> <script> var lat={{Latitude}}; var lng={{Longitude}}; var map; function myMap() { map = new google.maps.Map(document.getElementById('map'), { center: { lat:lat, lng:lng }, zoom: 8 }); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key="API KEY"&callback=myMap"> </script> </body> </html> Thanks for kindly reply! -
Django autocomplete from json
I'm trying to add some autocomplete field in Django Admin (Django 2.0.1). I managed to get it to work (both with the autocomplete included in Django and with Select2) because in those cases I loaded the dropdown options from a ForeignKey field. Now I need to have autocomplete on a simple CharField but the choices need to be taken from a remote API that return a json response. I can decide how to structure the json response. Any way to do this? The returned json responde doesn't represent objects of model, just simple text options. -
Why django masks running time errors and discontinues to run remaining code?
Django won't report errors. 2 recent examples here: First, in console: In [23]: if 'a' in page: ...: print(1) TypeError: a bytes-like object is required, not 'str' Second, I forgot to define cate here gi = Info(dept, cate, title, link, pub_date) gi.save() ... In both cases, no error report when running my django code. and the code below was not run. -
Building a ScrumBoard to learn Django Part 2
I am currently learning Django via Youtube, Udemy, and PluralSight so that I can make programs for our non-profit foundation. I'm running into a slew of issues from the stuff I started with from PluralSight. I have encountered yet another problem: queryset = List.objects.all() NameError: name 'List' is not defined I do believe the issue is similar to the other problems, with either another import missing, or maybe this: How can I retrieve a list of field for all objects in Django? For which the solution was: User.objects.all().values_list('username', flat=True) I tried looking up import django, list as well as import django.generic.view, no dice. Im not exactly sure why the flat=True would be required, or if I would need to add a values_list to my code at all, or what a "tuple" is. Can anyone show me where the imports are for django, as well as any advice on a better way to learn the language. Books, online videos, anything that doesnt require me to fix another bug every step would be amazing. -
Django: lazy loading installed_apps
I'm upgrading a project which I'm working on to Django 1.11 from 1.9. It uses a custom register app which inherits from django-registration-redux package. The django-registation-redux package is not inside the installed_apps as adding it tries to install models and fails since the models are installed by the custom register already. Is it possible to prevent apps installing it's models? -
Make Django query with .extra
My aim is to create a query which calculate the absolute value of my field and calculate the average of them as well. I have read about it and I tarted to use the .extra possibility in Django but I couldn't achieve my goals. I attach my attempt ant the desired SQl query too. Thank you in advance. The desired result would be equeal the reult of this PosreSql query: SELECT time_stamp, AVG(ABS(ddt)) FROM tropo WHERE time_stamp BETWEEN '2018-01-16 8:00' AND '2018-01-17 8:00' GROUP BY time_stamp ORDER BY time_stamp My attempt is in Django: Table.objects.all().filter(time_stamp__range=(2018-01-16 8:00, 2018-01-17 8:00)) .extra(select={"ddt_abs": "abs(field)"}) .values('time_stamp') .annotate(avg_field=Avg('field')) How can I reach that my Djanogo query works? -
Django model - dynamically decide which table to user according to model field
I have a Django model, for the example, I will call it Book: class Book(Model): class Meta: db_table = 'book' i need dynamically to change 'db_table' according to book instance attribute for example: when id>100 choose 'book_new' table so for query: Book.objects.get(id=200) 'book_new' will be used. also when creating a new Book (for 'new' attribute): Book(name='ff', new=True).save() a new record is added to 'book_new' (and not 'book') NOTE: i dont want to create new class, i need to use the same class, but to use a Manager(?) or Router(?) in order to choose the right db. -
wkhtmltopdf get CalledProcessError under uwsgi environment
I get a CalledProcessError under uwsgi environment, while I can run it in django normal runserver-mode ,and can run this command directly in command line correctly. here is my environment: Environment: Request Method: GET Request URL: http://x/api/sheet/?order=1784285260 Django Version: 2.0.1 Python Version: 3.6.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wkhtmltopdf', 'rest_framework', 'django_crontab', 'backend', 'api', 'website'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/www/env/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/www/env/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 158. response = self.process_exception_by_middleware(e, request) File "/www/env/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 156. response = response.render() File "/www/env/local/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/views.py" in rendered_content 78. cmd_options=cmd_options File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/utils.py" in render_pdf_from_template 186. cmd_options=cmd_options) File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/utils.py" in convert_to_pdf 124. return wkhtmltopdf(pages=filename, **cmd_options) File "/www/env/local/lib/python3.6/site-packages/wkhtmltopdf/utils.py" in wkhtmltopdf 110. return check_output(ck_args, **ck_kwargs) File "/usr/lib/python3.6/subprocess.py" in check_output 336. **kwargs).stdout File "/usr/lib/python3.6/subprocess.py" in run 418. output=stdout, stderr=stderr) Exception Type: CalledProcessError at /api/sheet/ Exception Value: Command '['/usr/local/bin/wkhtmltopdf.sh', '--dpi', '300', '--encoding', 'utf-8', '--margin-left', '20', '--margin-top', '10', '--orientation', 'Landscape', '--page-size', 'A4', '--print-media-type', '--quiet', '--zoom', '0.88', '/tmp/wkhtmltopdf0fjtzvle.html', '-']' returned non-zero exit status 126. and my uwsgi configuration: [uwsgi] vhost = true plugin = python36 socket = /tmp/site.sock master = true enable-threads = true processes = 4 virtualenv = /www/env/ home … -
How to Save a blob in django and Ajax
I have a blob file that I want to save on the backend using Ajax but I keep getting a 404 error and I have no idea what is the issue. This code is in views.py @csrf_exempt def upload(request): if request.method == 'POST' and request.FILES['blob']: audio = request.FILES['blob'] fs = FileSystemStorage() filename = fs.save(audio.name, audio) file_url = fs.url(filename) return render(request, 'upload.html', {'file_url': file_url}) And this is my Ajax request $.post("/main/upload/", { filename: blob.value, }, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); console.log(blob); } Your help will be appreciated :) -
Trying to display a profile edit form for different user types in Django
So I have two account types: student and teacher. I have two forms which hold the information to be updated for each case. Now, student and teacher have different form fields. I want that a student or a teacher could be able to update their profiles, problem is that I need to display different forms for students and teachers. For teacher my view and form work properly, but for student, instead of the student edit form, the teacher form is displayed again.. I tried something but now I get an error like: local variable 'form' referenced before assignment Please have a look here: @login_required def profile_edit(request): user = request.user student = request.user.student teacher = request.user.teacher if user.email == teacher.email: if request.method != 'POST': form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') else: form = TeacherEditForm(instance=teacher) elif user.email == student.email: if request.method != 'POST': form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') else: form = StudentEditForm(instance=student) context = { "form": form, } return render(request, "registration/profile_edit.html", context) I used email field, because it is unique and is stored in both Student/Teacher and User models. -
Django Forms - dynamic choice field filtering
I am trying to dynamically filter which choices are displayed in a form. the form fields are generated from model. Currently all choices are being displayed without any filters applying. in the view I get the currents site_type then pass this to the form, to filter the subnets that also have the same site_type, or this is whats supposed to happen anyway. can anyone see why the filter would not be applying? forms.py class AutoSubnetForm(forms.Form): subnet_type_data = SubnetTypes.objects.all() def __init__(self, *args, **kwargs): self.site_type = kwargs.pop("site_type") # get site type if set and filter against it if self.site_type: self.subnet_type_data = SubnetTypes.objects.filter(related_sites=self.site_type) super(AutoSubnetForm, self).__init__(*args, **kwargs) # create list for types subnet_types = [] for stype in subnet_type_data: # add tuple for each type subnet_types.append((stype.id,stype.subnet_type)) subnets = forms.MultipleChoiceField( choices=subnet_types, widget = forms.CheckboxSelectMultiple( attrs = {'class': 'form-control'} ) ) views.py @login_required @user_passes_test(lambda u: u.has_perm('config.add_subnet')) def auto_gen_subnets(request, site_id): #generate_subnets(site_id) from config.models import SubnetTypes site_data = get_object_or_404(SiteData.objects.select_related('site_type'),pk=site_id) subnets = None if request.method == 'GET': form = AutoSubnetForm(site_type=site_data.site_type) else: # A POST request: Handle Form Upload form = AutoSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnets = form.cleaned_data['subnets'] return render(request, 'sites/generate_subnets.html', { 'data': subnets, 'form': form, … -
Django - NoReverseMatch - Select form
I have a select form that is supposed to take the user to different program pages. Urls.py url(r'^program_page/(?P<id>\d+)$', views.program_page, name = 'program_page') This is my form HTML <form action= "{% url 'project:program_page' id= *****THIS IS WHAT I NEED HELP WITH. I DO NOT KNOW WHAT GOES HERE FOR THE ROUTE*** %}" method='post'> {% csrf_token %} <br> <select id=options name="function_program"> <option>Choose From List</option> {% for function_program in function_programs %} <option value="{{function_program.program.id}}">{{function_program.program.title}}</option> {% endfor %} </select><br> <input type="hidden" name="id" value="{{function_program.program.id}}"> <input type="submit" value="Go To page"> </form><br> I think that what I need help with is with the action expression. <form action= "{% url 'project:program_page' id= %}" method='post'> I tried <form action= "{% url 'project:program_page' id=function_program.program.id %}" method='post'> amongst several other things but keep getting the reverse no match error. How do I pass the id from the selection to the form action? -
django-registration-redux confirmation email not working
I've been trying for hours to make my django application send confirmation emails after registering but so far have had no luck with various errors. Below is my settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')u#-6zt#-1s_-n_1=w%u8dke8-7$n9qkqagu08(--toc#y27+%' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # 'django.contrib.sites', 'lollipop', 'pinpop', 'sweet', 'registration' ] # If True, users can register REGISTRATION_OPEN = True # One-week activation window ACCOUNT_ACTIVATION_DAYS = 3 # If True, the user will be automatically logged in REGISTRATION_AUTO_LOGIN = True # Successful login arrival page LOGIN_REDIRECT_URL = '/index/' # Page not-logged in users are redirected to if trying to access stuff that @login_required LOGIN_URL = '/accounts/login/' # Host for email EMAIL_HOST = 'smtp.gmail.com' # Port for email EMAIL_PORT = 567 # Host user EMAIL_HOST_USER = 'xxxx@gmail.com' # … -
axios.post reactjs Django Restframework
I am posting login throw my django backend with axios.here is my structure in Login.js: class Login extends Component { constructor(props) { super(props); this.state = { username: '', email: '', password: '' } } handleClick(event) { var apiBaseUrl = "/api/login/"; axios.post(apiBaseUrl, { "username": this.state.username, "email": this.state.email, "password": this.state.password } ) .then(function (response) { console.log(response.status); console.log(response); if (response.status === 200) { console.log("Login successfull"); alert('Login Successfull'); } else if (response.status === 204) { console.log("Username password or email do not match"); alert("username password do not match") } else if (response.status === 400) { console.log('noo!!!!!') } else { console.log("Username does not exists"); alert("Username does not exist"); } }) .catch(function (error) { console.log(error); }); }; render() { return ( <div> <MuiThemeProvider> <div> <AppBar title="Login" /> <TextField hintText="Enter your Username" floatingLabelText="Username" onChange={(event, newValue) => this.setState({ username: newValue })} /> <br /> <TextField hintText="Enter your email" floatingLabelText="Email" onChange={(event, newValue) => this.setState({ email: newValue })} /> <br /> <TextField type="password" hintText="Enter your Password" floatingLabelText="Password" onChange={(event, newValue) => this.setState({ password: newValue })} /> <br /> <RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)} /> </div> </MuiThemeProvider> </div> ); } } const style = { margin: 15, }; export default Login; so the problem is if the username and email and … -
Django page refresh page on new postgres entry to provide realtime updates to user
I want to automatically refresh / reload the django webpage in the users webbrowser when a new entry is found in the database. Currently i use a meta refresh as a temporary solution. I have installed and am using pgpubsub. So i can get a notification when there is a new item in the database. But how can i trigger django to reload the website? import pgpubsub pubsub = pgpubsub.connect(host="localhost",database="somedb",user="somebody") pubsub.listen('pg_news'); for e in pubsub.events(): print(e.payload) any ideas are welcome -
Heroku and Django - relation does not exist
I have launched an app on Heroku running Django 2.0.1 with a Postgres resource provisioned. My Procfile, after a few iterations, looks like this: Procfile release: python manage.py migrate sites --noinput && python manage.py migrate --noinput web: gunicorn app.wsgi --log-file - When I deploy from GitHub (not from the command line... I haven't deployed from the command line before as it is critical to me that the GitHub deploy works) everything works fine. The migrations run like they should, and the logs confirm that there are no errors when migrating. In fact, there are no errors at all. When I launch the site (forcing it into DEBUG mode to see the errors) I get this error on the front page: ProgrammingError at / relation "posts_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "posts_post" INNER JOIN "u... A similar error exists when trying to load the admin site: ProgrammingError at /admin/login/ relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ I followed the advice in Django: relation "django_site" does not exist to migrate sites first, but that did nothing. Also, this issue on GitHub is related, but was not helpful. To clarify, the app is … -
How to build a xmpp server with Jingle protocol implementation for Audio streaming from an android device within my Python django project
I already have a django based server with exposes a REST API using which my Android app is communicating through POST requests. But now I am exploring a way to stream audio from the android device MIC to my server for further processing to be done on the server. So for this, after a bit of exploration I found about XMPP protocol and it's Jingle protocol extension, which has been used for Vo-IP before, for implementing a audio-streaming to the server. However I am unable to find any library with proper documentation or guide for implementing this XMPP-Jingle stack in my Python server. So I am here, what should I use to implement this? I found this question in SO: XMPP server for Python, which is 1. Dated, and 2. Seems to suggest from what i was able to gather, using some non-python server like 'ejabberd' or 'openfire' and somehow bridging with my server code for my implementation? I haven't worked with this kind of technology before, so if that indirect implementation is my only recourse, then how to do that? I would require documentation/guide for that. Ofcourse, I would highly prefer a way to directly implement this in Python … -
Building a ScrumBoard to learn Django
I am currently learning Django via Youtube, Udemy, and PluralSight so that I can make programs for our non-profit foundation. I'm running into a slew of issues from the stuff I started with from PluralSight. The current problem is I keep getting an error: path(r'^scrumboard/', include('scrumboard.urls')), NameError: name 'include' is not defined Directory: /djangular (the project folder) /djangular/djangular (where my scrumboard directory/manage.py sits) /djangular/djangular/djangular (where urls.py, the file throwing the error sits) The code: from django.contrib import admin from django.urls import path urlpatterns = [ path(r'^admin/', admin.sites.urls), path(r'^scrumboard/', include('scrumboard.urls')), ] So far I have followed the directions to the t, and ran into countless problems, I am assuming this is another one. It initially wanted me to use the word "url" instead of path, which caused failures immediately. Is this another one of those situations, and are there other resources I can use to learn django? This one isnt panning out for me so well, but I really do want to be able to write my own code, and I love the language and the features. Im just not a professional coder. I dont expect my work to be pretty, but I do want to get the job done. I …