Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically modify database request in Django?
I've got a problem with my code. I need to get an instance of a model that looks like this: class Example(models.Model): # ... foo = models.JSONField(default={}) depending on the user's input. For example: Example.objects.filter(foo__userinput = bar) How can I manage to don't make JSON field hardcoded? -
How to apply migration to specific database in Django 1.7
How do you run a migration on a specific database in Django 1.7? I'm trying to migrate a Django 1.6 project to 1.7, but Django's new built-in migrations appear to be missing a lot of the features in the old South app. I have multiple databases, all of which I had been managing with South, but Django 1.7's new migration mechanism doesn't appear to support multiple databases. Its migrate command still accepts a --database parameter, but regardless of this value, it always runs migrations on the default database, making it impossible to manage schema in any other databases. Is this a known bug in Django 1.7? How do you run a migrate on a non-default database? -
Trying to make Google Maps show other locations using my location
I'm pretty new this Google Maps stuff. So far, my code successfully locates where I'm at in the world (pretty cool!). But now, I want to see what's near me using my location, restaurants for example. How would I go about doing this? Are there any links out there that can guide and point me in the right direction to make this idea come to fruition? I've looked around but can't find anything concrete. I've included the files I'm using. I'm also using Django to make the website. Here's map.html: <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="../../static/personal/css/map.css"> </head> <script src="../../static/personal/js/dMap.js"></script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCsz_aTtOb3STNIgh2BVkZrqpQHKT24ICY&callback=initMap"></script> <body> <div id="map"></div> </body> </html> Here's map.css: #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } Here's DMap.js: var map, infoWindow; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 6 }); infoWindow = new google.maps.InfoWindow; // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; infoWindow.setPosition(pos); infoWindow.setContent('Location found.'); infoWindow.open(map); map.setCenter(pos); }, function() { handleLocationError(true, infoWindow, map.getCenter()); }); } else { // Browser doesn't support Geolocation handleLocationError(false, infoWindow, map.getCenter()); … -
Django Rest Framework URL Mapping for multiple apps
I have a django-rest project called main and under it I created an app called users. So, my project has the files main/main/urls.py and main/users/urls.py In users/urls.py I have from django.conf.urls import url, include from rest_framework import routers from users import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) and in the main/main/urls.py I have from django.conf.urls import url from django.contrib import admin from users import urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^users/', users.urls), ] However, I keep getting the error NameError: name 'users' is not defined. What is the correct way to set up urls when I have multiple apps? I like to have a urls.py file for each app that is independent of the project. And in the root urls.py to include routing to different apps. -
I am trying to create a popover that stays open by ID
I found this result (How can I keep bootstrap popover alive while the popover is being hovered?) that works for one of my popovers, but I have multiple popover events targeted by ID and am wondering how I can apply this either to all of them or to each one. Here is an example of some of the code snippets that I am using. here is the html: <label class="checkbox"> <input type="checkbox" value="" />Body of Delusion<a data-bodyofdelusion="{% static 'pathfinder/html/sleepingGoddess/bodyOfDelusion.html' %}" data-toggle="popover" id="bodyOfDelusion">&#9660;</a> </label> <label class="checkbox"> <input type="checkbox" value="" />Call the Soul's Blade<a data-callthesoulsblade="{% static 'pathfinder/html/sleepingGoddess/callTheSoulsBlade.html' %}" data-toggle="popover" id="callTheSoulsBlade">&#9660;</a> </label> Here is the javascript: function loadContent(callTheSoulsBlade) { return $('<div>').load(callTheSoulsBlade, function (html) { parser = new DOMParser(); doc = parser.parseFromString(html, "text/html"); return doc.querySelector('h4').outerHTML + doc.querySelector('body').outerHTML; }) }; $(document).ready(function () { $("#callTheSoulsBlade").popover({ trigger: "hover focus", container: 'body', html: true, content: function () { return loadContent($(this).data('callthesoulsblade')) } }); }); function loadContent(bodyOfDelusion) { return $('<div>').load(bodyOfDelusion, function (html) { parser = new DOMParser(); doc = parser.parseFromString(html, "text/html"); return doc.querySelector('h4').outerHTML + doc.querySelector('body').outerHTML; }) }; $(document).ready(function () { $("#bodyOfDelusion").popover({ trigger: 'manual', container: 'body', html: true, animation: false, content: function () { return loadContent($(this).data('bodyofdelusion')) } }).on("mouseenter", function () { // This is the section from the link i provided. … -
Navigation Bar in html
I started my django project a week ago and currently trying to build a navigation bar. The source code is: {% load static %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" > <link rel = stylesheet type = "text/css" href="{% static 'music/style.css' %}" /> <nav class="navbar navbar-default"> <div class="container-fluid"> <!--LOGO--> <div class = "navbar-header"> <a class="navbar-brand" href="{%url 'music:index'%}">Pleer...</a> </div> </div> </nav> {% if all_albums %} <h3 class="text-muted">&nbsp;&nbsp;&nbsp;Albums</h3> <ul> {% for album in all_albums %} <li class="text-primary"><a href="{%url 'music:detail' album.id %}"><b class="text-danger">{{album.album_title}}</b></a></li> {% endfor %} </ul> {% else %} <h2>NO ALBUM FOUND</h2> {% endif %} but the result is only a simple link with no nav bar. Please help me in it. -
How can you host Django REST API on a home server (possibly on an Android phone)?
I would like to go to a job interview and show some portfolio with REST API that doesnt cost money to mantain, I dont want to use free trials on AWS and such either. I want something like PAW server that does python code, also i have no idea about what ports to open, how to open them and how to keep them secure -
For loop for ManytoMany Field Type
How should I create a for loop in my template so that I can show a ManyToMany relationship? Given that: in models.py I have class Cycle(models.Model): cycle_name = models.CharField(max_length=150) cycle_description = models.CharField(max_length=250) def __str__(self): return self.cycle_name + " -- " + self.cycle_description class Program(models.Model): program_name = models.CharField(max_length=50) program_description = models.CharField(max_length=250) cycles = models.ManyToManyField(Cycle) is_favourite = models.BooleanField(default="False") def get_absolute_url(self): return reverse('programs:program', kwargs={'pk': self.pk}) def __str__(self): return self.program_name in views.py class AllProgramsView (generic.ListView): template_name = 'programs/index.html' context_object_name = 'programs_list' def get_queryset(self): return Program.objects.all() class ProgramDetailView (generic.DetailView): model = Program template_name = 'programs/program.html' in urls.py #list of all programs url(r'^$', views.AllProgramsView.as_view(), name='index'), #single program page url(r'^(?P<pk>[0-9]+)/$', views.ProgramDetailView.as_view(), name='program'), In the single program page I need to list all the cycles that are contained in that specific program. I've been trying so many different things but none seems to be right. Here's my current take for the template, which however does not work: program.html <div class="bg-white"> <div class="container text-center text-muted"> <div class="row"> {% if cycle %} {% for cycle in program.cycles.all() %} <div class="col-sm-4 py-4"> <div class="card"> <p><h5>{{ cycle.cycle_name }}</h5></p> <p class="card-text">{{ cycle.cycle_description }}</p> <a href="" class="btn btn-secondary">Modify it</a> </div> </div> {% endfor %} {% else %} <div class="col-sm-12"> <p>No cycles found</p> </div> {% … -
can somone please try and help me with my holiday homework as i am struggeling [on hold]
Scenario : A Population Model You have been asked to create a simple population model to investigate how a greenfly population changes. Greenflies are a common insect that are considered to be a pest by gardeners because they damage roses and other garden plants. The Population Model rules To create a population model, the following rules must be followed. 1.At any one time there are three types of individual in the population: •Seniles – old greenfly that do not reproduce •Adults – greenfly that are reproducing •Juveniles – greenfly that are too young to reproduce. 2.The model lasts for a set number of new generations. At the end of each generation: •all surviving senile greenfly remain as seniles •all surviving adult greenfly change from adults to seniles •all surviving juvenile greenfly change from juveniles to adults. 3.Each type of individual has a survival rate. The survival rate is used to calculate the number of individuals that survive at the end of each generation. This number can be a value between 0 and 1. •A survival rate of 0 means no individuals of that type survive at the end of the generation. •A survival rate of 1 means all the individuals … -
Created Object in Python Shell, not recognized when queried
Currently creating a Django site for some work I'm doing. Here are the relevant code blocks: portal/device_categories/models.py from django.db import models # Create your models here. class Type(models.Model): device_category = models.CharField(max_length=20) def __str__(self): return self.device_category class Device(models.Model): category = models.ForeignKey(Type, on_delete=models.CASCADE) tms_code = models.CharField(max_length=5) device_name = models.CharField(max_length=30) device_count = models.CharField(max_length=3) def __str__(self): return "Device:" + self.device_name portal/device_categories/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<device_type>[A-Za-z]+)/$', views.deviceList, name='deviceList'), ] portal/device_categories/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Type, Device from django.template import loader # Create your views here. def index(request): return HttpResponse("This is the Device Categories Page") def deviceList(request, device_type): all_devices = Device.objects.get(category__device_category=device_type) template = loader.get_template('device_categories/index.html') context = { 'all_devices': all_devices, } return render(request, template, context) I have created numerous Device Objects using the: python manage.py shell methodology, some example categories are: fans, switches, modules. All the categories have also been set up as their own Type Class. Now I have 5 objects that I assigned a category of fans, but when I try to go to url: 127.0.0.1:8000/device_categories/fans/ I am getting error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/device_categories/fans/ Django Version: 1.11.4 Python Version: 3.6.0 Installed Applications: ['network_resources.apps.NetworkResourcesConfig', 'device_categories.apps.DeviceCategoriesConfig', … -
404 not fount deploying django with apache on digitalocean
i followed this tutorial : https://github.com/codingforentrepreneurs/Guides/blob/master/all/Debian_Install_Django_Apache2.md after this when i try to open my ip in web browser i got apache default page and when i navigate to /admin i got 404 not fountenter image description here -
Display CSV Contents in a Table using Views/Template
I am creating a site where users can upload a csv file, and am currently working on a page where users can view the contents of the file without downloading it. To do this I am reading the csv in views like so: def source_details(request, source_id): context_dict = {} # Get a specific object data_source = Source.objects.get(id=source_id) context_dict['data_source'] = data_source # Open the csv and print it to terminal with open(MEDIA_ROOT+data_source.sample, newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print(', '.join(row)) return render(request, 'data/source-details.html', context_dict) As you can see so far I have no trouble opening the uploaded csv file and printing it to the terminal, however I would like to display it in the browser as a table. Any ideas on how I can accomplish this? Thanks. -
TypeError: context must be a dict rather than Context
I'm trying to build a search engine into a django blog application and when I ran the command: >>> manage.py build_solr_schema I got this error: Traceback (most recent call last): File "C:\Users\KOLAPO\Google Drive\Python\Websites\mysite\manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\haystack\management\commands\build_solr_schema.py", line 29, in handle schema_xml = self.build_template(using=using) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\haystack\management\commands\build_solr_schema.py", line 57, in build_template return t.render(c) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\django\template\backends\django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\Users\KOLAPO\Anaconda3\lib\site-packages\django\template\context.py", line 287, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than Context. What's wrong? Note: I'm using Solr and Django-haystack for the search engine -
Gupshup Post - Empty Body
I'm building a simple bot that makes an http post call passing in JSON objects. The server responds back with the error - {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}: I dont think the server side is the issue; I've tried the request using httpie. The code in Gupshup var contextParam = { "botname": event.botname, "channel": event.channel, "sender": event.sender, "message":event.message }; var url = "https://abcserver.com/sm/postData"; var param = JSON.stringify(contextParam); var header = {"Content-Type": "application/json"}; context.simplehttp.makePost(url, param, header) The corresponding call from httpie http POST https://abcserver.com/sm/postData botname=MrBot channel=Skype sender=MrSender message=Hi At the server side : logger.debug("Request body : " + str(request.body)) puts - "Request body : b'" in the log file. PS: I'm using Django, Django Rest Framework -
DJANGO backend.authenticate(*args, **credentials) returning none
I have a weird case: I have a custom user model, connected to a sign up form, I do set_password(password) before saving it to the DB, and it does hash with argon2, and saves into the DB correctly. I checked that. The check_password(password) works just fine with verifying the username and password. BUT auth.authenticate(username=username, password=password) returns none. When debugging with Pycharm, I see that the username and password are getting passed correctly, but it's failing at this point: backend.authenticate(*args, **credentials) bare in mind, that I first get the user from the database to check if present, so the problem is with the password I'm guessing, but can't figure out why. In addition, login(request, user) is not working neither. No exception no nothing, they both just return none. Can anyone, for the love of coding help me? Here's the code: the form: class SignUpForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs['placeholder'] = 'first name' self.fields['username'].widget.attrs['placeholder'] = 'username' self.fields['email'].widget.attrs['placeholder'] = 'email' password = forms.CharField(widget=forms.PasswordInput(attrs={ 'placeholder': 'password' })) class Meta: # points the form to the model to use model = MyUser fields = [ 'first_name', 'username', 'email', ] def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user … -
Django model inheritance for closely related objects
I'm not sure about the "proper" way to define the relationship between a two closely related, hierarchy-based objects. I'm developing a kind of forum-like framework in Django. My initial idea was that, since a Thread is basically a "special" kind of Post, I should just create a fully-featured Post model, and then have a Thread model inherit from it, extended with any fields a Thread might need. Like so: class Post(models.Model): forum = models.ForeignKey(Forum) title = models.CharField(max_length=50, default="") text = models.CharField(max_length=2000, default="") created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User) class Thread(Post): thread_views = models.IntegerField() reply_count = models.IntegerField() (...) I also thought about making a single "Post" model with a "isThread" boolean field, but something didn't feel right about it. What would be the "proper" way to do this, performance-wise and good-practices-wise? -
Django REST Framework: Flatten nested JSON to many objects
I have this child model with parent field in it, and I'm getting a JSON from an API (which I can't control its format). models.py: class ChildModel(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() parent = models.CharField(max_length=100) API.json: { parent_name:'Homer', childs:[{ name:'Bart', age: 20 },{ name:'Lisa', age: 15 },{ name:'Maggie', age: 3 }] } I'm trying to write a serializer that will get this JSON and will create 3 different child objects. I manage to do this for one child: class ChildSerializer(serializers.Serializer): name = serializers.CharField() age = serializers.IntegerField() class ParentSerializer(serializers.ModelSerializer): parent_name = serializers.CharField() childs = ChildSerializer(source='*') class Meta: model = ChildModel fields = ('parent_name', 'childs') But when there are more than one child for a parent, I don't know how to save multiple children. I tried to change it like this: child = ChildSerializer(source='*', many=True) But the validated data looks like this: OrderedDict([(u'parent_name', u'Homer'), (u'name', u'age')]) Any suggestions how to make it possible? -
boto3 site-packages S3Response syntax err on collectstatic
the django-storages docs recommend using boto3 for managing static file storage with S3. expected this config to work but it's err'ing out requirements.txt boto3==1.4.6 botocore==1.6.3 django-storages==1.1.4 prod.py [settings] from .common import * from storages.backends.s3boto import S3BotoStorage ... DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = ENV_STR('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = ENV_STR('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = ENV_STR('AWS_STORAGE_BUCKET_NAME') S3_URL = 'http://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME STATIC_URL = S3_URL MEDIA_URL = 'http://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME ADMIN_MEDIA_PREFIX = STATIC_URL + '/admin/' AWS_S3_ENCRYPTION = True AWS_IS_GZIPPED = True but runing tests on manage.py collectstatic --noinput fail with a syntax err from storages package in storages/backends/s3boto.py: Traceback (most recent call last): File "manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/virtualenvs/venv-3.5.3/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/ubuntu/virtualenvs/venv-3.5.3/lib/python3.5/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/home/ubuntu/virtualenvs/venv-3.5.3/lib/python3.5/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/home/ubuntu/virtualenvs/venv-3.5.3/lib/python3.5/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/ubuntu/virtualenvs/venv-3.5.3/lib/python3.5/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/circleci/python/3.5.3/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/ubuntu/brightest-list/project/settings/prod.py", line 7, … -
Error: Request failed with status code 400. missing headers? error in backend?
I'm sending a POST request using axios to my localhost(this case, it's 10.0.0.2:8000) in React Native (android simulator) and I'm getting 400 error from Django RESTful Framework Backend. This is my action creator export const doAuthLogin = ({ username, password }) => dispatch => { axios.post(`${ROOT_URL}/rest-auth/login/`, { username, password }).then(response => { console.log(response); // Save Token post is Already await. AsyncStorage.setItem('auth_token', response.token); dispatch({ type: AUTH_LOGIN_SUCCESS, payload: response.token }); }) .catch(response => { console.log(response); dispatch({ type: AUTH_LOGIN_FAIL, payload: response.non_field_errors }); }); }; This is error message from Remote Debugger JS. It's just a console.log(response) from catch from axios.post. Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:18) at XMLHttpRequest.handleLoad (xhr.js:77) at XMLHttpRequest.dispatchEvent (event-target.js:172) at XMLHttpRequest.setReadyState (XMLHttpRequest.js:538) at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:381) at XMLHttpRequest.js:485 at RCTDeviceEventEmitter.emit (EventEmitter.js:181) at MessageQueue.__callFunction (MessageQueue.js:260) at MessageQueue.js:101 Error message in console, [17/Aug/2017 14:14:10] "POST /rest-auth/login/ HTTP/1.1" 400 40 And this is a part of settings.py, MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'profiles', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.twitter', 'django.contrib.sites', ] SITE_ID = 1 CORS_ORIGIN_WHITELIST = ( '10.0.2.2', 'localhost' ) I'm thinking I might have an error … -
django not returning any value for .id or .pk
I am just following one of the Django tutorials verbatim and have encountered a problem with queries of x.id or .pk not returning any value at all. This is across all rows in that table, though all other data is working. An example below is taken from my python shell. c = Album(artist="Stone Roses", album_title="The Stone Roses", genre="Indie", album_logo="http://www.classicrockreview.com/Images/1989/AlbumCovers/1989_StoneRos es.jpg") >>> c <Album: Album object> >>> c.id >>> c.artist 'Stone Roses' >>> c.pk >>> I was led to believe that .id is automatically taken care of by django? -
Django model listing
Iam working on a Django project with models.py as this.. need to have the next class Insurance listed in the browser How do i do class Patient(models.Model): patientID = models.CharField(max_length=20) firstName =models.CharField(max_length=20) lastName = models.CharField(max_length=20) age = models.IntegerField(max_length=None) SSN = models.CharField(max_length=15) address = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.patientID+"-"+self.firstName+" "+self.lastName+"--"+str(self.age)+"---"+self.SSN+"---"+self.address class Insurance(models.Model): patient = models.ForeignKey(Patient) memberID = models.CharField(max_length=20) groupID = models.CharField(max_length=20) provider =models.CharField(max_length=20) coPay = models.CharField(max_length=20) secIns = models.CharField(max_length=20) def __str__(self): return self.memberID+"-"+self.groupID+" "+self.provider+"--"+\ self.coPay+"---"+self.secIns -
Getting chart.js to work with Django and Apache
I have the following setup. I've a simple index.html being served through apache. It looks like the following. <!DOCTYPE html> <html lang='en'> <meta http-equiv="content-type" content="text/html; charset=UTF8"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <canvas id="myChart"></canvas> <script language="JavaScript" src="/customcharts.js"> </script> </body> </html> All the above does is to try and place a line chart on the browser. It uses chart.js. To accomplish this the customcharts.js tries to connect to a locally running django server. The above html is being served through apache running on port 8080 while django runs on port 8090. the customcharts.js looks as follows function renderChart(data){ console.log(data) console.log(data.labels) defaultLabels = data.labels defaultData = data.defaultData var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: defaultLabels, datasets: [{ lineTension: 0, label: 'Activity Profile', data: defaultData, }] } }) } var endpoint = 'http://localhost:8090/polls/alice/' var defaultData = [] var defaultLabels = [] $.ajax({ url: endpoint, dataType: "JSONP", success: renderChart, method: 'GET' } ); Further, my django view is def json_response(func): """ A decorator thats takes a view response and turns it into json. If a callback is added through GET or POST the response is JSONP. """ def decorator(request, *args, **kwargs): objects = func(request, *args, … -
DJANGO_SETTINGS_MODULE No Module Named
I am trying to create a population script for my database, but I get a No module named error. Traceback: Traceback (most recent call last): File "populate_rango.py", line 8, in <module> django.setup() File "/home/ubuntu/virtenv/webstatic/lib/python3.5/site- packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/virtenv/webstatic/lib/python3.5/site- packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/home/ubuntu/virtenv/webstatic/lib/python3.5/site- packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'mysite' My path: ['/home/ubuntu/virtenv/webstatic/staticone/mysite', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat- x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/ubuntu/virtenv/webstatic/lib/python3.5/site-packages'] My settings.py file is under mysite populate_rango.py under mysite folder: import sys print (sys.path) import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','settings') import django django.setup() from mysite.rango.models import Category,Page If I try os.environ.setdefault('DJANGO_SETTINGS_MODULE','mysite.settings') I get the same error: No module named mysite, but mysite is on the path, so I am confused as to why it is not finding the settings file. -
Django rest framework, translate model with hvad-django.
I have model Product: class Product(TranslatableModel): name = models.CharField(max_length=255, unique=True) translations = TranslatedFields( description=models.TextField(), ) and in administration on product detail I have tabs with languages. For example tabs EN, CZ, each includes disctiption. So PUT request looks like: { 'product': '1', 'id': 1, 'name': 'Name', 'translations': { 'cz': {'desctiption': 'Description cz'}, 'en': {'desctiption': 'Description en'} } } I founded in django-hvad TranslationsMixin that allows me to do that request. in serializers I have: class ProductTranslationSerializer(serializers.ModelSerializer): class Meta: exclude = ['description'] class ProductSerializer(TranslationsMixin, serializers.ModelSerializer): class Meta: model = Product translations_serializer = ProductTranslationSerializer fields = ( 'name', 'description', ) Questin is how will looks ModelViewSet for this request? Can I choose language like 'language_code=en', filter that query and get something like: [ { product_id: 1 name: "name" descritpion: "descritpion" }, .... ] Thank you! -
Django: what is the difference between redirect to a view function and redirect to a url (from urls.py file)
Which is better/standard practice? return redirect('index') return redirect('/users/new') index is view function /users/new is urlpatterns from urls.py