Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly configure Celery logging functionality with Django?
I use Django and Celery to schedule a task but I have an issue with the logger because it doesn't propagate properly. As you can see in the code below I have configured the Python logging module and the get_task_logger Celery module. import logging from celery import Celery from celery.utils.log import get_task_logger # Configure logging logging.basicConfig(filename='example.log',level=logging.DEBUG) # Create Celery application and Celery logger app = Celery('capital') logger = get_task_logger(__name__) @app.task() def candle_updated(d, f): logging.warning('This is a log') logger.info('This is another log') return d+f I use django-celery-beat extension to setup periodic task from the Django admin. This module stores the schedule in the Django database, and presents a convenient admin interface to manage periodic tasks at runtime. As recommended in the documentation I start the worker and the scheduler that way: $ celery -A capital beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler celery beat v4.4.0 (cliffs) is starting. __ - ... __ - _ LocalTime -> 2020-04-02 22:33:32 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) [2020-04-02 22:33:32,630: INFO/MainProcess] beat: Starting... [2020-04-02 22:33:32,631: INFO/MainProcess] Writing entries... [2020-04-02 22:33:32,710: INFO/MainProcess] Scheduler: Sending due task Candles update (marketsdata.tasks.candle_updated) [2020-04-02 … -
Graphene says field name is invalid keyword
I'm using ModelFormMutation and Graphene says a field keyword is not valid, when itself is looking for those fields. I delete the field and error changed to another field 😬. -
DRF How to restrict (permissions) user by companies?
I mean User have a company and restrict views by companies. If user in company A he can't look on same view on company B. Any help with this? thx class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): first_name = models.CharField(max_length=254) last_name = models.CharField(max_length=254) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) -
Django model method returning correct response when called from shell but not when called from template
models.py class player(models.Model): name = models.CharField(max_length = 100) rounds_played = models.IntegerField() rounds_missed = models.IntegerField() date_joined = models.DateTimeField(default = timezone.now) total_points = models.IntegerField() bio = models.TextField() user_ID = models.CharField(max_length = 10) user_m = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField(), def rounds_record(self): return int(100 * self.rounds_played / (self.rounds_played + self.rounds_missed)) def player_status(self): if self.is_active: return "Yes" return "No" def average_points(self): return int(self.total_points / self.rounds_played) def __str__(self): return self.name template snippet {% for player in players %} <div class = "grid-item"> {{player.player_status}} </div> {% endfor %} I'm developing a database web app (to learn django) in which players on a team and their statistics are tracked and stored in a psql database. When calling the player_status method from the manage.py shell it returns the correct response, say, for each user, 'yes', 'no'. However when the method is called from the template the method is returning 'yes', 'yes'. After some troubleshooting I found that it indeed is returning true for each response. What can I do to fix this problem. EDIT: I should specify I currently have 2 test users, one storing True and the other storing False in the is_active BooleanField -
NameError: name 'ProductTag' is not defined
models.py from django.db import models from django.contrib.auth.models import User class ActiveManager(models.Model): def active(self): return self.filter(active=True) class Product(models.Model): name = models.CharField(max_length=32) description = models.TextField(blank=True) price = models.DecimalField(max_digits = 5, decimal_places = 2) slug = models.SlugField(max_length=48) active = models.BooleanField(default=True) in_stock = models.BooleanField(default=True) date_updated = models.DateTimeField(auto_now=True) objects = ActiveManager() tags = models.ManyToManyField(ProductTag, blank=True) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="product-images") thumbnail = models.ImageField( upload_to="product-thumbnails", null=True) class ProductTag(models.Model): name = models.CharField(max_length=40) slug = models.SlugField(max_length=48) description = models.TextField(blank=True) active = models.BooleanField(default=True) def __str__(self): return self.name def natural_key(self): return(self.slug,) The name error says ProductTag is not defined, whereas ProductTag itself a Class. I don't understand where I missed... appreciate for the help -
Getting info from django-debug-toolbar when using manage.py run_method?
Is there a way to get the information that django-debug-toolbar collects/compiles, namely the sql queries and their times, when running code via manage.py run_method? I can construct an artificial view around the code I am running, but it sure would be nice to just run my code directly. I swear I saw a SO question describing how to do this recently, but either I was mistaken or I'm unable to find it now. -
Register two models with one form
I'm looking for the best way to register two related models with one django form or model form. e.g. User and Profile models. An user has onetoone Profile. Actually django CreateView allows select the user from menu, I wanna register in one operation both. I also tried inheritance, from two model forms, but django only takes fields from first modelform. Any idea? -
Website Template and Admin panel template, work synchranously in different two apps, in one project in Django problem
I want to make process in front end and admin panel together as two apps in a project. I can easily get website content. But I cannot get admin panels interface. I get 404 error. I put static folder in main project files and set it up in main settings.py. Here is the main urls.py configuration: path('', include('home.urls')), path( 'panel/', include( 'panel.urls')), path( 'admin/', admin.site.urls ), This is panel app's url.py panel urls.py’a from .views import Panel urlpatterns = [ path(‘panel’, Panel, name=‘Panel’), ] [enter image description here][1] Identification of Static folder's in settings.py STATIC_URL = ‘/static/’ STATIC_ROOT = os.path.join(BASE_DIR, ‘static’) MEDIA_URL = ‘/img/’ MEDIA_ROOT = os.path.join(BASE_DIR,‘img/’) STATIC_DIRS = [os.path.join(BASE_DIR, “static”),] Could you please help me for solving this problem. Thanks in advance! -
How to create a dropdown navbar which is automatically updated (Django)
Hey guys how are you doing? I'm creating my portfolio and I'd like to do it using Django and now i need some help. I'm trying to create a navbar with a dropdown list that contains my projects and it is automatically update when I publish a new project. Now my project_list page already do this, and when I'm on it the navbar works as I want, but when I'm in another page it doesnt show any project. This is my model: from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model from django.utils import timezone from django.contrib.auth.models import User class Publish(models.Model): user = models.ForeignKey(User,null=True, on_delete=models.CASCADE ) author = models.CharField(max_length=256, null= True) name = models.CharField(max_length=256, null = True) description = models.TextField() create_date = models.DateTimeField(default=timezone.now) def published(self): self.create_date = timezone.now() self.save() This is my views.py from django.shortcuts import render,redirect, get_object_or_404 from django.views.generic import ListView, DeleteView, CreateView, TemplateView, UpdateView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import PublishCreateForm from publish.models import Publish from django.urls import reverse, reverse_lazy from django.views.generic.detail import SingleObjectMixin from django.utils import timezone class NavItems(object): def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context.update({ 'nav_items' : Publish.objects.all(),}) return context class ResumeView(TemplateView,NavItems): template_name = 'publish/resume.html' class PublishListView(ListView): model = Publish def get_queryset(self): … -
pip can't find django 3.x
whe I run: pip install django==3.05 I get Could not find a version that satisfies the requirement django==3.05 (from versions: 1.1.3, ... 2.2.11, 2.2.12) I need to update some references somewhere, but I am not sure how. Plz Help. -
django id foreagin key
I have client model and contact model with foreign key relation, i want to know to can I create the client and hist contact in the same time, I mean that how to get the client id which is the foreign key in client model while the creating of the client?? should I use Django signals or there is another way of doing this ?? models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def save_client_form(request, form,Contact_form, template_name): data = dict() if request.method == 'POST': if form.is_valid() and Contact_form.is_valid(): form.save() contact = Contact_form.save(commit=False) # contact.id = Contact_form.save() data['form_is_valid'] = True books = Client_Data.objects.all() data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', { 'client': books }) else: print(form.errors) print(Contact_form.errors) data['form_is_valid'] = False context = {'form': form,'contact_form':Contact_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def client_create(request): if request.method == 'POST': form = ClientForm(request.POST) contact_form = Contact_Form(request.POST) else: form = ClientForm() contact_form = Contact_Form() return save_client_form(request, form,contact_form, 'Client_Section/partial_client.html') forms.py class ClientForm(forms.ModelForm): class … -
Chart does not display on webpage in Django app (with Chart.js)
I am new to web development and I struggling with the frontend side of a django project. I have a dashboard template that I got from bootstrap and I want to integrate a chart that I made with chart.js. The charts works fine in another project but I cannot get it to display anything when it's a part of a dashboard. I attached my index.html as well as my plot.html and a sample of the data that I am trying to plot and the error I get in Chrome console <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin 2 - Dashboard</title> <!-- Custom fonts for this template--> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i' %}" rel="stylesheet"> <!-- Custom styles for this template--> <link href="{% static 'css/sb-admin-2.min.css' %}" rel="stylesheet"> </head> <body id="page-top"> <!-- Page Wrapper --> <div id="wrapper"> <!-- Sidebar --> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <!-- Sidebar - Brand --> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3"> Inventory Management <sup></sup></div> </a> <!-- Divider --> <hr class="sidebar-divider … -
django - models.ForiegnKey to the same model, to self
Peace be upon you! Currently, I'm working on my first django project, of course as all django developers, I have stumbled upon so many bugs, my current problem is that I want to set up comments system (DB, front-end, back-end), I have searched for a solution for this but no answer is found. this is my models: from django.db import models from datetime import datetime from django.contrib.auth.models import User class Comment(models.Model): # if I am a reply, so "comment" my parent comment, so each comment will have replies_set comment = models.ForeignKey('self', on_delete=models.CASCADE, default = '', related_name='replies') user = models.ForeignKey(User, on_delete=models.CASCADE, default='') value = models.CharField(max_length=100, default='') date = models.DateField(default = datetime.now()) def __str__(self): return self.value class Reaction(models.Model): comment = models.ForeignKey(Comment, on_delete=models.CASCADE, default = '') # the user that this love belong to user = models.ForeignKey(User, on_delete=models.CASCADE, default='') # type: like:0, love:1, laugh:2, cry:3, angry:4, ... TYPES = [ (0, 'like'), (1, 'love'), (2, 'laugh'), (3, 'cry'), (4, 'angry'), ] reaction_type = models.IntegerField(choices=TYPES, default=0) def __str__(self): return self.types[self.reaction_type][1] I want to make something similar to twitter comments, to reply forever not a thing such that in StackOverflow, to have a root post or question and comments with a reply for a user … -
Django Translation Internationalization and localization: forms, models, tables
I have two questions. How can I translate in forms: a) labels b) Form ValidationErrors ? forms.py from django import forms from django.db.models import Max, Min from .models import Application, FlowRate, WaterFilterSubType, Fineness, Dirt from .models import DirtProperties, Flange class InputDataWaterForm(forms.Form): '''Application''' choices = list(Application.objects.values_list('id','application')) application = forms.ChoiceField(choices = choices, initial="1", label="Specify application:") .... def clean(self): cleaned_data = super(InputDataWaterForm, self).clean() application = cleaned_data.get('application') ... '''OTHER CONDITIONS if not flowrate ...''' if not (flowrate or pressure or dirt or dirtproperties or application or fineness or temperature or flange or atex or aufstellung or ventil): raise forms.ValidationError('PLEASE ENTER THE REQUIRED INFO') How can I translate content of a table in a database? All records eg. product names in a table must be translated. models.py from django.db import models '''FILTER PROPERTIES LIKE COLOR''' class FP_sealing(models.Model): value = models.CharField('Material Sealing', max_length=10) descr = models.CharField('Description', max_length=200, default="") def __str__(self): return("Seal: " + self.value) Thank you -
Monkey Patch Django Components
Suppose we have a django component django.views.generic.base.ContextMixin I Want to replace it with my own ContextMixin without changing any imports. How to that in django ? I have tried it many ways, reassigning the class in manage.py, in project init, etc. Has anyone done it? In django where is proper place to do system wide patching? -
Template Language for Django which does not silently fail on exception?
I like django, the ORM, the admin, the community. But I don't like the handling of exception in the template language, like documented here: invalid template variables. Is there an alternative template variable where I always get an exception if something is wrong (even in production)? I prefer exceptions to "silently ignore errors". -
How can i use django groups for specific model?
does any body can help me to use Django groups for a specific model ? for example for blog app,in Entry model, can i add a field like this to have groups like sport,news and etc ? group = models.ForeignKey(groups,on_delete=models.CASCADE) (something like this) -
(.SVG, .PNG) not loading in react component
I am trying to load SVG and PNG images in my react app. I am running a back end server on Django. I always get this error when I try to load any Image. "GET /b5cde312e6d66e389b1ca2ccfc013da0.png HTTP/1.1" 404 2195 webpack.config.js { test: /\.(jpg|png|svg)$/, loader: 'url-loader', options: { limit: 25000, }, }, { test: /\.(jpg|png|svg)$/, loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', }, }, My component import React from 'react'; import '../App.css'; import Nav from '../components/Nav'; import Logo from '../logo512.png'; export default class Dev extends React.Component { render(){ return ( <div className="App"> <Nav /> <header className="App-header"> <div className="container"> <img src={Logo} alt="React Logo" /> </div> </header> </div> ) } } -
Why do I get a KeyError on a Model in Django?
I am getting a KeyError: 'conversation' on the line conv = ans.conversation in the code section: answers = Answers.objects.all() for ans in answers: conv = ans.conversation ... My model 'Answers' looks like this: class Answers(models.Model): conversation = models.ForeignKey(Conversation) ... I get the error sometimes, so if I run the code, I get the correct result a few times, but eventually within the for loop, sometimes the line conv = ans.conversation fails. Why do you think an error like this could ocurr? The entire error trace is here: Traceback (most recent call last): File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 164, in _get_ rel_obj = self.field.get_cached_value(instance) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'conversation' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/webapps/municipio/municipio/reportes/views.py", line 153, in get_whats_data conv = ans.conversation File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in _get_ rel_obj = self.get_object(instance) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 145, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 402, in get num = len(clone) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 256, in _len_ self._fetch_all() File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/query.py", line 55, in _iter_ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql cursor.execute(sql, params) File "/webapps/municipio/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute … -
Django Rest Framework: Pagination w/ ListModelMixin
I've been following the django-rest-framework documentation examples but I'm having trouble getting pagination to work when using a `ListModelMixin and viewsets.GenericViewset This does NOT paginate: class InvitesViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer def list(self, request): invited_users = self.get_queryset() # just did this as a test serializer = UserSerializer(invited_users, many=True) return Response(serializer.data) While this does: class InvitesViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer How can I return a custom list response (because I need to filter on the request.user) with pagination while using ListModelMixin? -
include sub html parts in one Django template
My project contains a lot of parts like header,footer,... that every part has it's own css/js libraries like below simple project: templates/master.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block css_links %}{% endblock %} <title>Test</title> </head> <body> {% block content %}{% endblock %} </body> </html> templates/part1.html: {% extends "master.html" %} {% load static %} {% block css_links %} <link rel="stylesheet" href="{% static 'css/style1.css' %}"> {% endblock %} {% block content %} <h2 class="content1">This is content1.</h2> {% endblock %} and another block like part2 with style2.css and content2 in h2 that both files included in Main.html below: templates/Main.html: {% include "part1.html" %} {% include "part2.html" %} and output is below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/style1.css"> <title>Test</title> </head> <body> <h2 class="content1">This is content.</h2> <meta charset="UTF-8"> <link rel="stylesheet" href="/static/css/style2.css"> <title>Test</title> <h2 class="content2">This is content.</h2> </body> </html> as you can see,part2 head parts like css link,meta and title wasn't loaded in head.what can I do? -
AttributeError at /register 'function' object has no attribute 'META'
I am new to using Django. So when I tried to create a register form I keep getting the error: AttributeError at /register 'function' object has no attribute 'META' from groups.forms import LoginForm, RegisterForm from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import UserCreationForm def register(response): if response.method == "POST": form = UserCreationForm(response.POST) if form.is_valid(): user = form.save() user.save() else: form = UserCreationForm() return render(request, 'register.html' , {"form":form}) This is the html code: {% load static %} {% include "includes/header.html" %} <br/><br/><br/><br/> <div class="container" align="center"> <div style="text-align: left; padding-left: 3%; width: 400px;"> <!-- Log in zone --> <form action="{% url 'register' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if next %} <input type="hidden" name="next" value="{{ next }}" /> {% endif %} <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title" align="center">Register</h3> </div> <div class="panel-body"align="center"> <div class="form-group has-primary"> {% csrf_token %} <input type="text" id="username" name="username" placeholder="Username" class="form-control" ><br/><br/> <input type="text" name="first_name" id="first_name" placeholder="First Name" class="form-control"><br/><br/> <input type="text" id="last_name" name="last_name" placeholder="Last Name" class="form-control" ><br/><br/> <input type="text" id="email" name="email" placeholder="Email" class="form-control" ><br/><br/> <input type="password" name="password" id="password" placeholder="Password" class="form-control"><br/><br/> <button type="submit" class="btn btn-primary">Register</button><br/><br/> </div> </div> </div> </form> </div> </div> <script src="/static/graphics/js/jquery.min.js"></script> <script src="/static/graphics/js/bootstrap.min.js"></script> <script src="/static/graphics/js/respond.min.js"></script> <script src="/static/graphics/js/bodypadding.js"></script> -
Since Django update, template rendering throws "'int' object has no attribute 'encode'"
After updating django I am now getting this error in a template rendering: int object has no attribute encode. I have checked that all of the variables sent to the template are str() except for one recordset. There is no occurrence of the string encode anywhere in the template. The error-stop in debug mode unhelpfully points at a <meta> tag at the top of the template. The error appears to be occurring somewhere inside the render() call. The only possibly-significant clue is that one line in the traceback is: response = self.process_exception_by_middleware(e, request) ... This software was working normally before the upgrade. It's now still fairly backwards, parked at Django 2.2. -
Django Static files loading failed
I am trying to load static files in my django project. but it isn't loading. My static folder is in the base directory of project . Here I am giving some relevant code. Here is my project's settings.py file's static part. STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assests') Here is the html part {% load static %} <img id="undraw_shared_workspace_hwky" src="{% static 'undraw_shared_workspace_hwky.png' %}"> My project name is 'webpage' and here is the image path. webpage\static\undraw_shared_workspace_hwky.png I have tried... manage.py collectstatic to collect the static files. It worked and gave me a assests directory inside or root directory. But when I go to the website it doesn't load the image. and the console says "Failed to load resource: the server responded with a status of 404 (Not Found)" . I am in a windows machine and using Django 3.0. Now I need you help to fix this problem. Thanks in advance. -
unable to use the variable in django
i recently started my django course online nad getting some problem. i am not able to use my variable which i passed from index.html to about.html. but in about.html it is not shown up. .py file code : from django .http import HttpResponse from django.shortcuts import render def index(request): return render(request , 'index.html') def about(request): t1 = print(request.GET.get('text' , 'default')) return render(request , 'about.html' , t1) index.html file code: <!DOCTYPE html> <html> <head> <title>template</title> </head> <body> <h1> hello everyone </h1> <form action="/about" , method="get"> <textarea name="text" style="margin: 0px; width: 1245px; height: 171px;"></textarea> <input type="submit" name="OK"> </form> </body> </html> about.html file code : <!DOCTYPE html> <html> <head> <title>template</title> </head> <body> <h1>you typed {{t1}}</h1> </form> </body> </html>