Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get_foo_display isn't functioning well with DRF
I have this class MEMBERSHIP_STATUS: PENDING = 0 DECLINED = 1 MEMBER = 2 and the model is class Membership(models.Model): MEMBERSHIP_STATUS = ( (MEMBERSHIP_STATUS.PENDING, _('Pending')), (MEMBERSHIP_STATUS.DECLINED, _('Declined')), (MEMBERSHIP_STATUS.MEMBER, _('Member')), ) user = models.OneToOneField(User, on_delete=models.CASCADE) status = models.IntegerField(max_length=10, choices=MEMBERSHIP_STATUS, default=MEMBERSHIP_STATUS.PENDING) def __str__(self): return self.user.username now, in serializers.py, I have this class MembershipSerializer(serializers.ModelSerializer): user = UserSerializer() family = FamilySerializer() status = serializers.SerializerMethodField() class Meta: model = Membership fields = '__all__' def get_status(self, membership): return membership.get_status_display() This always returns 0, Even tho I'm expecting it to return the display. The solution I found is class MEMBERSHIP_STATUS: PENDING = '0' DECLINED = '1' MEMBER = '2' Changing the Integers to Strings seems to work, But I don't understand why. Any explaination? -
How can I load only one object from react-redux using api?
I am working on a simple web app that allows user login. I am using python == 3.7.4 django == 3.0.4 djangorestframework == 3.11.0 react == 16.13 axios == 0.19.2 In my users's api, # localhost:8000/api/users [ { "url": "http://localhost:8000/api/users/2/", "id": 2, "username": "foo", "boards": [ "http://localhost:8000/api/boards/15/" ] }, { "url": "http://localhost:8000/api/users/3/", "id": 3, "username": "poopoop", "boards": [] }, ] My auth in action is, // actions/auth.js import { USER_LOADED, USER_LOADING } from './types' export const loadUser = () => (dispatch, getState) => { dispatch({ type: USER_LOADING }) const token = getState().users.token; const config = { headers: { 'Content-type': 'application/json' } } if(token) { config.headers['Authorization'] = 'Token ${token}'; } axios.get('/api/users', config) .then(res => { dispatch({ type: USER_LOADED, payload: res.data }); }).catch(err => { dispatch(returnErrors(err.response.data, err.response.state)); dispatch({ type:AUTH_ERROR }) }) } reducers/auth.js const initialState = { token: localStorage.getItem("token"), isAuthenticated: null, isLoading: false, user: null }; export default function(state=initialState, action){ switch(action.type){ case USER_LOADING: return { ...state, isLoading: true } case USER_LOADED: return { ...state, isAuthenticated: true, isLoading: false, user: action.payload } case AUTH_ERROR: case LOGIN_FAIL: localStorage.removeItem('token'); return { ...state, token: null, user: null, isAuthenticated: false, isLoading: false } case LOGIN_SUCCESS: localStorage.setItem("token", action.payload.token); return { ...state, ...action.payload, isAuthenticated: true, isLoading: false } default: … -
Use an image in Wagtail's Base.html template
I'm looking to add a logo to my base.html by pulling from the page model... But I don't have access to the base.html page model through wagtail, and so I don't know where to create a ImageChooserPanel to specify the logo for my navbar (which should be applied to all pages). -
super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght'
Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\django\myfirst\myfirst\apps\articles\models.py", line 8, in <module> class Comment(models.Model): File "D:\django\myfirst\myfirst\apps\articles\models.py", line 10, in Comment author_name = models.CharField('имя автора', max_lenght = 50) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 984, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght' -
Django - Fetch values from children via Foreign Key, while looping the parent objects in template
I am quite new to Django and probably this will be totaly noobish question, but I am stuck in this situation and bit help would be much appreciated. I have the following models: class BillType(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name class Bill(models.Model): bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE) month = models.CharField(max_length=200) amount = models.IntegerField() due_date = models.CharField(max_length=200) note = models.TextField(blank=True) recurring = models.BooleanField(default=True) currency = models.CharField(max_length=100) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.month and the following view: def billingOverview(request): bill_types = BillType.objects.all() context = { 'bill_types': bill_types, } return render(request, 'management/billing-overview.html', context) In the template, I am using the For loop to loop through the BillType objects and that part is working fine. However, for each of the looped BillType objects that are rendered separately in the template, I need to access and show the data for 'month' corresponding to that particular BillType object. Can you help me with an example of how I can do that action? Thanks, Bojan In case the template is needed: {% for bill_type in bill_types %} <!-- Billing overview column --> <div> <!-- Billing overview widget --> <div class="bo-widget"> <div class="bo-widget-header"> <div> <h2>{{ bill_type.name }}</h2> <span>Overview of {{ bill_type.name|lower … -
TypeError: Tried to update field dashboard.Product.province with a model instance
I am trying to save the url in my object where the encrypted id of my object is located. So it writes all fields and finally tries to add the url to the already called object. Then my error is shown 'TypeError: Tried to update field dashboard.Product.province with a model instance.' How do I save my url after calling object.save () once. Maybe there is a better way to get object.id before calling object save (). I would not have to save the same object a second time. Thank you in advance for any help. Models.py class Product(models.Model): type = models.CharField(max_length=50) img = models.ImageField() img_sm = ResizedImageField(size=[400, 400], crop=['middle', 'center'], force_format='JPEG', quality=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.TextField() province = models.CharField(max_length=100) city = models.CharField(max_length=100) name_user = models.CharField(max_length=50) phone = models.CharField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) url = models.URLField() #aktualny url produktu pawnshop_send = models.IntegerField(default=random_pawnshop) def __str__(self): return '%s - %s - %s' % (self.type, self.name, self.city) class Meta: ordering = ['-date_created', ] views.py if request.method == 'POST': form = FormNewProduct(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data object = Product() object.type = type object.img = cd['img'] object.img_sm = cd['img'] object.category = get_instance(cd['category'], Category) object.name = cd['name'] object.description = cd['description'] … -
How can i deploy a Django API
How can i deploy a Django API to an server? Is there a command like python3 manage.py deploy? In order for me to copy paste the produced files to the server -
django-allauth: Facebook always requires entering password
I have set user registration via Facebook with django-allauth. Everything works fine, except for one thing: when I am redirected to Facebook for logging in, I am required to enter my Facebook password. How can this be avoided? I want perform the login silently, without the user being prompted to commit any additional actions. My allauth settings in settings.py: SOCIALACCOUNT_PROVIDERS = \ { 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'path.to.callable', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}, 'google': { 'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'], 'AUTH_PARAMS': {'access_type': 'online'}, } } -
Django: Update Fields, throws "Save with update_fields did not affect any rows." Even though row is updated
I have a table with a row that needs to be updated. This Table however has a trigger. For simplicity I have limited the trigger to present my case. Alter TRIGGER Cow_UpdateTrigger ON Cow FOR update AS select * from Cow This trigger gets called when an Update occurs, however the trigger doesn't modify any fields with in the Cow Table. The code below shows me attempting to updating the name of a Cow. It throws the following exception upon saving. "Save with update_fields did not affect any rows." However the name of the cow actually has been updated. cow = Models.Cow.objects.get(pk=1) cow.name = "Life" cow.save(update_fields=["name"]) # Raises Error, However successfully updates fields. Further Analysis with the cursor. c = cursor.execute("""Update COW set cow_name = "Love" where COW_ID = '1' """) c.rowcount The following code is ran with three different update trigger scenarios. The returning row count reflecting the rows changed differs. Trigger is removed and Update is performed. Row count = 1 The Trigger is created with a select statement . Row count = -1 however a row has changed A trigger is created with an update statement to randomly change an attribute in updated row. This also returns … -
Django saving data with form
I already saw many Stack overflow posts, but cannot find any problem on my code, but this code doesn't save any piece of data. models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=50, blank=True) content = models.CharField(max_length=200, blank=True) post_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title forms.py from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['title', 'content', 'post_date'] views.py from django.shortcuts import render from django.template import loader from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.http import Http404 from .models import Post from .forms import PostForm # Create your views here. def index(request): latest_post_list = Post.objects.order_by('-post_date')[:5] template = loader.get_template('form/index.html') context = {'latest_post_list':latest_post_list} return render(request, 'form/index.html', context) def posts(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'form/posts.html', {'post':post}) def posting(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') else: print(form.errors) else: form = PostForm() return render(request, 'form/posting.html', {'form' : form}) posting.html <form action="/form/" method="post"> {% csrf_token %} {{ form }} <input type='submit' value='Submit'> </form> <script src="" async defer></script> I swear I saw many questions about it, but still I'm in trouble :/ I thought form.save in the views.py would make it work … -
Uploading multiple files using react and DJango REST API
I am building a project in which users can upload videos in bulk, My code works fine but I want to show the users a progress bar when their videos are being uploaded to the server, By doing some research on the internet I found that the onUploadProgress event of Axios can be used, but I have no idea on how to send the upload progress of each video file individually. Below is my code reducers.js file- import * as actionTypes from "../actions/types"; const intialState = { isLoading: false, uploadProgress: 0, error: null }; export default function(state = intialState, action) { switch (action.type) { case actionTypes.ADD_VIDEO_START: case actionTypes.ADD_VIDEO_SUCCESS: case actionTypes.ADD_VIDEO_ERROR: return { ...state, isLoading: action.isLoading, error: action.error }; case actionTypes.VIDEO_UPLOAD_PROGRESS: return { ...state, uploadProgress: action.percentage }; default: return state; } } actions.js import * as actionTypes from "./types"; import { getToken, VIDEO_URL } from "./Utils"; import axios from "axios"; export const addVideos = video => dispatch => { if (getToken()) { dispatch({ type: actionTypes.ADD_VIDEO_START, isLoading: true, error: null, }); const config = { headers: { Accept: "application/json", "Content-Type": "multipart/form-data", Authorization: `Token ${getToken()}` }, onUploadProgress: progressEvent => { const { loaded, total } = progressEvent; let percentage = Math.floor((loaded * 100) … -
Can I use digital ocean spaces for user uploaded files with django?
I would like to have a central place for images, javascript, css, etc. to enable horizontal scaling on my Django application. Currently I am looking at DigitalCcean spaces however in their guides it seems only possible to upload files manually using: python manage.py collectstatic Does anyone have experience using DigitalOcean spaces with media files? I basically want to make sure that a file uploaded on one server, is accessible by another server. Thanks in advance! -
Getting authenticated username in Django
I'm using Django's built in user who is in my application authenticates and uses some service. Now my problem is, I want to get current user's username and write it to database. Here I've used such method that mentioned User model as a ForeignKey, but it is assigning to database as an empty data. But I want to write current user's name. Here are my codes: views.py: @login_required(login_url='sign_in') def upload_document(request): context = {} form = UploadDocumentForm() if request.method == 'POST': form = UploadDocumentForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('index') context = {'form':form} return render(request, 'upload_document.html', context) models.py: class OriginalDocument(models.Model): document = models.FileField(upload_to='static/original_document', blank=False) document_title = models.CharField(max_length=300) student_name = models.CharField(max_length=100) teacher_name = models.CharField(max_length=100) document_type = models.CharField(max_length=100) university = models.ForeignKey(University, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add = True) checked_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.document_title -
Dynamically Populate New Row in HTML Table using Javascript/JQuery
I have a HTML table which is populated using Django variables: <h3>Recommended Playlist</h3> <table class="table table-dark" id="playlist_table"> <thead> <tr> <th scope="col"> <h4>Artist</h4></th> <th scope="col"> <h4>Track</h4></th> <th scope="col" style="display:none;"> <h4>Track ID</h4></th> <th scope="col"> <h4>Album</h4></th> <th scope="col" colspan="2"> <h4>Accept/Reject</h4></th> </tr> </thead> <tbody> {% for song in playlist %} <tr> <td>{{song.artist_name}}</td> <td>{{song.track_name}}</td> <td style="display:none;" class="song_id">{{song.track_id}}</td> <td>{{song.album_name}}</td> <td class="approve"><i class="fas fa-check-circle fa-2x" onclick="approveRow(this)"></i></td> <td class="reject"><i class="fas fa-times-circle fa-2x" onclick="deleteRow(this)"></i></td> </tr> {% endfor %} </tbody> </table> Users can 'Accept' or 'Reject' rows using the tick/X icons: Table Screenshot The following Javascript functions are called if users 'Accept'/'Reject' a song: //if a user accepts a row function approveRow(r) { var i = r.parentNode.parentNode.rowIndex; var row = document.getElementById("playlist_table").rows[i]; row.deleteCell(5); row.deleteCell(4); var blank1 = row.insertCell(4); //green tick once song approved blank1.innerHTML = '<center><i class="fas fa-check-circle fa-2x" style="color:#00ee21;"></i></center>'; //order of above is important as once a cell is deleted, the other's index is index-1 approve_counter++; console.log(approve_counter); song_selection.push('Accept'); } //if a user rejects a row function deleteRow(r) { var i = r.parentNode.parentNode.rowIndex; document.getElementById("playlist_table").deleteRow(i);//delete existing row var table = document.getElementById("playlist_table"); var row = table.insertRow(i); //insert new blank row var artist = row.insertCell(0); var track = row.insertCell(1); var album = row.insertCell(2); var approve = row.insertCell(3); var reject = row.insertCell(4); artist.innerHTML = "New … -
Django - CKeditor dynamic image size based on client device
I'm trying to develop a blog style website and I use Django as web framework, CKeditor as wygiwys and Filer for file management (linked with CKeditor with django-ckeditor-filebrowser-filer). It's all working, but the problem is that I can't control the image size for the images used inside the posts, I'd like to serve them based on user's devide (smaller on mobile, larger on desktop, etc..). I have no idea how to do that, any ideas? thanks -
Django-Ckeditor seems to turn dropped PDFs into .. an image?
When people drop PDF files into posts on my forum, django-ckeditor somehow magically turns it into an image of page-one! (The PDF is gone.) Now, I've peeked behind the scenes at this piece of software enough to know that "step-one should be for me to ask somebody." What's causing this behavior? (Which is very unexpected, actually ...) And, what can I do to cause the PDF to instead display as the visible attachment that the user (and, I ...) undoubtedly anticipated? Thanks in advance! -
Django: No module named 'projectxproject.urls'
I have multiple urls files in a folder with an __init__.py so it is treated as a module however Django keeps returning ModuleNotFoundError: No module named 'projectxproject.urls' Here is my folder structure, the code in my __init__.py file and my ROOT_URLCONF settings. -
Match an url with slash at the end in Django url.py
I have an endpoint: url(r'^reports/(?P<site>.*)', Scan.report) that match, for example, https://www.google.com and the same url with a slash at the end. But, when I send https://www.google.com/ my endpoint clean the final slash from the url. How can I resolve this? I need the slash at the end to be optional. And Django doesnt remove it. -
Reverse for "new_entry" not found
Working through Python Crash Course and completely hung up on this error: NoReverseMatch at /new_entry/1/ Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/new_entry/1/ Django Version: 3.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$'] Exception Location: C:\Users\KentSurface\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Users\KentSurface\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\KentSurface\\PycharmProjects\\learning_log', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\KentSurface\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] Server time: Thu, 19 Mar 2020 19:40:21 +0000 Error during template rendering In template C:\Users\KentSurface\PycharmProjects\learning_log\learning_logs\templates\learning_logs\base.html, error at line 0 Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$'] 1 <p> 2 <a href="{% url 'learning_logs:index' %}">Learning Log</a> - 3 <a href="{% url 'learning_logs:topics' %}">Topics</a> 4 </p> 5 6 {% block content %}{% endblock %} 7 -
Django: In deployment where stays the static files of admin?
i have a web application runing, the statics files from apps works but in /admin/ seems like doesn't have a css file. In the production the admin page works fine. My question is where is the css file from admin page of django? Just in case if somebody want to check, this is my configuration of static files of the web-app in deployment STATIC_URL = '/static/' STATIC_ROOT = '/apps_wsgi/generic_name/main/static/' MEDIA_URL = '/media/' MEDIA_ROOT = '/apps_wsgi/generic_name/main/media/' -
PostgreSQL: Create extension not working when called from init script
I'm using docker-compose to create a database capable of performing a trigram similarity search using the pg_trgm extension: postgres-db: restart: always image: postgres:12.2 env_file: - ../../.envs/_compose_prod.env expose: - 5432 volumes: - database-data:/var/lib/postgresql/data/ - ../entrypoints/init.sql:/docker-entrypoint-initdb.d/init.sql ../entrypoints/init.sql: create extension pg_trgm; I used docker-compose down -v first. Here's an excerpt from the output of docker-compose up --build: postgres-db_1 | 2020-03-19 19:36:42.352 UTC [46] LOG: database system was shut down at 2020-03-19 19:36:42 UTC postgres-db_1 | 2020-03-19 19:36:42.360 UTC [45] LOG: database system is ready to accept connections postgres-db_1 | done postgres-db_1 | server started postgres-db_1 | CREATE DATABASE postgres-db_1 | postgres-db_1 | postgres-db_1 | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sql postgres-db_1 | CREATE EXTENSION postgres-db_1 | postgres-db_1 | postgres-db_1 | 2020-03-19 19:36:42.643 UTC [45] LOG: received fast shutdown request postgres-db_1 | waiting for server to shut down....2020-03-19 19:36:42.647 UTC [45] LOG: aborting any active transactions postgres-db_1 | 2020-03-19 19:36:42.649 UTC [45] LOG: background worker "logical replication launcher" (PID 52) exited with exit code 1 postgres-db_1 | 2020-03-19 19:36:42.650 UTC [47] LOG: shutting down postgres-db_1 | 2020-03-19 19:36:42.686 UTC [45] LOG: database system is shut down postgres-db_1 | done postgres-db_1 | server stopped postgres-db_1 | postgres-db_1 | PostgreSQL init process complete; ready for start up. postgres-db_1 | … -
Django - Custom admin page not displaying properties
In my project, I use the AbstractUser class to override the default User model so I can add extra properties. I want these properties to be added to the admin page, therefore I can view them. The code below is how I have customized my admin page so far. forms.py: class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'following', 'posts') class CustomUserChangeForm(UserChangeForm): class Meta: model = User fields = ('username', 'email', 'following', 'posts', ) admin.py: class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User list_display = ['username', 'email', 'bio', 'profilePic',] When I click on a user object on the admin page, I can view all the properties such as a users username and email, however I want to view properties such as following and posts, which are both ManyToManyFields. I supply these properties in the CustomUserCreationForm and the CustomUserChangeForm, however I can't still view these properties. Does anybody know how I can view these fields when I view or create a new user object? Thank you. -
Django MEDIA_URL, unable to source image
Whenever I try to run the code below I get the error: the system cannot find the path specified: 'app_pickfeel/images/' I'm trying to source a random image from the following directory: 'PickFeel/app_pickfeel/static/app_pickfeel/images' Using a custom template tag (random_image.py) random_image.py import os import random from django import template from django.conf import settings # module-level variable register = template.Library() @register.simple_tag def random_image(image_dir): try: valid_extensions = settings.RANDOM_IMAGE_EXTENSIONS except AttributeError: valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', ] if image_dir: rel_dir = image_dir else: rel_dir = settings.RANDOM_IMAGE_DIR rand_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) files = [f for f in os.listdir(rand_dir) if os.path.splitext(f)[1] in valid_extensions] return os.path.join(rel_dir, random.choice(files)) html template: <img src="{{ MEDIA_URL }}{% random_image "app_pickfeel/images/" %}"> settings.py MEDIA_ROOT = '' MEDIA_URL = '/images/' STATIC_URL = '/static/' Any help would be greatly appreciated. -
Django loggers don't work when DEBUG=False
I'm using Django==2.2.11 and djangorestframework==3.11.0. When I run ./manage.py runserver and make an http request to the endpoint that has some database queries I got all the logging information. This is only when DEBUG = True. If I set DEBUG=False I won't get any logging to console at all: settings.py: DEBUG = False LOGGING = { 'version': 1, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False }, 'django.request': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False }, } } -
Problem witch pyplot graphics from a same view in django
I use a view to create a graph with matplotlib. This view is like this and depend on the id_projet argument. def Graphique_view(request,id_projet): """ s'occupe de l'affichage du graphique d'un projet """ projet = Projet.objects.get(pk=id_projet) date_debut = projet.date_debut semaine_fin = delta_semaine(date_debut,projet.date_fin) f= plt.figure(figsize=(16,9)) plt.title('graphique') x1=[] y1=[] semaine = 0 ETP = 0 while semaine <= semaine_fin : compteur = 0 for bilan in Bilan_horaire.objects.filter(projet=projet): if delta_semaine(date_debut,bilan.date) == semaine : ETP += bilan.ETP compteur +=1 bilan_semaine=bilan if compteur != 0 : x1.append(bilan_semaine.date) y1.append(ETP) semaine+=1 plt.plot(x1,y1,label = 'ETP travaillés') ETP = 0 for livrable in projet.livrables : semaine = delta_semaine(date_debut,livrable.dernier_jalon.date_jalon) for utilisateur in projet.utilisateurs: ETP += ETP_ressources_livrable.objects.filter(utilisateur=utilisateur).filter(livrable=livrable).order_by('date_modification').reverse()[0].ETP_estime x=[date_debut,livrable.dernier_jalon.date_jalon,livrable.dernier_jalon.date_jalon] y=[ETP,ETP,0] plt.plot(x,y,label=livrable.libelle) myFmt = mdates.DateFormatter('S%W - %Y') axes = plt.gca() axes.xaxis.set_major_locator(mdates.DayLocator(interval=7)) axes.xaxis.set_major_formatter(myFmt) plt.xticks(rotation = '-50') plt.xlabel('temps (semaines)') plt.ylabel('heures (ETP)') plt.legend() canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) matplotlib.pyplot.close(f) return response The url associate is projet/<int:id_projet>/graphique This is the result for projet/9/graphique for instance And this is the result for projet/10/graphique for instance Now if try to display this 2 images in a html like this : <img src="{% url 'graphique_projet' 9 %}" /> <img src="{% url 'graphique_projet' 10 %}" /> I have that which is not what I want. Any help would be appreciate. …