Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter intermediary ManytoMany django with negation
This question is related to: Filter intermediary ManytoMany django class Ingredient(Model): name = CharField(max_length=55, unique=True) def __str__(self): return self.name class Meta: ordering = ('name',) class Product(Model): name = CharField(max_length=55) def __str__(self): return self.name class Meta: ordering = ('name', ) class ProductIngredient(Model): product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients') ingredient = ForeignKey(Ingredient, on_delete=CASCADE) optional = BooleanField(default=False) class Meta: unique_together = (('product', 'ingredient'),) ordering = ('product__name',) def __str__(self): return f'{self.product} - {self.ingredient}' I want to make two queries: select all products, whose ingredients don't contain strawberry AND milk select all products, whose ingredients don't contain strawberry OR milk In this case I'm totally lost. -
How to rename an image after upload in django?
How can I rename an image after upload in models.py Function to rename a company image after upload Args: instance: Company object filename: uploaded image filename Returns: New image filename -
Celery not writing logs to file in Docker
Celery does not appear to be writing any log files when run in a Docker container. The same command works fine when run outside of Docker. In my docker-compose.yml file: celery_main: build: context: . dockerfile: Dockerfile command: bash -c "sleep 20 && celery -A my_project worker -n 1 -Q celery -c 10 -l info -E --logfile=celery_main.log" links: - db - redis - web depends_on: - db - redis I am running Celery as a regular user. When I log into the working directory inside the container with bash, I can create files, so I don't understand what is stopping Celery from creating log files? I get logging printed to STDOUT as usual. -
How To Capture OnChange Event Using CKEditor with React JS
I am building a blog app using React, Django and Graphene. I want to integrate the CKEditor component in the React frontend but I can seem to be able to get the data from the CKEditor and store in state. Every time I type in the textfield i get the following errors "CKEditorError: Cannot read property 'value' of undefined". Please I'ld appreciate it if you can help point out what I'm doing wrong or not doing. My code is below. import React, { useState, Fragment } from "react"; import { Mutation } from "react-apollo"; import { gql } from "apollo-boost"; import axios from "axios"; import CKEditor from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import { makeStyles } from "@material-ui/core/styles"; import { Button, Input, TextField, Container, Typography } from "@material-ui/core"; const useStyles = makeStyles(theme => ({ paper: { marginTop: theme.spacing(12), display: "flex", flexDirection: "column", alignItems: "center" }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main }, form: { width: "100%", // Fix IE 11 issue. marginTop: theme.spacing(1) }, submit: { margin: theme.spacing(3, 0, 2) } })); const CreatePost = () => { const classes = useStyles(); // const [open, setOpen] = useState(false); const [title, setTitle] = useState(""); const [content, setContent] = useState(""); const [file, … -
ERROR: pull access denied for postgress, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
While learning Docker using Django I got some problem related to installing PostgreSQL in Linux Mint. This is the code from file docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgress:11 Error that I'm receiving while firing docker-compose up -d command Pulling db (postgress:)... ERROR: The image for the service you're trying to recreate has been removed. If you continue, volume data could be lost. Consider backing up your data before continuing. Continue with the new image? [yN]y Pulling db (postgress:)... ERROR: pull access denied for postgress, repository does not exist or may require 'docker login': denied: requested access to the resource is denied This error still raises after login in docker. -
Filter intermediary ManytoMany django
class Ingredient(Model): name = CharField(max_length=55, unique=True) def __str__(self): return self.name class Meta: ordering = ('name',) class Product(Model): name = CharField(max_length=55) def __str__(self): return self.name class Meta: ordering = ('name', ) class ProductIngredient(Model): product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients') ingredient = ForeignKey(Ingredient, on_delete=CASCADE) optional = BooleanField(default=False) class Meta: unique_together = (('product', 'ingredient'),) ordering = ('product__name',) def __str__(self): return f'{self.product} - {self.ingredient}' I want to make two queries: select all products, whose ingredients contain strawberry AND milk select all products, whose ingredients contain strawberry OR milk The first query is: Product.objects.prefetch_related('product_ingredients__ingredient').filter(product__ingredients__ingredient__name='strawberry').filter(product__ingredients__ingredient__name='milk') Do I need to write distinct in the first query? How to write the second query? -
How to pass a variable value from model to view (Django)
I am developing an app in Django. In this app there is a file form. In the view function associated to base.html I have implemented a message system that publishes a message if the user has not copleted the form correctly and tries to submit it. messages.error(request, ('ERROR: Compile the form properly!')) In my models.py I have a clean function that prevents form validation by raising a validation error and printing a message in the console. def clean(self): if not (self.file): raise ValidationError("No file selected.") if not self.Glossary_file.lower().endswith('.xls', '.xlsx', '.xlsm' '.csv', '.xml', '.xlt'): raise ValidationError("The selected file is not a spreadsheet.") However, these two messages gets overwritten by the string in views.py. Let's imagine I re-write my clean method like this: def clean(self): if not (self.file): error_message="No file selected." raise ValidationError("who cares, it gets overwritten by view message") if not self.Glossary_file.lower().endswith('.xls', '.xlsx', '.xlsm' '.csv', '.xml', '.xlt'): error_message="The selected file is not a spreadsheet." raise ValidationError("who cares, it gets overwritten by view message") How can I pass a variable containing the error message from my model to my views? I would need something like this in my views.py, replacing the other line: messages.error(request, (error_message)) but I don't know how to pass … -
Django Form how to set field value after clean()
I have a form that allow to select a point on a map or a postal code. The result will be a tuple longitude/latitude of the selected point or of the centroid of the postal code area. I want to keep the 2 input widget synchronized when re-displaying the formview. Here you have the solution I've found thanks to what explained in 813418 but modifying the raw data of the form is not recomended, how can I implement such behaviour in a better manner? class MyForm(geoforms.Form): postalcode = ModelChoiceField( queryset=PostalCode.objects.all(), required=False, initial=2429, widget = Select() ) coordinates = geoforms.PointField( widget=CustomOSMWidget(), required=False, srid=4326, initial=Point(4.72, 50.63, srid=4326) ) def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) return def clean(self): cl_data = super(MyForm, self).clean() if not cl_data.get("coordinates"): cl_data["coordinates"] = Point( float(cl_data["postalcode"].longitude), float(cl_data["postalcode"].latitude), srid=4326 ) else: nearest_zipcode = PostalCode.objects.get_nearest_postal_code_centroid( longitude=cl_data["coordinates"].x, latitude=cl_data["coordinates"].y) cl_data["postalcode"] = nearest_zipcode # to synchronize form fields # BEWARE changing the raw data of the form is not recomended self.data = self.data.copy() # IMPORTANT, self.data is immutable self.data.update(postalcode=cl_data["postalcode"]) self.data.update(coordinates=cl_data["coordinates"]) return cl_data -
Django vs Django Rest Framework, why use on over the other? [closed]
For my internship assignment i am going to create simple api that interacts with a mysql database, it also need authentication with multiple users. I have basically no knowledge of Python but do know other languages such as PHP and Laravel, Java and some C++. The minimum requirement for this project is that it's writen in Python. So i'm looking into some frameworks. I have played a little bit with Django and Django Rest Framework but it's not exactly clear to me why i should use DRF over plain Django. Can anyone point out to me the major advantages or disadvantages of DFR vs plain Django? -
getattr(): attribute name must be string
Very beginner here i am not getting whats the error here #Models.py file `from django.db import models class User(models.Model): name = models.CharField(max_length=20) email = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=50,null=True) steps = models.CharField(max_length=2000,null=True) image = models.ImageField(height_field=200,width_field=200,null = True, blank = True) ingredients = models.CharField(max_length=100, null=True) description = models.CharField(max_length=1000,null=True) user = models.ForeignKey(User, on_delete=models.CASCADE)` #Form file `from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Recipe class SignupForm(UserCreationForm): username = forms.CharField(max_length=30) email = forms.EmailField(max_length=200) class Meta: model = User fields = ['username','email','password1','password2'] class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name','steps','image','ingredients','description']` #views.py file `from django.shortcuts import render, redirect from .forms import SignupForm,RecipeForm from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages # views here @login_required(login_url='blog-login') def recipes(request): form = RecipeForm() if request.method == "POST": form = RecipeForm(request.POST) if form.is_valid(): form.save() return redirect('blog-home') context = {'form':form} return render(request,'food_app/Add_recipe.html',context)` -
Redirect user based on his type using obtain_jwt_token
i am using obtain_jwt_token to login to my system and I have 2 types of users admin and employee when one of them login to my system , the system will redirect him to his different page. I am using django framework for backend and react js for frontend -
How to make context variable dynamic in django template
Is it possible to append 2 context variables together into a single context variable that is calculated at run-time? For example: if I have {{contextA}} (which equals 1) and {{contextB}} (which equals 'building') and I wanted to add these together to get context {{1building}} How would I do this? I have tried: {{contextA + contextB}} {{{{contextA}} + {{contextB}}}} {{contextA |add: contextB}} {{contextA contextB}} I suppose this is not possible and this needs to be done in the view using python, but it would be ideal if I could just combine context variables in the template. -
Am writing test cases for modelviewset am using firebase Authentication taken based how to pass the token in this test cases in django
def test_address_post(self): client = RequestsClient() self.client.credentials(HTTP_AUTHORIZATION ="JWT"+"eyJhbGciOiJSUzI1NiIsImtpZCI6IjYzZTllYThmNzNkZWExMTRkZWI5YTY0OTcxZDJhMjkzN2QwYzY3YWEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vbW9kaXN0YWJveCIsImF1ZCI6Im1vZGlzdGFib3giLCJhdXRoX3RpbWUiOjE1ODE2NzU4NDIsInVzZXJfaWQiOiJMR3hvcFM2VnVvVkZVcTRscUxIT0t1aDN0SzEyIiwic3ViIjoiTEd4b3BTNlZ1b1ZGVXE0bHFMSE9LdWgzdEsxMiIsImlhdCI6MTU4MTY3NTg0MiwiZXhwIjoxNTgxNjc5NDQyLCJlbWFpbCI6InNhY2hpbmJnc2FjaGluM0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsic2FjaGluYmdzYWNoaW4zQGdtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn19.2pBUaEw-4KSDJrywdumTJTTuD-8Yo7cH7SDuPLbcGn_ZyvevWpdt4FhxJQnn-ss7dTiBGV4G0MfEmpWeiNUdeIAj_o85AivyltmDCzdY1SvvhfQ9eAHKOCAwj_EQs0lqQVeIvudBs_cLoYq21tw8NDPTooOcWUNsIeoCiPJIiuo0wmLa2b8pYm6F5OgV8AZ2E3Hmv52ehqxyH1-2JCsXpherMSP_N_9MbI0nqAfkpibx7uJi72nP53_Za52Ks4nN9M_nAa_E_VBJOM1JTFzr6prM6FERBGflmMD8pq2g1sJ5cbKezmbjzpXynFhBIOunCAmao8miXZJ4dgjjAWOWDg") address = Address(user_id='22',street='mg',city='bng',data={"name":"sachin"}) address.save() response = client.post('http://localhost:8000/api/v1/address/',self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) am getting error output as def test_address_post(self): client = RequestsClient() self.client.credentials(HTTP_AUTHORIZATION ="JWT"+"eyJhbGciOiJSUzI1NiIsImtpZCI6IjYzZTllYThmNzNkZWExMTRkZWI5YTY0OTcxZDJhMjkzN2QwYzY3YWEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NlY3VyZXRva2VuLmdvb2dsZS5jb20vbW9kaXN0YWJveCIsImF1ZCI6Im1vZGlzdGFib3giLCJhdXRoX3RpbWUiOjE1ODE2NzU4NDIsInVzZXJfaWQiOiJMR3hvcFM2VnVvVkZVcTRscUxIT0t1aDN0SzEyIiwic3ViIjoiTEd4b3BTNlZ1b1ZGVXE0bHFMSE9LdWgzdEsxMiIsImlhdCI6MTU4MTY3NTg0MiwiZXhwIjoxNTgxNjc5NDQyLCJlbWFpbCI6InNhY2hpbmJnc2FjaGluM0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImZpcmViYXNlIjp7ImlkZW50aXRpZXMiOnsiZW1haWwiOlsic2FjaGluYmdzYWNoaW4zQGdtYWlsLmNvbSJdfSwic2lnbl9pbl9wcm92aWRlciI6InBhc3N3b3JkIn19.2pBUaEw-4KSDJrywdumTJTTuD-8Yo7cH7SDuPLbcGn_ZyvevWpdt4FhxJQnn-ss7dTiBGV4G0MfEmpWeiNUdeIAj_o85AivyltmDCzdY1SvvhfQ9eAHKOCAwj_EQs0lqQVeIvudBs_cLoYq21tw8NDPTooOcWUNsIeoCiPJIiuo0wmLa2b8pYm6F5OgV8AZ2E3Hmv52ehqxyH1-2JCsXpherMSP_N_9MbI0nqAfkpibx7uJi72nP53_Za52Ks4nN9M_nAa_E_VBJOM1JTFzr6prM6FERBGflmMD8pq2g1sJ5cbKezmbjzpXynFhBIOunCAmao8miXZJ4dgjjAWOWDg") address = Address(user_id='22',street='mg',city='bng',data={"name":"sachin"}) address.save() response = client.post('http://localhost:8000/api/v1/address/',self.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) E AssertionError: 401 != 201 tests.py:39: AssertionError -------------------------------------------------------------------------------- Captured log call --------------------------------------------------------------------------------- WARNING django.request:log.py:228 Unauthorized: /api/v1/address/ ================================================================================ 1 failed in 8.48s ================================================================================= -
Django: 2 models in 1 Form using ModelForm and passing data in views.py?
I just got into Django and I'm trying to build a book-tracker app where users can login and submit books they've read and rate each book on a 5-star scale. I have 2 models for the books and the rating but I'm not sure how to combine them in the forms.py or how to pass the data in views.py. models.py: from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) book_title = models.CharField(max_length=200) book_author = models.CharField(max_length=100, null=True) book_review = models.TextField(max_length=1000) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) def number_of_ratings(self): ratings = Rating.objects.filter(book=self) return len(ratings) def avg_rating(self): sum = 0 ratings = Rating.objects.filter(book=self) for rating in ratings: sum += rating.stars if len(ratings) > 0: return sum / len(ratings) else: return 0 def __str__(self): return self.book_title class Rating(models.Model): book = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) class Meta: unique_together = (('user', 'book'),) index_together = (('user', 'book'),) forms.py: from django import forms from home.models import Post, Rating class HomeForm(forms.ModelForm): post = forms.CharField() class Meta: model = Post fields = ( 'book_title', 'book_author', 'book_review', ) class RatingForm(forms.ModelForm): rating = forms.IntegerField() class Meta: model = Rating fields = ( 'stars', ) views.py: … -
Django: using a centralized pyodbc connection for all the project
I'm using Django 3.x backed by Postgres for the Django ORM. Apart from that, I need to connect to an Informix DBMS to run SQL query. In my tests I run queries with pyodbc and all worked fine. Here is an example: import pyodbc # connecting with PROTOCOL=onsoctcp conn = pyodbc.connect('SERVICE=1504;PROTOCOL=onsoctcp;CLIENT_LOCALE=en_US.UTF8;DB_LOCALE=en_US.UTF8;DRIVER={IBM INFORMIX ODBC DRIVER (64-bit)};UID=user;PWD=my_pwd;DATABASE=my_db;HOST=my-host;SERVER=my_informix_server') conn.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8') conn.setencoding(str, encoding='utf-8') conn.setencoding(unicode, encoding='utf-8', ctype=pyodbc.SQL_CHAR) cursor = conn.cursor() cursor.execute("select * from foo") rows = cursor.fetchall() I have to run queries in a variety of Django views and I'm wondering if it is possible to manage the connection and the cursor in a centralized way. I'd like to avoid to put that code in each view, thus opening a new connection every time. I know that Django can manage secondary databases, but it does not support Informix. I wanted to try django-pyodbc but it seems unmaintained. Is there a solution to set up a project-wide pyodbc connection and cursor? -
How to add media files in django sitemap
How to start parse /media/ folder and write it in sitemap. Example site.com/media/1.pdf site.com/media.1.webp -
How to solve the problem of Devtools in django?
Whenever I load the page, it gives me the following error in command-line interface and error in chrome console also. Although it is loading in chrome, page is not loading in firefox. How to deal with this problem? How to make it work in every browser instead of just chrome? [14/Feb/2020 07:06:29] "GET /static/home/js/popper.min.js.map HTTP/1.1" 404 1802 [14/Feb/2020 07:06:29] "GET /static/home/js/bootstrap.min.js.map HTTP/1.1" 404 1811 Image to see the error in console https://i.stack.imgur.com/LryCT.png -
How do I use my intermediate table to show the m2m relationship in my templates?
I want to be able to see which players are in a team from my team-detail.html file. The team is chosen in my team-list.html. These are my relevant models: class Player(models.Model): name = models.CharField(db_column="Player's_Name", blank=True, null=True, max_length=32) team = models.CharField(db_column="Player's_Team", blank=True, null=True, max_length=32) username = models.CharField(db_column='Username', blank=True, null=True, max_length=32) password = models.CharField(db_column='Password', blank=True, null=True, max_length=16) email = models.EmailField(db_column='Email', blank=True, null=True) bio = models.CharField(db_column='Bio', blank=True, null=True, max_length=5000) # teamid = models.CharField(db_column='TeamID', blank=True, null=True, max_length=8) teams = models.ManyToManyField('Team', through='Membership') def get_absolute_url(self): return reverse('player-detail', args=[str(self.id)]) class Team(models.Model): team_name = models.CharField(db_column='Team_Name', blank=True, null=True, max_length=32) playernames = models.TextField(db_column='Players', blank=True, null=True) def get_absolute_url(self): return reverse('team-detail', args=[str(self.id)]) class Membership(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) date_joined = models.DateField(auto_now_add=False, blank=True, null=True) def get_absolute_url(self): return reverse('membership-detail', args=[str(self.id)]) Here is my team-detail file: {% extends "base_generic.html" %} {% block content %} <h1>Team Name: {{ team.team_name }}</h1> <p><strong>Players:</strong> <a href="{% url 'player-detail' team.membership_set. %}">{{ team.membership_set.all }}</a></p> {% endblock %} I'm not using my own query set, I'm using class TeamDetailView(generic.DetailView): model = Team Please let me know if you need any more info -
Can't get DJANGO URL Patterns to work. Can find index and admin but no other paths
Below are the files. The page keeps saying Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index/result.html Using the URLconf defined in marciano.urls, Django tried these URL patterns, in this order: admin/ [name='index'] index/result [name='calc'] ^media/(?P<path>.*)$ The current path, index/result.html, didn't match any of these. image1 image2 -
django/nuxt app stays logged in after refresh
I'm trying to figure out why my nuxt app won't log me out properly. When I logout using by clicking logout and I refresh the page I'm still logged in. My app is a dockerized django/DRF + nuxt with seperate frontend + backend setup. I've been looking in the logs and I see in django Unauthorized: /api/auth/token/destroy/ I'm not sure why I'm seeing this error. Is this a problem with django settings or frontend code? layouts/default.vue <template> <div class="mt-2"> <b-navbar toggleable="md" type="dark" variant="info"> <b-navbar-toggle target="nav-collapse"></b-navbar-toggle> <b-collapse is-nav id="nav-collapse"> <b-navbar-nav> <b-nav-item to="/">Events</b-nav-item> <b-nav-item to="/monitor">Monitor</b-nav-item> <b-nav-item to="/configuration">Configuration</b-nav-item> <b-nav-item to="/reports">Reports</b-nav-item> </b-navbar-nav> <b-navbar-nav class="ml-auto" v-if="$store.state.loggedIn"> <b-nav-text>{{ $store.state.user.username }}</b-nav-text> <b-nav-item @click="logout()">Logout</b-nav-item> </b-navbar-nav> <b-navbar-nav class="ml-auto" v-if="!$store.state.loggedIn"> <b-nav-item to="/login">Login</b-nav-item> </b-navbar-nav> </b-collapse> </b-navbar> <div class="mt-2"> <nuxt/> </div> </div> </template> <script> export default { methods: { logout () { this.$store.dispatch('logout') this.$router.push('/') } } } </script> server/auth.js const axios = require('axios') const app = require('express')() const API_URI = process.env.API_URI app.post('/login/', async (req, res) => { try { const result = await axios.post(API_URI + '/auth/token/create/', req.body) req.session.authToken = result.data.auth_token await req.session.save() return res.json({"OK": true}) } catch (e) { console.log(e) return res.status(401).json({ error: 'Bad credentials' }) } }) app.post('/logout/', async (req, res) => { delete req.session.authToken await req.session.save() axios.post(API_URI + '/auth/token/destroy/') return … -
How to convert UTC timezone to indian time format using from django.utils import timezone in django?
data.objects.filter(loan_date__range=[start_date, end_date] , disbursement_status=2).values('id', 'loanId', 'user_id', 'loan_date') -
How to encrypt credentials using Apache for Django?
I have configured my Django website on apache to run on the https protocol. And it is running as expected on https://xx.xx.xx.xx:8080. But in the VAPT test, we are getting "Transmission of Credential in Clear text". We have enabled SSL and used cipher as well, which was shown below. httpd-ssl.conf: # When we also provide SSL we have to listen to the # standard HTTP port (see above) and to the HTTPS port # Listen 8080 httpd-vhosts.conf: SSLProtocol -all +TLSv1.2 SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:ECDHE-RSA-AES128-SHA:DHE-RSA-AES128-GCM-SHA256:AES256+EDH:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GC:DES-CBC3-SHA$ WSGIPythonPath "E:/Python/Django channels/real_time_table/" <VirtualHost *:8080> ServerAdmin xxx.xxx@xxxx.com <Location "/retail/ws/home"> ProxyPass "wss://xx.xx.xx.xx:8081/retail/ws/home" </Location> WSGIScriptAlias / "E:/Python/Django channels/real_time_table/real_time_table/wsgi.py" DocumentRoot "E:/Python/Django channels/real_time_table" <Directory "E:/Python/Django channels/real_time_table/"> <Files wsgi.py> AllowOverride All Require all granted </Files> </Directory> <Directory "E:/Python/Django channels/real_time_table/app/static"> Require all granted </Directory> Alias /static "E:/Python/Django channels/real_time_table/app/static" SSLEngine on SSLCertificateFile "E:/Python/Django channels/real_time_table/cert/Wildcard_Jan19.crt" SSLCertificateKeyFile "E:/Python/Django channels/real_time_table/cert/wildcard_jan19_new.key" ErrorLog "E:/Python/Django channels/real_time_table/log/error.log" CustomLog "E:/Python/Django channels/real_time_table/log/access.log" common </VirtualHost> What else we should do in the apache configuration to pass the credentials in encrypted form? As I'm new to this, I tried provided all the necessary information at my best. Feel free to ask for more details to solve this issue. Feel free to provide any kind of information, that can even help as a starting point to debug! … -
Django Framework AUTH_LDAP_BIND_PASSWORD encryption
Can't find anything specific about this. I am using django-auth-ldap library for LDAP connection. Defined HPA to AUTH_LDAP_BIND_DN and AUTH_LDAP_BIND_PASSWORD plaintext. Works like a charm. Question: how would you resolve problem with having plain text password here? Base64 may be too weak, but i will take base64 solution under consideration also. -
Is there any way to make a second LOGIN_REDIRECT_URL in settings.py in Django?
I am creating an app in Django which have two external users: 1. Teacher 2. Student I have to create total of 3 apps, one the base app that contains home.html template, other the student app that contains student.html template and third teacher app that contains teacher.html template. I have just created two apps for now, base app and student app, I have created login, logout and register pages for student app, now I am successfully able to redirect the user (student) to the student.html whenever the student logs into the system and I did this by putting LOGIN_REDIRECT_URL = 'student' in my settings.py. I want to do the same for Teacher app as well but I want to redirect teacher to the teacher.html. Is there any way that I can create the second LOGIN_REDIRECT_URL in settings.py to fulfil this purpose or it will be done any other way? -
Difference between django-environ and python-decouple?
Here I have used django-environ to set the environment variable but it is giving me SECRET_KEY error.How to properly configure the environmental variable? I also used the python-decouple for this instead of django-environ which works fine but didn't work with django-environ. What is the difference between django-environ and python-decouple which will be the best for this ? settings import environ env = environ.Env() SECRET_KEY = env('SECRET_KEY') DEBUG = env.bool("DEBUG", False) .env file DEBUG = True SECRET_KEY = #qoh86ptbe51lg0o#!v1#h(t+g&!4_v7f!ovsl^58bo)g4hqkq #this is the django gives Got this exception while using django-environ django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable