Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call API from React
I am trying to get React to get the JSON from the Django Rest Framework API. The link is written like so http://127.0.0.1:8000/band/api/1/?format=json and the structure is as below: { id: 1, name: "Muse", date_added: "2017-04-17", image: "https://upload.wikimedia.org/wikipedia/commons/a/a3/Muse_melbourne28012010.jpg", bio: "Muse are an English rock band from Teignmouth, Devon, formed in 1994. The band consists of Matt Bellamy (lead vocals, guitar, piano, keyboards), Chris Wolstenholme (bass guitar, backing vocals, keyboards) and Dominic Howard (drums, percussion)." } My react is written like so: class ItemLister extends React.Component { constructor() { super(); this.state={items:[]}; } componentDidMount(){ fetch(`http://127.0.0.1:8000/band/api/1/?format=json`) .then(result=>result.json()) .then(items=>this.setState({items})) } render() { return( <ul> {this.state.items.length ? this.state.items.map(item=><li key={item.id}>{item.name}</li>) : <li>Loading...</li> } </ul> ) } } ReactDOM.render( <ItemLister />, document.getElementById('container') ); The HTML container div stays at loading..., the console shows no errors. I know its something to do with the JSON but cannot figure out what it is, any help appreciated! -
Django user registration and authentication to mutiple databases
I'm looking for a way to register and authenticate custom users accross mutiple databases using Django and postgreSQL. The application will be cross countries (still brainstorming). Regarding the different laws we need to store the users details inside their own country. For exemple, US users must have data stored in the US, Canadians users stored in Canada and Europeans users stored in Europe. The problem is that Django (1.11) doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. So I came up with 2 options at the moment but I can't see the perfect one. I'm asking if you would have a better solution. Option 1: using postgres_fdw (PostgreSQL foreign data wrapper) Manually creating localized (us, can, euro) databases to store users’ details https://www.postgresql.org/docs/9.6/static/postgres-fdw.html Then integrate Django with a legacy database Pros: Supports foreign database relationships Cons: Manual migration, manual integration, custom scripts. Option 2 : Skip Django referential integrity https://gist.github.com/gcko/de1383080e9f8fb7d208 Pros: Easier Django integration Cons: Risk of data corruption. I would avoid it!! Thanks Django: 1.11 PostgreSQL 9.6 Python 3 -
Universal Angular with Django Backend?
I'm working on a project with a Django backend (DRF API) and an Angular 2 front end. I'd like to use Universal Angular for my SEO implementation; it's being developed by the Angular team for use with Google's bots, so it looks like it'll be well maintained, well documented, and a stable option for long-term maintenance. It doesn't look like Universal Angular is set up to work with backends that aren't Node.js or ASP.NET, however. Does anyone know if there's a way around this? Or would it be better to just use a service like Prerender.io? -
How to annotate in Django w/DRF with Co
I have an note field, which has email ID, and multiple notes can exist with same email_id. But when I am coalesce I want to count the value only once. So lets say I have a note with email_id=1 and status of "sent", and another with email_id=1 and status="sent", I want the total_sent to be 1, not 2. queryset = EmailTemplate.objects.annotate( total_sent=Coalesce( Sum( Case( When( Q(note__email_status="Sent") | Q(note__email_status="Opened") | Q(note__email_status="Clicked"), then=1), default=0, output_field=IntegerField() ) ), Value(0), ), total_opened=Coalesce( Sum( Case( When( Q(note__email_status="Opened") | Q(note__email_status="Clicked"), then=1), default=0, output_field=IntegerField() ) ), Value(0), ), total_clicked=Coalesce( Sum( Case( When(note__email_status='Clicked', then=1), default=0, output_field=IntegerField() ) ), Value(0), ) ) -
How can one setup Flask/Django apps on a server running cpanel/whm on my VPS?
I purchase web hosting and have setup cpanel/whm on a VPS server. This helps certain clients easily manage their sites/domains. Currently, I have Centos 7 for the OS. Is it possible to use a reverse proxy with Apache or is that unique to NGINX? Can I setup sub-domains to host Python web apps like django or flask without causing problems with the existing domains/accounts on the server - which are managed by cpanel? How would I do that - the easiest route would be to keep apache with cpanel but manually create sites that correspond to the sub-domain such as django.example.com Would it be easier to use NGINX or is Apache able to do this? Lastly, one thing that has left me uncertain was how to manage Docker containerized apps in production. The same issues, I mentioned above for just publishing Python apps without considering Docker, are relevant in the scenario of using Docker. I wonder if it is possible to use Docker on a VPS server that I already am paying to have without having to also use Digital Ocean, AWS, Azure cloud, or similar PAAS solutions - do I have the correct acronym, for what I am discussing? … -
Detect any changes made to Django models
I have found myself in a situation where for several models say X, Y and Z, I would like to know when any change happens on them i.e. any create, update, delete. I have scoured the internet but all I get is libs on instance audit history. Is there any way to accomplish this inbuilt in django or even a custom solution/lib would be highly appreciated. -
CSRF token missing or incorrect AJAX / DJANGO
Can someone help me with this problem? I have list of tasks in my page. Every task has there own form where users can send comments. When I add new task AJAX update list of comments and then I try to send comment by form and it raise error : “CSRF token missing or incorrect”. In any other situation forms work well. I have {% csrf_token %} in my form. It seems like I need send CSRF in AJAX. Where I did mistake? Why it didnt work? JS: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); // TASK $(function () { var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal").modal("show"); }, success: function (data) { $("#modal .modal-content").html(data.html_task_form); } }); }; var saveForm = function () { … -
Django - sitemap file from google. How to serve this up?
So here is the problem. I have never used Django before but our company took over SEO for a site that was built with Django. I have sftp access to the site and cms login information. (we are not hosting this) I have a few questions: Do i need to install any software locally on my machine for any reason to modify the website? What I am talking about is a CLI or anything like that? (of course I have my IDE of choice - phpstorm) I am brand new to Django (and python) - this is my exposure and from my understanding there is typically a build process with Django - such as a dev staging and production site. I of course do not have a build process so I am working off of production. Is this even feasible with Django? The pressing issue is our SEO team wants me to replace the sitemap with one generated from the google search console. I have read through the Django documentation and I learned that the sitemaps are being generated through a class of some sort. See: # urls.py from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap # Sitemap config pages_sitemap = {'queryset': Page.objects.filter(status='active'), … -
POST method is not executing to fill form which saves values to database
I am a newbie to django framework and want to take values and save it to database. for this i used post method but when i check it is executing else part. I went through previous question on it but still found unsatisfying in my case. Code is as follow: #views.py from django.shortcuts import render, render_to_response from django.http import HttpResponse, HttpResponseRedirect from .models import student_info, history from django.shortcuts import get_object_or_404, render from .forms import info def index(request): return HttpResponse("Hello, world") def info(request): if request.method == "POST": the_form=info(request.POST or None) context={ "form": the_form } if form.is_valid(): form.save() else: return HttpResponse("It sucks") return render_to_response(request, 'info.html', context) #models.py from __future__ import unicode_literals from django.db import models # Create your models here. class student_info(models.Model): name=models.CharField(max_length=40, help_text="Enter Name") reg_no=models.IntegerField(help_text='Enter your reg_no', primary_key=True) email=models.EmailField(help_text='Enter email') def __str__(self): return self.name class history(models.Model): Reg_no=models.ForeignKey('student_info', on_delete=models.CASCADE) date=models.DateTimeField(auto_now=True) def was_published_recently(self): return self.date >= timezone.now() - datetime.timedelta(days=1) #forms.py from django import forms from .models import student_info, history class info(forms.ModelForm): name= forms.CharField(label= 'Enter name') reg_no= forms.CharField(label= 'Enter registration no.') email= forms.EmailField(label= 'Enter email') class Meta: model= student_info fields= ['name', 'reg_no', 'email',] #info.html <h1>Enter the details</h1> <form action="{% url 'auto:info' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Go" /> </form> -
Django - BDD test can not find element by name
It seems like it can not find the element "firstname" which i have defined in forms. Something i'm missing or have misunderstood? Still a newbie and really appreciate your help, folks! Creating test database for alias 'default'... Feature: Add member Scenario Outline: Member succesfully added -- @1.1 Members Given a form ... passed in 1.913s When i fill in "foo","bar","fb@gmail.com","female","1990-02-01","2017-01-01","2017-06-03" ... failed in 1.867s Traceback (most recent call last): File "C:\...\lib\site-packages\behave\model.py", line 1456, in run match.run(runner.context) File "C:\...\lib\site-packages\behave\model.py", line 1903, in run self.func(context, *args, **kwargs) File "features\steps\step_add_member.py", line 39, in step_impl br.find_element_by_name('firstname').send_keys('foo') File "C:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 378, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "C:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 784, in find_element 'value': value})['value'] File "C:\...\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 249, in execute self.error_handler.check_response(response) File "C:\...\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: ***Message: {"errorMessage":"Unable to find element with name 'firstname'"***,"request":{"headers":{"Accept":"application/json","Accept- Encoding":"identity","Connection":"close","Content-Length":"92","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:40945","User-Agent":"Python http auth"},"httpVersio n":"1.1","method":"POST","post":"{\"using\": \"name\", \"value\": \"firstname\", \"sessionId\": \"341886b0-2447-11e7-b206-cf7b056db255\"}","url":"/element","urlParsed":{"anchor":"", "query":"","file":"element","directory":"/","path":"/element", "relative":"/element","port":"","host":"", "password":"","user":"","userInfo":"","authority":"","protocol":"","source": "/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/341886b0-2447-11e7-b206-cf7b056db255/element"}} Screenshot: available via screen forms.py CHOICES = [('Female', 'Female'), ('Male', 'Male')] class RegForm(forms.ModelForm): first_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'firstname', 'id': 'firstname'}), max_length=30, required=True) last_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'name': 'lastname', 'id': 'lastname'}), max_length=30, required=True) email = forms.CharField( widget=forms.EmailInput(attrs={'class': 'form-control', 'name': 'email', 'id': 'email'}), required=True, max_length=75) reg_date = forms.DateField(widget=DateWidget(usel10n=True, bootstrap_version=3, attrs={'name': 'reg_date'})) … -
Deploying and viewing file contents
I've done (succefull) this tutorial: https://cloud.google.com/python/django/flexible-environment I have several questions: Can i view/edit files in browser? Under Tools->Development->Source code is nothing Suggested way to deploy is: gcloud app deploy but it always does full import. Is there a way to deploy delta? My local source code is not under GIT(was not mentoned in tutorial) -
Django form User is 'not-null' even though it's manually set
For ease of use, one of the fields in my form can have multiple foos, but eachfoo should/will create it's own record in the database. I have a ModelForm (MyForm) that captures the fields that are repeated for each instance of foo. Inside my views.py I copy MyForm for each instance of foo. All that is working, except for the bit where the logged in user is set as the submitter of the form. The following error is thrown: null value in column "submitter_id" violates not-null constraint. models.py class MyModel(models.Model): foo_bar = models.CharField(max_length=10) foo_baz = models.CharField(max_length=10) submitter = models.ForeignKey(User) forms.py class MyForm(forms.ModelForm): class Meta: Model = MyModel exclude = ['foo_bar','foo_baz','submitter'] views.py Note: obj is a dictionary of however many foos were entered into the form my_form = MyForm(request.POST) if my_form.is_valid(): for k,v in obj: copy = MyForm(request.post) copy.save(commit=False) copy.foo_bar = k copy.foo_baz = v copy.submitter = request.user # I have inspected this, and request.user is an instance of the User model copy.save() # <-- here is where I get the error above -
Django email attach method is not taking parameters right
My problem is that while sending email in django i want to attach a file. If i do it that way: email.attach("Random_name", uploaded_file.read()) it works and my email sends. But if instead of string "Random name" i put a variable there representing uploaded file name as: uploaded_file = request.FILES['stl_file'] uploaded_file_name = request.FILES['stl_file'].name email.attach(uploaded_file_name, uploaded_file.read()) the whole things blows up and i get a ValueError "need more than 1 value to unpack" for email.send() method. I have checked both variables upload_file and upload_file_name(by use of pdb tool) and both of them get the right value before calling attach method. Here is my view where i am trying to send the mail: def print(request): if request.method == 'POST': form = PrintForm(data=request.POST, request = request) if form.is_valid(): contact_name = request.POST.get('contact_name', '') contact_email = request.POST.get('contact_email', '') form_content = request.POST.get('content', '') supervisor = form.cleaned_data['supervisor'] template = get_template('threeD/email/contact_template_for_printing.txt') context = Context({ 'contact_name': contact_name, 'supervisor': supervisor, 'contact_email': contact_email, 'form_content': form_content, }) content = template.render(context) subject = "New message" email = EmailMessage( subject, content, contact_email, [supervisor], headers={'Reply-To': contact_email} ) if request.FILES: uploaded_file = request.FILES['stl_file'] uploaded_file_name = request.FILES['stl_file'].name email.attach(uploaded_file_name, uploaded_file.read()) email.send() messages.success(request, "Thank you for your message.") return redirect('/index/print/') else: form = PrintForm(request=request) context_dict = {} context_dict['printers'] = Printer.objects.all() … -
Django DataTables.net table can't display date data with NULL values
I have a table in my Django project which has some dates and other fields. Dates have displayed fine until now, but when adding a new column an error is thrown and the data does not display. The data type in SQL (date, null) and models.py (models.DateField(null=True)) is the same for existing date columns which work fine, and the new one which will not display. The migration process is also the same. NULL values should be allowed, but from what I can tell the only difference is that a high proportion of records in the new column (about 70%) are NULL, whereas there were no NULL values in the prior date columns. The error is the generic DataTables.net error saying that the parameter is unknown (anytime something goes wrong with a field, I get that same error regardless of the root cause). Here's the Python code: $(document).ready( function () { studentList = [] for (i = 0;i < advisor_portfolio.length;i++){ //console.log("i am here") var regind; var sreind; var sid = advisor_portfolio[i]; //console.log(advisor_portfolio[i]) if (sid.Reg_progress_ind == "R"){ regind = "<img src=\"/static/images/1red_star.png\" height =\"13\" width=\"13\" alt=\"R\">"; //console.log(regind); } else if(sid.Reg_progress_ind == "Y"){ regind = "<img src=\"/static/images/2yellow_star.png\" height =\"13\" width=\"13\" alt=\"Y\">"; //console.log(regind); } else … -
django -how to read uploaded csv file which one field contain '\n'
I encountered a problem when I try to read a uploaded csv file which one field contains '\n' character. e.g. I have a csv file, its content like this: 1. row 1: "one", "this is \nsample", 2. row 2: "two", "this is also \nsample". I can get the uploaded file in request.FILES successfully, but when I loop the file, the row will break down because '\n' character. My code is: file = request.FILES.get('filename', None) for line in file: if line: line = line.decode("utf-8") fields_set = list(csv.reader([line], skipinitialspace=True))[0] In first loop, the content of variable 'line' is: "one, this is". And in second loop, the variable'line' get the value "sample". but what I want is to get 'one, "this is \nsample"'. Any help are appreciate, thanks in advance. -
Using Slack Interactive Buttons with a custom Slack app
A little bit confused about how to use the interactive buttons with my current slack application. I have the app authorized and I have the slack token with these scopes:identify,bot,commands,incoming-webhook. Whenever I press one of the buttons, I get "Oh no, something went wrong. Please try that again." How is the POST message sent to my specified URL? I assumed the buttons worked similarly to slash commands, but the POST requests from the buttons are not being interpreted. I'm also confused about how I'm actually supposed to use Slack Token to make a response back to slack. At the moment this is how I'm responding to slash commands: def post(self, request, format=None): base = {"response_type": "in_channel","mrkdwn":True} base['text'] = "Testing" command = request.data["text"].strip() if request.data["text"] == "test": return Response(base) -
How Access angular passed parameters in django views
I was trying to post the data using angular $http.post method in django,i wanted to know how will i access that parameter value in my django views:- Here is my controller.js var nameSpace = angular.module("ajax", ['ngCookies']); nameSpace.controller("MyFormCtrl", ['$scope', '$http', '$cookies', function ($scope, $http, $cookies) { $http.defaults.headers.post['Content-Type'] = 'application/json'; // To send the csrf code. $http.defaults.headers.post['X-CSRFToken'] = $cookies.get('csrftoken'); // This function is called when the form is submitted. $scope.submit = function ($event) { // Prevent page reload. $event.preventDefault(); // Send the data. var in_data = jQuery.param({'content': $scope.card.content,'csrfmiddlewaretoken': $cookies.csrftoken}); $http.post('add_card/', in_data) .then(function(json) { // Reset the form in case of success. console.log(json.data); $scope.card = angular.copy({}); }); } }]); Here is what i am attempting to access those in my view function:- card.content =request.POST.get('content') where card is my model's object,But i am getting NameError: name 'content' is not defined,Please help me out! -
Best way to save and display logs for multiprocess web app Django
We have a Django application with multiprocessing. Each process have it own log. How to store it? In DB or in separated files? -
how to take image path from html form
i need take image path from html form using django app. i know in the images field save the paths of images and not the images in database i need to take some from that paths using html form. i use this test=request.POST.get('cars') but not work because in print in debug show me none how to take image path ? class MyModel(models.Model): user = models.ForeignKey(User, unique=True) images = models.ImageField(upload_to='upload') views.py @login_required(login_url="login/") def disaster(request): #Myform = MyModelForm(user=request.user) photos=MyModel.objects.filter(user=request.user) test=request.POST.get('cars') print test return render(request,'about.html',{'photos':photos}) html : <form action=""> <select name="cars"> {% for photo in photos %} <option value="{{ photo.upload.url }}">{{ photo.upload.name }}</option> {% endfor %} </select> -
Error "Page no found(404)" using Django-Social-Auth in Django project
I am using Django-social-auth to login on my application. I used official documentattion and this tutorial but when I want to login, django throw me an error. The error is this: Page not found(404) Request Method: GET Request URL: http://127.0.0.1:8000/login/google-oauth2/ Raised by: social_django.views.auth Backend not found And I don't know why and how to solve it... I think the problem is in the urls. First I install social auth app: $ pip install social-auth-app-django and then I configure everything. The configuration... setting.py TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.contrib.messages.context_processors.messages", "django.core.context_processors.request", "social_django.context_processors.backends", #<-- "social_django.context_processors.login_redirect", #<-- "athento_context_processors.addons_settings", ) AUTHENTICATION_BACKENDS = ( #'social.backends.linkedin.LinkedinOAuth2', #'athento_backends.AthentoLDAPBackend' 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.google.GoogleOAuth', 'social_core.backends.github.GithubOAuth2', 'social_core.backends.twitter.TwitterOAuth', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) MIDDLEWARE_CLASSES = ( # 'pyinstrument.middleware.ProfilerMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', #<-- ) INSTALLED_APPS = ( ...... ...... 'social_django', ) # SETTING_SOCIAL_AUTH LOGIN_URL = 'login' LOGOUT_URL = 'logout' LOGIN_REDIRECT_URL = 'home' SOCIAL_AUTH_URL_NAMESPACE = 'social' # END_SETTING_SOCIAL_AUTH # SETTING_OAUTH2_KEY SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '<my key>' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '<my key>' # END_SETTING_OAUTH2_KEY urls.py urlpatterns = patterns('', ...... ...... ...... url(r'^home/$', 'views.index', name='home'), url(r'^login/$', 'views.index', name='login'), ...... ...... url(r'^oauth/', include('social_django.urls', namespace='social')), ) views.py def index(request): import os domain = request.META.get('HTTP_HOST', 'domain.com').split('.')[0] context = {'user': request.user, 'request': request, 'CLOUD': CLOUD, 'SIGNUP': SIGN_UP_ENABLED} domain_image = domain … -
Django: KeyError 'user' - update to 1.10
i updated my Django version from 1.9 to 1.10. Now, I get this KeyError. I hadn't this error message before. I looked at the changes of django version, but find nothing helpful. Here the error message: --- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.4/logging/__init__.py", line 978, in emit msg = self.format(record) File "/usr/lib/python3.4/logging/__init__.py", line 828, in format return fmt.format(record) File "/usr/lib/python3.4/logging/__init__.py", line 568, in format s = self.formatMessage(record) File "/usr/lib/python3.4/logging/__init__.py", line 537, in formatMessage return self._style.format(record) File "/usr/lib/python3.4/logging/__init__.py", line 381, in format return self._fmt % record.__dict__ KeyError: 'user' Here some parts of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # own context_processor for admin request 'test_modul.context_processors.global_settings', ], }, }, ] So I have included django.contrib.auth.context_processors.auth. Maybe somebody have for me an idea. -
Django_db mark for django parametrized tests
I have been learning django for the past few weeks and I tried using the parametrizing fixtures and test functions and from what I understood I can simply run multiple tests at once. With the parametrized test I am trying to test functions, which are found in all models. I read the documentation, but sadly, as soon as I tried it I got the following error message Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it.. I did read about the error and possible fixes and what I found was to create an autouse fixture and put it in conftest.py: import pytest @pytest.fixture(autouse=True) def enable_db_access_for_all_tests(db): pass Sadly, this change made 0 difference and I received the same exact error after running the test. I did also try to use the django_db mark to grant the test access to the database, but that also did not seem to work. -
Django import/reformat JSON into Model
I like to periodically import json data into a Django. What's the best way to import the data below to a Django model. As far as I've seen is the best approach to use Django fixtures. Since my Model looks like this and I can't change the given JSON, what's the best way to import the data or restructure the JSON to use it as a fixture. Django Model class Item(models.Model): item_name = models.CharField(max_length=250) timestamp = models.DateTimeField() value01 = models.DecimalField(max_digits=7, decimal_places=2) value02 = models.DecimalField(max_digits=7, decimal_places=2) Data I like to store: Item1 | 2017-04-18 09:24:46 | 15.00 | 12.68 Item1 | 2017-04-18 09:25:44 | 14.92 | 12.42 Given JSON: [ { "id": 1, "timestamp": "2017-04-18 09:24:46", "details": { "id": 843, "color": "white" }, "item": { "id": 1691, "category": "1", "item_type": { "id": 14, "name": "Item1" } }, "itemdatavalues": [ { "id": 227, "value": "15.00" }, { "id": 228, "value": "12.68" } ] }, { "id": 2, "timestamp": "2017-04-18 09:25:44", "details": { "id": 843, "color": "white" }, "item": { "id": 161, "category": "1", "item_type": { "id": 14, "name": "Item1" } }, "itemdatavalues": [ { "id": 283, "value": "14.92" }, { "id": 284, "value": "12.42" } ] } ] -
using webcomponent imports with django
Running a django app that serves web components, I am wondering how I can make a {% static %} tag resolution on collectstatic. For Example having the following web component (that is a static file - the static tag does not work): <link rel="import" href="{% static "polymer/polymer.html" %}/> <link rel="import" href="{% static "myapp/other_component.html" %}/> <dom-module id="hello-element"> <template>Hello there</template> </dom-module> <script> Polymer({ is: "hello-element" }) </script> I would like the collectstatic command to resolve the static tag on execution. I cannot use just static paths, e.g. /static/polymer/polymer.html because I am using: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' which appends a hash to any static file. On the other hand I would not like to serve the components as a template as it would impair the performance. How do I make collectstatic resolve the {% static %} attribute in static files on runtime? -
Django redirect user to app based on permission and group
Say i have a django project which have 4 apps 1 app is for logging in project urls: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^', include('Login.urls')), url(r'^admin/', admin.site.urls), ] settings: LOGIN_REDIRECT_URL = '/' login app urls: from django.conf.urls import url from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'), ] now say i have 3 apps based on user type i.e. Admin, Team Lead, Worker so i want to redirect user based on their type of employment. how can i achieve this ? any help is appreciated