Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the use of __table_args__ = {'extend_existing': True} in Flask-SQLAlchemy?
I have a flask application which I'm trying to convert into Django. In one of the models which inherit an abstract base model, it is mentioned as __table_args__ = {'extend_existing': True} Can someone please explain what this means in SQLAlchemy with a small example. I have gone through few articles but as I worked on Django and new to Flask-SQLAlchemy I couldn't understand it properly. https://hackersandslackers.com/manage-database-models-with-flask-sqlalchemy/ https://docs.sqlalchemy.org/en/13/orm/extensions/declarative/table_config.html -
I want to get the vote button with proper functionality but i'm unable to do that...i tried but fail...help me please, how to do that
Actually i want vote button that works properly, when user clicks that button it should increase the number of votes there itself... views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from . models import Question, Choice from django.urls import reverse # Create your views here. def base(request): return render(request, 'base.html') def home(request): return render(request, 'home.html') def quest(request): question_list=Question.objects.all() context={'question_list': question_list} return render(request, 'quest.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.base, name='base'), path('home', views.home, name='home'), path('quest', views.quest, name='quest'), ] base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://kit.fontawesome.com/a076d05399.js"></script> <title>Voting World</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav ml-auto"> <a class="nav-item nav-link active" href="#">About us</a> <a class="nav-item nav-link active" href="#"><i class="fas fa-user"></i> Login</a> <a class="nav-item nav-link active" href="#"><i class="fas fa-sign-in-alt"></i> Signup</a> </div> </div> </nav> <div class="container"> {% block body %} {% endblock %} </div> </body> </html> quest.html {% extends 'base.html' %} {% block body %} {% if question_list %} <ul style="list-style: none;"> {% for question in question_list … -
Dynamic field logic
For example, on a product comparison site, each product does not have the same feature, so what I mean is that the car has the option of a gear while the phone has a memory option. Or in the lol tournament, teams fight with teams, but in fortnite players fight with players. The question is how do they keep it in the database. Can you send me a link to review how it's done? (Github project or Youtube video series) I'm new to web development and have no idea how it's done. -
Django, jwt authentication in django view, not just DRF
I'd like to use jwt with django (probably https://github.com/davesque/django-rest-framework-simplejwt) The library documentation and most web blogs on jwt talks about using jwt on DRF authentication. But we have Django regular views which are not DRF based. Can I still use one jwt authentication backend for both DRF and regular django views? -
Create dropdown select with image
I want to create a project that make user select countries in order to rate countries he/she want, how I can add flag to each country in dropdown list in django ? -
Not able to select many to many in Django admin as right selection pane not visible
I have a model which contains ManyToMany relationship. But when I go to admin and want to add object from admin, the right pane where selection goes is not visible. -
Django overriding detail view get method
This is my post detail view and it works perfectly. class PostDetailView(DetailView): model = Post context_object_name = 'post' template_name = 'posts/detail.html' def get_queryset(self, *args, **kwargs): request = self.request pk = self.kwargs.get('pk') queryset = Post.objects.filter(pk=pk) return queryset def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) content['comments'] = Comment.objects.all() return context However, when I add get method to the view it does not work anymore. def get(self, request, *args, **kwargs): # how to return here so that it works exactly like before After adding get method get_queryset and get_context_data do not gets called automatically and the context is empty in the template. So what would be the get method so that it works exactly like before? -
How can I load the last page only once?
It seems easy but somehow I couldn't wrap my head around it. So basically I have a Django pagination for the posts. Through API I get the number of the pages, and I want to load the last page once, but with this solution, the last page gets loaded into the dataSource once more. Function makeRemoteRequest = () =>{ const {page} = this.state setTimeout(()=>{ axios.get(URL+'/api/posts/?page='+page, {headers: {'Authorization':'Token '+this.props.screenProps.jwt}}) .then((response) => { this.setState({ dataSource: page===1 ? response.data.post : [...this.state.dataSource,...response.data.post], loading: false, refreshing:false, user: response.data.current_user, last_page: response.data.last_page, doRefresh:false }); handleLoadMore = () =>{ if(this.state.page >= this.state.last_page){ this.setState({ page: this.state.page + 1 },()=>{ this.makeRemoteRequest() }) } } -
The view ProjectManagementapp.views.product_insert_view didn't return an HttpResponse object. It returned None instead
"I'm going to make a project but getting httpresponse error in my code, what should i do for it?" from django.shortcuts import render from .models import ProductData from .forms import productInsertform,productdeleteform,ProductUpdateForm from django.http import HttpResponse def home(request): return render(request,'ProjectManagementapp/product_home.html') def product_insert_view(request): if request.method =="POST": iform = productInsertform(request.POST) if iform.is_valid(): Product_id1 = request.POST.get('product_id','') Product_name1 = request.POST.get('product_name', '') Product_cost1 = request.POST.get('product_cost', '') Product_color1 = request.POST.get('product_color', '') Product_class1= request.POST.get(' product_class', '') Customer_name1 = request.POST.get('customer_name', '') Customer_mobile1 = request.POST.get(' customer_mobile', '') Customer_email1 = request.POST.get(' customer_email', '') data = ProductData( product_id=Product_id1, product_name=Product_name1, product_cost=Product_cost1, product_color=Product_color1, product_class=Product_class1, customer_name=Customer_name1, customer_email=Customer_email1, customer_mobile=Customer_mobile1, ) data.save() iform = productInsertform() return render(request,'ProjectManagementapp/product_insert.html',{'iform':iform}) else: iform = productInsertform() return render(request,'ProjectManagementapp/product_insert.html',{'iform':iform}) -
load more button does not work in other divs
I have Load More button problem. I have a template. I want to load more button for my posts. I use jquery toggle but toggle is in another divs. Other divs blocked my toggle . I do not see . I guess height problem but I did not solve. This is my code ; <section class="pt-page" data-id="blog"> <div class="section-inner custom-page-content"> <div class="page-header color-1" style="background-image: url({% static 'media/general/sp_main_bg.png' %});"> <h2>Blog</h2> </div> <div class="page-content"> <!-- Blog Posts Grid --> <div class="blog-masonry two-columns gizli"> {% for article in hidden_articles %} <!-- Blog Post Hidden --> <div class="item"> <div class="blog-card"> <div class="media-block"> <a href="{% url 'blog:detail' article.slug %}"> {% if article.article_image_one %} <img class="post-image img-responsive" src="{{article.article_image_one.url}}" alt="{{article.title}}" /> {% endif %} <div class="mask"></div> <div class="post-date"><span class="day">{{article.created_date|date:'d'}}</span><span class="month">{{article.created_date|date:'F' }}</span><!--<span class="year">2016</span>--></div> </a> </div> <div class="post-info"> <ul class="category"> <li><a href="{% url 'blog:detail' article.slug %}">{{article.category.title}}</a></li> </ul> <a href="{% url 'blog:detail' article.slug %}"><h4 class="blog-item-title">{{article.title}}</h4></a> </div> </div> </div> <!-- End of Blog Post Hidden --> {% endfor %} </div> <div class="center download-resume"> <button id="loadMore">Daha Fazla Göster</button> </div> </div> </div> $(document).ready(function() { $("#loadMore").click(function () { $(".gizli").slideToggle(); }); $(".gizli").css("height").slideDown(); $(".section-inner.custom-page-content").css("height").slideDown(); }); Before click the load more button After click the load more button , actually it is work but toggle stay in … -
How can i filter a column in Django using .filter?
I have the following line: test = MyModel.objects.filter(user=request.user) The problem with this line is that it will retrieve the whole row. What if i want to retrieve the data from a certain column? For example, instead of the whole row, i'm trying to retrieve the column email I tried this, but it's not working: email = test.email -
How to extend Django's test database with custom SQL view?
I'm using Django 2.1 with MySQL. I have one custom SQL view, which is bound with a model with Meta managed = False. Django's TestCase has no idea how the view is created, so I'd like to provide SQL command to create this view. The best option would be to do this on database create, but I have no idea how to do that. What I've done so far was to override TestCase's setUp method. It looks like that: class TaskDoneViewTest(TestCase): def setUp(self): """ Create custom SQL view """ cursor = connection.cursor() file_handle = open('app/tests/create_sql_view.sql', 'r+') sql_file = File(file_handle) sql = sql_file.read() cursor.execute(sql) cursor.close() def test_repeatable_task_done(self): # ... def test_one_time_task_done(self): # ... I've got this solution from similar SO post: How to use database view in test cases. It would be a nice temporary solution, but the problem is with all those 2 test cases active I'm getting following error: $ python manage.py test app.tests Creating test database for alias 'default'... System check identified no issues (0 silenced). ...E.. ====================================================================== ERROR: test_repeatable_task_done (app.tests.test_views.TaskDoneViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/asmox/AppDev/Python/bubblechecklist/project_root/app/tests/test_views.py", line 80, in setUp cursor.execute(sql) File "/home/asmox/AppDev/Python/bubblechecklist/env/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/asmox/AppDev/Python/bubblechecklist/env/lib/python3.6/site-packages/django/db/backends/utils.py", line … -
expected string or bytes-like object error in django
When I add this class to my models.py I accord with the error that came in the title. my code is clear! do you see any problem there? class Turn(models.Model): Time=models.DateTimeField(null=True) Doctor=models.ForeignKey(Doctor,on_delete=models.CASCADE) Patient_FirstName=models.CharField(max_length=100) Patient_LastName=models.CharField(max_length=100) -
Two forms one view - Value is not coming from Form - Django
I have two forms and their models are related to each other and i am trying that both of them should get saved in database simultaneously. My one form (sim_form) will be updated while my other form (payment_form) will be saved using the same button. I am using django Crisp-forms and as far as display is concerned both forms are being rendered. Similarly, i am also able to fetch data of sim_form based on value received to it (pk=id). I am able to update data (save in database) in Sim model but value from Form is not coming into my Payment model, thats is why it gives me a validation error that "Column deposit_date cannot be null. I have tried different solutions, as you can see from the code below. def updatePayment(request, id): sim = get_object_or_404(Sim, pk=id) if request.method == "POST": print("i am in if1") payment_form = AddPaymentForm(request.POST) # payment_form = payment_form.save(commit=False) sim_form = UpdatePayment(request.POST, instance=sim) try: if sim_form.is_valid: print("i am in if") # payment_form = payment_form.save(commit=False) # sim_form = sim_form.save(commit=False) # payment_form.save() sim_form.save() messages.success(request, ("Payment has been updated")) if payment_form.is_valid(): print("i am in if paymemt") payment_form.save() else: messages.warning(request, ("Data in fields is incorrect, please try again")) except Exception as … -
'list' object has no attribute '_clone' after chaining 2 querysets
I have wrote custom search in django-admin to have 2 querysets with equal and contains matching in a row. I have used chain from itertools "queryset = list(chain(equal_qs, contains_sq))", cause "equal_qs | contains_sq" and "equal_qs.union(contains_sq)" not usable for me (they are mixing up results) def get_search_results(self, request, queryset, search_term): queryset, use_distinct = super(ProductAdmin, self).get_search_results( request, queryset, search_term) search_words = search_term.split() if search_term: equal_qs = queryset.filter( name__iexact=search_term).order_by('brand') obj_to_exclude = [o.id for o in equal_qs] contains_sq = queryset.filter( name__icontains=search_term).exclude( id__in=obj_to_exclude).order_by('brand') queryset = list(chain(equal_qs, contains_sq)) return queryset, use_distinct enter image description here -
How could I write test, wich test import data from csv file into db model via django admin user interface (used django-import-export app)
I write django unit test, which test import model data from csv file via admin (used django-import-export app). How could I send last filled form in the test? Load data via web browser admin user interface interactively work. 2 steps: Fill form with data (csv file and file format), and then send. In the response (html) is loaded data from csv file, for the verification. Next step is send verified data form. Test method: def test_profile_import(self): p = pathlib.PurePath(__file__) csv_file = p.parents[1] / 'test_data' / 'create_profiles.csv' fp = open(csv_file) address = '/aklub/profile/import/' post_data = { 'import_file': fp, 'input_format': 0, } # In this step data loaded from csv, and in the response (html) user verify if loaded data is correct) response = self.client.post(address, post_data, follow=True) self.assertEqual(response.status_code, 200) # Check data in the response self.assertContains(response, 'male', html=True) Response content: <form action="/aklub/profile/process_import/" method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="XhX3DPW5SOS5Zjn41DTBtjYAzl3Tp8FNq6djE4teFqFS7V1yWu4i9ZVK9P5JSevR"> <input type="hidden" name="import_file_name" value="/tmp/tmpjm300wjk" id="id_import_file_name"><input type="hidden" name="original_file_name" value="create_profiles.csv" id="id_original_file_name"><input type="hidden" name="input_format" value="0" id="id_input_format"> <p> Below is a preview of data to be imported. If you are satisfied with the results, click 'Confirm import' </p> <div class="submit-row"> <input type="submit" class="default" name="confirm" value="Confirm import"> </div> </form> <!--Loaded data from csv file for verification--> .... <!---> Next last … -
Django user foreignkey not saving the user
In my model i added the following line: user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, editable=False), so that when the form saves some data to that table, it will also save the user who saved that data. This is the entire model: class MyModel(models.Model): key = models.CharField(max_length=200) secret = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, editable=False) def save(self): # ALL the signature super(MyModel, self).save() When the user saves a key and a secret code, there should also be saved the user id of the user whose key it is. The problem with the actual code, is that instead of saving the id, i'm seeing a NULL below the user id column. I'm using the same system on another model and it works fine, can someone help me find the issue? This is the form: class MyForm(forms.ModelForm): key = forms.CharField() secret = forms.CharField() class Meta: model = MyModel fields = ("key", "secret") def save(self, commit=True): send = super(MyForm, self).save(commit=False) if commit: send.save() return send -
Get the different value from multiple elements with the same class in Selenium for Python?
I have an html code like this: <span class="class_name">10</span> <span class="class_name">20</span> <span class="class_name">32</span> the number (10, 20, 32) are variable, they could be 32, 56 and 65 in selenium I do: findclass = driver.find_element_by_class_name("class_name") now, my goal is take and assign number to variable like: var1 = 10 var2 = 20 var3 = 32 thank you -
Trouble with Dynamically Change Form Action Based on Select Option Using jQuery
There is a django project. The correct url should be inserted into the form, depending on the chosen option. For example, if option value="1" then the form action should be equal to {% url 'kiev_python_url' %}, if option value="2" then form action {% url 'kiev_javascript url' %} and so on. Jquery is loaded from the base.html template: <script type="text/javascript" src="{% static 'js/jquery-3.4.1.min.js'%}"> </script> The path to the jquery file 'static/js/' Thanks for any help! Tried: <script> $("#main-form").submit(function(){ if($("#language-field").val()==="1"){ $(this).attr("action","{% url 'kiev_python_url' %}"); } if($("#language-field").val()==="2"){ $(this).attr("action","{% url 'kiev_javascript_url' %}"); } }); </script> Tried: <script> $(document).ready(function() { $("#language-field").change(function() { var selected = $(this).children(":selected").text(); switch (selected) { case "Python": $("#main-form").attr('action', "{% url 'kiev_python_url' %}") break; case "Javascript": $("#main-form").attr('action', '{% url "kiev_javascript_url" %}'); break; case "Java": $("#main-form").attr('action', 'kiev_java_result.html'); break; case "C#": $("#main-form").attr('action', 'kiev_c_result.html'); break default: $("#main-form").attr('action', '#'); } }); }); </script> index-page-form.html <form action="" method="POST" class="mt-5 mb-5 text-center" id="main-form"> {% csrf_token %} <div class="form-row deep-purple-text"> <div class="form-group col-md-6"> <label for="language-field">Выберите язык:</label> <select class="form-control" id="language-field"> <option name="kiev_python" value="1">Python</option> <option name="kiev_javascript" value="2">Javascript</option> <option name="kiev_java" value="3">Java</option> <option name="kiev_c" value="4">C#</option> </select> </div> <button class="btn purple-gradient waves-effect btn-block mt- 3"type="submit">Поиск</button> </form> url.py from django.urls import path from .views import * urlpatterns = [ path('', index_page, name='index_page_url'), path('result/kiev_python/', kiev_python, name='kiev_python_url'), … -
CustomUserManager is not called when creating new user from admin
My problem is that I have created a CustomUserManager, and override the create_user and create_superuser functions. The problem is that any of those functions are not called when I create a new user from admin page. If I create a superuser from console, with the command python manage.py createsuperuser the function create_superuser from my CustomUserManager is called. I have created a CustomUser that inherits from AbstractUser. Alose I have created a CustomUserManager that inherits from BaseUserManager. This is the CustomUserManager class # managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): # Stuff def create_superuser(self, email, password, **extra_fields): # Stuff This is the CustomUser, that sets object to CustomUserManager # models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] objects = CustomUserManager() def __str__(self): return self.email Also I have two forms for my CustomUser, to edit or create a new user. class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('email',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('email',) Finally I have created a CustomUserAdmin class where I set the add_form, form and the … -
Unable to register a user in django deployement on heroku?
I've deployed a django-blog web-app on heroku. Its working but with an error. When i register a new user it says user created but when I try to login through registered user it says username and password didn't match. And when I login in my admin panel then the user i registered wasn't created at all. Here's my settings.py file import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'myblog/media') SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = False ALLOWED_HOSTS = ['mydjangoblogapp.herokuapp.com'] INSTALLED_APPS = [ 'blogapp.apps.BlogappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myblog.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'OPTIONS':{ 'max_similarity': 1, } }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_TMP = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS … -
Empty and partial dropdown list displayed when loading data from AJAX call via API; and how to POST data?
I have a Django form on which users will be able to input data about a musical composition. Among the various fields there's also a 'performances' one, which is a formset, with venue, date, notes, and link. The 'venue' field is a select2() dropdown list: if the venue is not already in the database the user must be able to add a new one. I initially thought of giving this possibility by adding a button 'add new venue', which opens a modal containing a mini-form with just one field, where the user can input the name of the new venue. I've achieved this with a XHR call. Nevertheless, what if the user wants to easily change the venue name, or delete it? That's why I thought of using select2()'s tags:true option and use API calls (I'm using tastypie) via AJAX for both GET and POST. My template: [...] <h3>Performances</h3> <table id="performancesnodb"> <tbody id='performancesnodb_body'> {% for formPerformance in form_performances.forms %} <tr id="row-performancesnodb-{{forloop.counter0}}" class="formPerformances"> <td><select class="selectVenue" name="{{ formPerformance.venue.html_name }}" data-thisId="{{formPerformance.venue.id_for_label }}" id="{{formPerformance.venue.id_for_label }}"> <option value="-1">----</option> </select> </td> [... other fields like link, notes] <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url: "http://127.0.0.1:8000/api/venue/", type: "GET", success: function(data, textStatus, jqXHR) { var xdata = data.objects.map(function(item){ return {value: … -
Filter creation in django filter
Can Anyone describe me these part of Django-filter package. I can't understand the three method decribed here -
How to change user password programmatically in django?
I use another app api to login. and every user I don't have in my database login I add them. but if they change their password in that app how can I change their password in my User model? I use postgreSql and django2.2 my custom User Model from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) class UserManager(BaseUserManager): def create_user(self, username, password=None, is_active=True, is_accountant=False, is_admin=False): if not username: raise ValueError("Users must have username") if not password: raise ValueError("Users must have password") user_obj = self.model() user_obj.username = username user_obj.set_password(password) # change user password user_obj.accountant = is_accountant user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def change_pass(self, nPassword): user = self.model() user.set_password(nPassword) return user def create_accountantuser(self, username, password=None): user = self.create_user( username, password=password, is_accountant=True ) return user def create_superuser(self, username, password=None): user = self.create_user( username, password=password, is_accountant=True, is_admin=True ) return user class User(AbstractBaseUser): username = models.CharField(max_length=255, unique=True) active = models.BooleanField(default=True) # could login or not accountant = models.BooleanField(default=False) # accountant admin = models.BooleanField(default=False) # SuperUser USERNAME_FIELD = 'username' object = UserManager() def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_active(self): return … -
How can I add request.user.username in django.server logger records?
I'm trying to include request.user.username in my django project default loggers' records. So I tried to add a custom filter and add the user field in my log record. But I got in trouble and need your help! Here is my logging configuration dict: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[{server_time}] @{user} {message}', 'style': '{', } }, 'filters': { 'request_user_filter': { '()': 'carpooling.filters.RequestUserFilter' }, }, 'handlers': { 'django.server': { 'level': 'INFO', 'filters': ['request_user_filter'], 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'loggers': { 'django.server': { 'handlers': ['django.server', 'mail_admins'], # logfile 'level': 'INFO', 'propagate': False, }, } } And this is my custom formatter: class RequestUserFilter(logging.Filter): def filter(self, record): if record.request.user.is_anonymous: record.user = 'Anonymous' else: record.user = record.request.user.username return True When I request to 127.0.0.1:8000/ on my browser, I expect to see the [25/Aug/2019 11:44:54] @Anonymous "GET / HTTP/1.1" 200 1868 record on console but I get the following error: Traceback (most recent call last): File "/usr/lib/python3.6/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.6/wsgiref/handlers.py", line 183, in finish_response self.close() File "/home/mohsen/.virtualenvs/carpooling/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 111, in close super().close() File "/usr/lib/python3.6/wsgiref/simple_server.py", line 35, in close self.status.split(' ',1)[0], self.bytes_sent File "/usr/lib/python3.6/http/server.py", line 536, in log_request self.requestline, str(code), str(size)) File "/home/mohsen/.virtualenvs/carpooling/lib/python3.6/site-packages/django/core/servers/basehttp.py", …