Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Responsive design combined with Bootstrap and Django doesn't work
I do not know where I make errors. What is not correct in my code? I have website with subpages as below. Responsive design doesn't works. Is it related to any mistake in HTML/CSS code or instead of media queries I should use any specific way of making responsive design in bootstrap? Generally there is a problem with rows and columns - I can't change margins and font size responsively. Might it be related to django inheritance mechanism? {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeN$ <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3$ <link rel="stylesheet" type="text/css" href=relax/css/grid.css"> <title>Visyrelax</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { background: #F8F8FF; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */ .row{ margin:100px; } @media (min-width: 576px) { @include media-breakpoint-up(sm) .row{ font-size:10px; margin:10px; } } @media (min-width: 768px){ @include media-breakpoint-up(sm) .row{ font-size:20px; margin:10%; } } @media (min-width: 1200px){ @include media-breakpoint-up(sm) .row{font-size:60px;} p{ font-size:25px; } } </style> </head> <body> <nav class="navbar navbar-dark bg-dark"> <a class="navbar-brand" href ="{% url 'index'%}"> <p style="font-size:40px;"> &nbsp;&nbsp; <font color=DodgerBlue> Visy</font><font color$ <div class="navbar"> <a class= "nav-item nav-link" href ="{% url ‘a’%}”><font color=white>a</font></a> <a class= "nav-item nav-link" href ="{% url ‘b’%}”><font color=white>b</font></a> <a class= "nav-item … -
A way to check coverage of API tests for Django applications with Pytest
I have an application based on Django framework. Under the repo of the Django app, there is a repo which contains API tests based on Pytest framework. I am using requests library to send a request to the server, and asserting on the response data. An example of API test: import requests def test_some_api(self): s = requests.Session() response = s.get('/api/some_api') assert response.status_code == 200 Is there any way to know how many lines of code ran out of total amount of code lines of a given module? I managed to get a nice report with pytest-cov, but it works only for Unittests (calling functions directly from server repo). -
How to refresh 'refresh token' in django
Whenever I get a new access token using Refresh token, I want to get it reissued as well. So after coding as I thought, the refresh token was the same as the one issued before. How can I get a refresh token again? Here is my code. views.py class customRefreshView (GenericAPIView) : serializer_class = customTokenRefreshSerializer def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) try : token = RefreshToken(serializer.data['refresh']) except : return Response({'message': '잘못된 refresh token 입니다.'}, status=401) data = { 'token_type': 'Bearer', 'access_token': str(token.access_token), 'expired_at': str(datetime.now() + timedelta(minutes=30)), 'refresh_token': str(token), 'refresh_token_expires_at': str(datetime.now() + timedelta(hours=8)) } return Response(data, status=200) -
How to push data in selected data in django?
i Want to push key and data in to Selected data array .i am using mongodb database. i have two models in my lesson model class LessonsModel(models.Model): course_id = models.CharField(max_length=255) lesson_name = models.CharField(max_length=255) lesson_day = models.CharField(max_length=255) my course model class CourseModel(models.Model): course_name = models.CharField(max_length=255,blank=False) course_description = models.TextField(blank=False) course_image = models.ImageField(upload_to='course/',blank=False) i am selecting all data from my lessons model using following code. def fun(request): data=LessonsModel.objects.all() in my html file i am displaying this data. {% for newdatain data%} <tr> <td>lesson_name</td> <td>lesson_day </td> <td>course name(i want to display)</td> </tr> {% endfor %} now i want to display course name here.for that i need to select data from CourseModel. LessonsModel is having course_id. i want to append course_name into my 'data' object.how to to that? -
Django not serving HTML table in template (word counter web app)
Summary: Django is not rendering a basic 2 column by 11 row HTML table containing the top 10 most commonly used words in a large text file (Alice and Wonderland which is a public domain work). But right now the table is empty. Details: The table currently rendering on the web page looks like this, see here on imgur. In that pic, notice the bottom right corner, the table is empty. The fully populated word counter table and its contents rendering when a web user navigates to http://127.0.0.1:8000/counters. See here on imgur. However the problem there is that then the blog post lorem ipsum content is empty. See here: Here is my parent top level urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), # path('', include('mortems.urls')), path('', include('redactors.urls')), path('', include('posts.urls')), path('', include('counters.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is my counters app’s views.py: from django.shortcuts import render from collections import Counter import re from nltk.corpus import stopwords def counters(request, text=""): """ This function processes the top 10 most common words in a text file and then renders them. """ text = open("counters/Alice.txt", "r").read().lower() stoplist = stopwords.words('english') … -
Javascript how to know the current user? Session variable dont work? Uncaught (in promise) ReferenceError: require is not defined
SO this is my js code document.addEventListener('DOMContentLoaded', function() { document.querySelector('#inbox-view').innerHTML = `<p class="header" >Messages</p> `; fetch('/inbox') .then(response => response.json()) .then(messages => { messages.forEach(message => { let msection = document.createElement("div"); //create a clickable area let content = `<a href="#" class="posta"><img src="${message.senderimage}" class="rounded-circle"> <h4> ${message.sendername}</h4> <p style="display:inline;"> @${message.sender}</p> <p class="posta" id="myMessage"> ${message.content}</p> </a> <br> <br> <hr>`; msection.innerHTML = content; //set its content msection.setAttribute('class','msec'); //set its style msection.href ="#"; // make it clickable var session = require('express-session') if(`${message.sender}` != session){ document.querySelector('#inbox-view').append(msection); } What I want is I have this dynamic content in a Django Project. I want to display only the messages didn't send by the current user( basically display an inbox, not reply messages) In this section of my code var session = require('express-session') if(`${message.sender}` != session){ document.querySelector('#inbox-view').append(msection); } I want to check if the sender is current user if so I don't want to display that message. I already install thee package npm install express-session but still gives me this error: Uncaught (in promise) ReferenceError: require is not defined at inbox:130 (Without this session thing code works just fine) So what is the way of knowing the logged-in user? Is there any other way? Thank you -
File manager for amazon s3 in django admin (for django-ckeditor images)
Im looking for possibility to manage uploaded files to s3 bucket in django admin. Im sending some images to s3 via django-ckeditor. But ckeditor can only upload images, not delete. So after few month my bucket will be full of trash. I want add possibility to my django admin to manage that images. Maybe Ckeditor has some plugins for it? Or some django file managers? I found only that old question - How to remove images uploaded with django-ckeditor? -
Is there support for ordinal number suffixes localization?
For example if I have n-th apple (1st apple, 2nd apple, 3rd apple), how will this be translated in django? Is there some function to get suffix for given n? Looks like this depends on the gender of the word: 1re pomme, 2e pomme 1r homme 2e homme -
how to get list of active celery tasks inside django views
I want to get the list of all active celery tasks inside django views. When I looked online I found this link. I tried implementing this inside of django views like this from celery.app.control import Inspect def index(request): inspect = Inspect() print(inspect.active()) return render(request, 'index.html') but this give me the following error 'NoneType' object has no attribute 'control' Not sure what i am doing wrong -
Django Rest Framework - Serializing optional OneToOne relation
Suppose I have a Rating model used to store ratings on specific categories. Users can either provide a generic rating on a specific category, or they can provide a rating on a specific category guided by a question they were asked. The question thus is an optional field. Please note that this is a simplified example. In reality I am dealing with multiple optional fields. Therefore I would like to avoid using null for optional fields. To accomplish this I have created the following two models: class Rating(models.Model): score = models.IntegerField() category = models.CharField() class QuestionRating(models.Model): rating = models.OneToOneField(Rating, primary_key=True) question = models.CharField() These models model a missing question by a missing row instead of a null value which, as far as I know, is best practice. I would like to expose these models through a single API endpoint with a Django REST Framework ViewSet. On serialization the serializer should add a 'question' field only if a QuestionRating exists, and on deserializiation it should create/update the QuestionRating only if a 'question' field is provided; What would be the best way to accomplish this with a DRF serializer? -
Materialize css sidenav not working in django
I am trying to create a navbar and sidenav from materialize css in django. Created three main html files with the name of mbase.html, navbar.html and sidenav.html. below are the codes respectively. mbase.html: {%load materializecss %} {% load static %} <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--custom css for materialize--> <link rel="stylesheet" type="text/css" href= {% static 'css/style.css' %}> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--Title of the page goes here--> <title>{% block title %}Hello World {% endblock title %}</title> </head> <body> {% include 'navbar.html' %} {% block body %} {% endblock body %} <!--Jquery optional--> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script type="text/javascript" src={% static 'js/main.js' %}></script> </body> </html> navbar.html: {% load static %} <nav> <div class="nav-wrapper"> <a href="#" data-target="slide-out" class="sidenav-trigger left show-on-large"><i class="material-icons">menu</i></a> <a href="{% url 'index' %}" class="brand-logo center">CMMS</a> <ul class="right hide-on-med-and-down"> <!-- Dropdown Trigger for userprofile --> {% if request.user.is_authenticated %} <li><a id="userdropdown" class="dropdown-trigger" href="#!" data-target="dropdown2" >Hello, {{ request.user.email }}<i class="material-icons right">arrow_drop_down</i></a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> | <li><a href="{% url 'registration' %}">Registration</a></li> {% endif %} <li><a … -
ValueError: Unable to configure handler 'errors_file': [Errno 2] No such file or directory: '/log/ErrorLoggers.log'
I'm trying to deploy django project in AWS EC2. When I run my apache server error.log file contains this. I don't know what I'm missing. Can't find file log/ErrorLogger.log. [Wed Sep 02 08:50:20.751531 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] mod_wsgi (pid=18839): Target WSGI script '/home/ubuntu/django/pims/pims/wsgi.py' cannot be loaded as Python module. [Wed Sep 02 08:50:20.751588 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] mod_wsgi (pid=18839): Exception occurred processing WSGI script '/home/ubuntu/django/pims/pims/wsgi.py'. [Wed Sep 02 08:50:20.751761 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] Traceback (most recent call last): [Wed Sep 02 08:50:20.751802 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/config.py", line 565, in configure [Wed Sep 02 08:50:20.751808 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] handler = self.configure_handler(handlers[name]) [Wed Sep 02 08:50:20.751815 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/config.py", line 738, in configure_handler [Wed Sep 02 08:50:20.751819 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] result = factory(**kwargs) [Wed Sep 02 08:50:20.751826 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/handlers.py", line 202, in __init__ [Wed Sep 02 08:50:20.751830 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) [Wed Sep 02 08:50:20.751843 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/handlers.py", line 57, in __init__ [Wed … -
How to upload multiple files in django Generic Model
I've two models, one is normal model and one is generic model as below. class Gallery(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() and the another one is class GenericImage(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to="category_images", null=True, blank=True) Now how can i upload multiple image. i tried this one https://xn--w5d.cc/2019/09/18/minimalistic-multiupload-in-django-admin.html but this is only valid for foreign table. I know i can use foreign table to store images. But i did'n't to create multiple table to store photo for multiple tables. -
Is there a way to "link" external domains to my django app?
I'm developing a Django webapp in wich I want to let my users to link an external domain, for example https://mywebstore1.com so whenever someone introduces that url in the browser, what it shows is the content that I show in for example: https://myapp.com/user-store. My knowledge in the hole domains thing is very limited so any help is much appreciated. -
can FormMixin be used in TemplateView?
Hi i've used FormMixin in DetailView but I would also like to implement it in TemplateView if that isn't possible how can I implement a form in TemplateView -
Is there a way to serialize multiple objects in Django?
In a Django Project I would like to implement a simple chat-box. Version Django version 3.0.8 Models.py class DirectMessageClass(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_this') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_this') timestamp = models.DateTimeField(auto_now=True) content = models.CharField(max_length=200) read = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.username, "sendername":self.sender.profile.firstname, "senderimage":self.sender.profile.image.url, "receiver": self.receiver.username, "content": self.content, "timestamp":self.timestamp.strftime("%m/%d/%Y, %H:%M:%S"), # to format date "read":self.read, } Views.py def loadbox(request): user = request.user # Return messages in reverse chronologial order messages = DirectMessageClass.objects.filter(receiver=user).order_by("-timestamp").all() return JsonResponse([message.serialize() for message in messages], safe=False) I successfully get messages and turn it into a JSON object in the /loadbox path with this method. Later on, I fetch this data to display messages and it works. Example of my /loadbox path [{"id": 1, "sender": "ekvatorcizgisi", "sendername": "Asli", "receiver": "bilge", "content": "hi", "timestamp": "09/02/2020, 08:22:26", "read": true}] However, because I want it to display as a dialog. I need to add also the reply messages in this JSON object. In views.py I try def loadbox(request): user = request.user # Return messages in reverse chronologial order messages = DirectMessageClass.objects.filter(receiver=user).order_by("-timestamp").all() # return replies sent by the current user replies = DirectMessageClass.objects.filter(sender=user).order_by("-timestamp").all() return JsonResponse([message.serialize() for message in messages], safe=False) I am not sure how to return multiple … -
Django Python - Variable seems to be getting cached?
Within my Django app I obtain a list of projects within our Google Cloud Organisation with the following: try: global projectdicts projectdicts = cloudresmanv1.projects().list().execute() projectdicts = projectdicts.get('projects') except Exception as e: logging.error(e) The above is taken from a Django form called ProjectForm. However, after I've created a GCP project and browse within my Django app to the ProjectForm page again, the list doesn't update to show the newly-created project. My understanding is that it should run the above again, regardless. If I run through the script manually, the projectdicts variable of course updates. So, this leads me to believe for some reason the Django app or Python is caching the variable and not bothering to run the above again. Is this a likely problem? And if so, how do I force Django/Python to re-run this part of the script again to ensure the list of GCP projects is updated whenever I browse to the ProjectForm page? -
how to import modules in python/django correctly?
Started learning Python recently and had a problem importing a model into django. I am trying to import a product model into Telegram bot handler but an error occurs. Below is how my directory structure looks like: structure.png Code: from jangoMiniShop.products.models import Product Error: ModuleNotFoundError: No module named 'jangoMiniShop' Code: from ..products.models import Product Error: ImportError: attempted relative import with no known parent package -
Error Running WSGI application - client_secrets.json
I´m making a web app with django, but when I run the application, I´m getting this error: I have uploaded my client_secrets.json file in the project path and I´m sure I have no typos Settings.py GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json' WSGI.py # This file contains the WSGI configuration required to serve up your # web application at http://bohosul02.pythonanywhere.com/ # It works by setting the variable 'application' to a WSGI handler of some # description. # # The below has been auto-generated for your Django project import os import sys # add your project directory to the sys.path project_home = '/home/bohosul02/misitio' if project_home not in sys.path: sys.path.insert(0, project_home) # set environment variable to tell django where your settings.py is os.environ['DJANGO_SETTINGS_MODULE'] = 'gfglogin.settings' # serve django via WSGI from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Why is the JQuery not working? (Djangoapp)
I have a html file that displays a weekly calendar, which works fine in my app. {% extends 'blockit/base.html' %} {% load static %} {% block head %} <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static 'img/favicon.png' %}"/> <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/main.css" %}" /> <title>BlockIt - My Calendar</title> {% endblock %} {% block content %} <div class="row"> <div class="row"> <button id="back" class="col-md-3" align="left" onclick=location.href='?n={{ way.0 }}'>Last Week</span> </button> <div align="center"> <strong class="col-md-6" id="year">{{ week.0 }} - {{ week.6 }} - {{ year }}</strong> </div> <button class="col-md-3" align="left" onclick=location.href='?n={{ way.1 }}'>Next Week</span> </button> </div> {% load filters %} <div class="table-responsive" align="center"> <div class="col-md-12"> <table id="calendar" class="table"> <tr> <th></th> {% for day in week %} <th>{{day}}</th> {% endfor %} </tr> {% for i in range24 %} <tr> <th>{{i}}:00</th> {% for j in range7 %} {# id is time-day for example 8-17 it means 17th day of month and time is 8 #} <td id={{i}}-{{week|lookup:j|slice:"0:2"}}></td> {% endfor %} </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} {% block script %} <script type="text/javascript"> String.prototype.format = function() { var str = this; for (var i = 0; i < arguments.length; i++) { var reg … -
How to set validation for password in django admin Interface
In my Django admin interface when i click on change password. then i have 3 fields old password, new password and new password confirmation. So when i type old password and also type the new password same as old password it is being changed. But instead it should give error whenever in the new password field i write old password that "Create a new password that isn't your current password". Please let me know how to fix this. Forms.py from django.contrib.auth.password_validation import validate_password class ClientUserForm(forms.ModelForm): email = forms.EmailField(max_length=100, required=False) username = forms.CharField(max_length=100, required=True) password = forms.CharField( required=True, widget=forms.PasswordInput(), validators=[validate_password]) permissions = forms.MultipleChoiceField(choices=CLIENT_USER_PER_CHOICES) client = forms.ModelChoiceField(queryset=get_user_model().objects.filter( is_superuser=False, is_staff=True, client__isnull=True)) # permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all()) -
needs to fetch data from two tables. with one view function in django
def index(request): jobvacancylist = User.objects.all() return render(request, 'index.html', {"User":jobvacancylist}) candidatelist = applyjobsUser.objects.all() return render(request, 'index.html', {"applyjobsUser":candidatelist}) -
django prefetch_related for list of instances
I was wondering if it is possible to prefetch related fields for already instantiated django objects. for example let's say I have a group of instance of MyModel which I got from different sources (so I couldn't prefetch related the queryset at the first place) and I want to access related fields. I want to prefetch the fields for my list of objects in only 1 DB call. Is there an elegant way to populate my instance prefetch cache? I was imagining something like prefetch_related(list_of_instances, [field1, field2, field3]) -
Call simple function with Route Python Django
Its a simple question, but I want to understand it. I have a simple api rest in django rest framework router = routers.DefaultRouter() router.register(r'productos', ChelaViewSet) That gives me my data json from my model, it's working fine. Class ChelaViewSet: class ChelaViewSet(viewsets.ModelViewSet): serializer_class = ChelaSerializer queryset = Chela.objects.all() I just want to call a class with simple function like "hello world" from my route, when I put the URL print "Hello world" in console, no more, without queryset etc... What can I do? Ty -
Django DIRS issue
I am learning Django doc. It says , that i have to fill DIRS in INSTALLED_APP: 'DIRS': [BASE_DIR / 'templates'] That templates located in project/templates as they say. And now i somehow getting an error: ...File "D:\KoronaTime\DjangoPython\FirstProject\mysite\mysite\settings.py", line 58, in <module> 'DIRS': [BASE_DIR/ 'templates'], TypeError: unsupported operand type(s) for /: 'str' and 'str' Am I missing something?