Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django logger does not log below warning level on server
I cannot get the django logger log below WARNING level on my web server. The below configuration logs as intended on localhost dev server, but not on my web server (Nginx, gunicorn). The log file as defined in the file handler is created and logs are written to it, but only logs of level WARNING and above. My goal is to log INFO level logs as well (such as GET requests). I found this discussion (https://stackoverflow.com/questions/65362608/), but it didn't help. I tried configuring root logger for INFO level by adding '': {#same settings as in below django logger} to loggers, but that did not have any effect. I restarted both Nginx and gunicorn. #in settings.py DEBUG = False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/django.log', 'formatter': 'detailed' }, 'mail': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], } }, 'loggers': { 'django': { 'handlers': ['file', 'mail'], 'level': 'INFO', 'propagate': True, }, }, } Any ideas what might be causing the issue? -
How to put appropriate keyboard after clicking on the form in Django?
I just built one app, but that app needs language that is not English to type in.I want user to get a keyboard of that language after clicking the text field to type something. Is that possible in Django? When I don't have any keyboard, my Android just gives me English keyboard, which is not what I want. I don't want to change in settings. I want my user in any part of the world to get as a user experience keyboard of that language, no matter is it on computer or on mobile device. -
how can i implement django input form with the default values
writing an online store I have a form to add items to cart with different quantities. I have implemented this through "TypedChoiceField": class CartAddProductRetailForm(forms.Form): quantity = forms.TypedChoiceField( choices=PRODUCT_RETAIL_QUANTITY_CHOICES, coerce=int, label='quantity', ) But it looks ridiculous. Can you tell me how to implement it with a "CharField" or "DecimalField" with a default '1' value. quantity = forms.DecimalField(max_value=999, min_value=1, ) Thanks! -
How to display the category 1 item into category 2 based on UID in Django Model?
How to display the category 1 item into category 2 based on UID in Django Model? Category_1: UID Item 1 A 1 B 2 C 2 D expected result: Category_2: UID Category_1 Cateogry_1_Des 1 1 A 2. 1. B 3. 2 c 4. 2. D Model coding (show all item of category_1 but want to show only item mathcing UID) : Category_2 = models.ForeignKey( Category_1, verbose_name=_('cat2'), related_name='cat2' ) -
Get Queryset Django based on another one
Have this model: class Review(models.Model): RATING_VALUES = [ ('1', 'Ужасно'), ('2', 'Плохо'), ('3', 'Сносно'), ('4', 'Хорошо'), ('5', 'Отлично'), ] spare_part = models.ForeignKey('SparePart', on_delete=models.PROTECT, verbose_name="Запчасть") mileage = models.SmallIntegerField(verbose_name="Пробег, тыс.км") car_brand = models.ForeignKey('CarBrand', on_delete=models.PROTECT, verbose_name="Марка авто") car_model = models.ForeignKey('CarModel', on_delete=models.PROTECT, verbose_name="Модель авто") owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Владелец") rating = models.CharField(max_length=1, choices=RATING_VALUES, verbose_name="Рейтинг", default=3) testimonial = models.TextField(max_length=1000, blank=True, verbose_name="Отзыв") likes = models.ManyToManyField(User, related_name='like', default=None, blank=True, verbose_name="Лайки") like_count = models.BigIntegerField(default='0', verbose_name="Кол-во лайков") date = models.DateTimeField(default=now, verbose_name='Дата') In views.py I get all User reviews like this: user_reviews = Review.objects.filter(owner_id=request.user.id).order_by('spare_part', 'spare_part__category_id') And now I need to get all the Review objects which current user liked. I do it this way, but get an error "Cannot use QuerySet for "Review": Use a QuerySet for "User"." user_liked = Review.objects.filter(likes__in=user_reviews) How to di it right? -
Am trying to create a date field where a user can select when to set an appointment with a worker. Am only getting a blank field with no Date picker
class Appointment(models.Model): CATEGORY = ( ('Plumbing', 'Plumbing'), ('Electrical', 'Electrical'), ('Cleaning', 'Cleaning'), ) STATUS = ( ('Pending', 'Pending'), ('Delivered', 'Delivered'), ) user = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL) worker = models.ForeignKey(Worker, null=True, on_delete=models.SET_NULL) category = models.CharField(max_length=200, null=True, choices=CATEGORY) task_date = models.DateField(_("Task Date"), blank=True, null=True) task_location = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) task_description = models.CharField(max_length=1000, null=True) def __str__(self): return str(self.user) forms.py file class AppointmentForm(ModelForm): class Meta: model = Appointment fields = '__all__' exclude = ['user','worker','status'] widgets = {'task_date': forms.DateInput(format='%d/%m/%Y')} -
Django & React: Connecting multiple apps from one template
Good morning, I would like to ask, if it's possible to connect multiple apps in django, each using his own react frontend? For example: I have one main page that holds all the links to the different applications... Folder-Structure: |- project | |- app_main | | |- templates | | | |- app_main | | | | |- main.html | |- app_1 | | |- frontend_1 (react) | | | |- public | | | | |- index.html | |- app_2 | | |- frontend_2 (react) | | | |- public | | | | |- index.html As I understood - or at least I think so -, the folder holding the html-files have to be included inside the template in settings.py... settings.py REACT_ROUTE_APP_1 = os.path.join(BASE_DIR, 'app_1', 'frontend_1', 'public') REACT_ROUTE_APP_2 = os.path.join(BASE_DIR, 'app_2', 'frontend_2', 'public') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ REACT_ROUTE_APP_1, REACT_ROUTE_APP_2 ], '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', ], }, }, ] Is this the right way or is there a much better solution? And if it's the right choice, how can I connect the url-route inside my ? main.html <div> <a href="?">Link to App 1</a> <a href="?">Link to App 2</a> </div> … -
I am creating a TodoApp using Django3.2 and React js and I got the error: cannot import views
I am creating a Todo App using Django 3.2 with python 3.6.8 and react js. I have installed the djangorestframework and Django-cors-headers. However, I cannot get the App views. I could not do the migration as well. I got the following error when I try to run the server: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen … -
How to update the content of a div after an AJAX call
I have a div (<div class="card-body">) and I want to put elements inside from the database (the elements are retrieved via AJAX call) But I need something dynamic since I will be adding content dynamically and apparently Django template tags are not enough. How can I do something like that from the ajax success function? index.html: {% extends 'base_generic.html' %} {% load static %} {% block content %} {% get_current_language as LANGUAGE_CODE %} <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: '/todo_ajax/', type: 'get', success: function(data) { alert(data); }, failure: function(data) { console.log('Got an error dude'); } }); }); </script> <div class="wrapper"> <!-- Index Content --> <div id="content"> <div class="row row-cols-1 row-cols-md-3 g-4 mb-5"> <div class="col"> <div class="card h-100"> <div class="card-header" id="toDoHeader"> ... (truncated) </div> <div class="card-body"> {% for o in some_list %} <div class="cardItem cardItemIndex" class="mb-3"> <div class="row"> <div class="col"> <h6 class="card-title">{{ o.title }}</h6> </div> </div> <div class="row"> <div class="col"> <p class="card-text">{{ o.description }}</p> </div> </div> <p class="card-text to-do-footer">{{ o.start_date }} - {{ o.end_date }}</p> </div> {% endfor %} </div> </div> </div> </div> </div> </div> {% endblock %} views.py @login_required def todo_ajax(request): response = dict() if request.method == 'GET': to_do_list = ToDoList.objects.all().filter(user=request.user) data = serialize("json", to_do_list) return HttpResponse(data, content_type="application/json") return … -
django, python why timestamp changes after localize
CODE: import pytz from django.utils import timezone KST = pytz.timezone('Asia/Seoul') UTC = pytz.timezone('UTC') default_time = timezone.datetime(2021, 11, 29, 16, 44) current_manual_kst = KST.localize(default_time) current_manual_utc = default_time print(current_manual_kst.timestamp()) print(current_manual_utc.timestamp()) RESULT: >>> 1638171840.0 >>> 1638204240.0 So, I can see that results are different. I thought timestamps should be the same but results are not. Why this happened? And How to get the same timestamps (by default: UTC) from KST.localized datetime? -
SMTPSenderRefused getting this error while requesting the forget password
Getting the below error when I submit user's email address to get the password reset link the below pic is settings.py file -
How are all serializer errors returned in DRF at once?
I'm testing for multiple validation errors to be raised in(UserRegistrationSerializer). Yet DRF only returns the first error that is raised: {'username': [ErrorDetail(string='Choose a different username', code='invalid')]} I'm expecting: {'username': [ErrorDetail(string='Choose a different username', code='invalid')], 'password2': [ErrorDetail(string='Password confirmation failed', code='invalid')] How can multiple errors be accounted for once a serializer is validated as in the documentation example? https://www.django-rest-framework.org/api-guide/serializers/#validation class TestRegisterationSerializer__002(TestCase): '''Verify that the registeration process fails with respect to selecting an unavailable username and password confirmation''' @classmethod def setUpTestData(cls): User.objects.create_user(username="Python") cls.data = { 'username': "Python", 'password': "#secret#", 'password2': "Secret" } cls.error_messages = [ "Choose a different username", "Password confirmation failed" ] cls.serializer = UserRegisterationSerializer(data=cls.data) def test_user_registeration_invalid_confirmation(self): self.serializer.is_valid() print(self.serializer.errors) import re from django.contrib.auth.models import User from rest_framework import serializers class UsernameSerializer(serializers.ModelSerializer): username = serializers.SlugField(min_length=4, max_length=12) def validate_username(self, value): try: self.Meta.model.objects.get(username__iexact=value) except self.Meta.model.DoesNotExist: return value raise serializers.ValidationError("Choose a different username") class Meta: fields = ['username', ] model = User class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username, password = [ input.lower() for input in [data['username'], data['password']] ] if all(password[i] == password[i + 1] for i in range(len(password) - 1)) or username == password: raise serializers.ValidationError({ 'password': "Invalid password" }) return data class Meta: fields = ['username', 'password', ] … -
Grouping model field names in Django
I have a complex detail view where a lot of varied data is rendered dynamically. My model has hundreds of fields, many of which are related to one another. I would like to be able to group a number of these fields in order to do queries. Is there are way to do this? In order to cherry-pick specific fields and group them, my current approach has been to use word extensions to the field names that is common for each group. For example, field names like: ampicillin = models.CharField(...) ciprofloxacin = models.CharField(...) ... become: ampicillin_antimicro = models.CharField(...) ciprofloxacin_antimicro = models.CharField(...) ... The idea is then to create a field name list and access specific groups of fields using a substring search. How am I to do this? Below is a summary of my attempts and issues so far. Using _meta I can access the raw model field name information using _meta: all_fields = [] for field in MyModel._meta.fields: all_fields.append(field) This gives a list like: [<django.db.models.fields.CharField: ampicillin_antimicro>, <django.db.models.fields.CharField: ciprofloxacin_antimicro>, ...] but I've not been able to figure out how to extract the information I need from this, however. Using _meta and field.get_attname_column()[0] I can make a list of field name … -
How can I rewrite an average value per datet time interval MySQL query as a Django QuerySet
I have the following MySQL query that displays the average value per 10 minute interval: SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(date_time) / 600) * 600) AS interval_date_time, AVG(some_value) AS avg_value FROM djangoapp_somemodel GROUP BY interval_date_time ORDER BY interval_date_time; For example, if I have the following 3 records: date_time some_value 2021-11-29 00:11:01 10 2021-11-29 00:16:15 20 2021-11-29 00:24:32 25 The query will output the following: interval_date_time avg_value 2021-11-29 00:10:00 15 2021-11-29 00:20:00 25 I suspect the query isn't that efficient but I want to get the same output using a Django QuerySet. Here's what I have so far: (SomeModel.objects .annotate(interval_date_time=F("date_time")) .values("interval_date_time") .annotate(avg_value=Avg("some_value")) .order_by("interval_date_time") ) I believe I need to make changes to the first annotate method call. Any help would be appreciated. -
How do I import views.py to my project urls file
I am working with Django and trying to do a login system The app is supposed to deliver a simple 'Login System'-view but my_app/urls.py fails to import methods from my_app/views.py. My app name is authentication Here is my-project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('authentication.urls')), ] Here is my_app/urls.py. from django.contrib import admin from django.urls import path, include from authentication import views urlpatterns = [ path('', views.home, name="home"), path("signup", views.signup, name="signup"), path("signin", views.signup, name="signin"), path("signout", views.signup, name="signout"), ] Here is my-app/views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, "authentication/index.html") I have also added this in my-project/settings.py 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR /"templates"], 'APP_DIRS': True, And I get the following error TemplateDoesNotExist at / authentication/index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.9 Exception Type: TemplateDoesNotExist Exception Value: authentication/index.html Exception Location: C:\Users\julie\Login System\venv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\julie\Login System\venv\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\julie\\Login System', 'c:\\python39\\python39.zip', 'c:\\python39\\DLLs', 'c:\\python39\\lib', 'c:\\python39', 'C:\\Users\\julie\\Login System\\venv', 'C:\\Users\\julie\\Login System\\venv\\lib\\site-packages'] -
"detail": "Method \"GET\" not allowed." i have not set it as GET so why is it showing this error
i am trying yo create a new item but i am getting "detail": "Method \"GET\" not allowed error on page of django rest framework and 405 (Method Not Allowed) error in console views.py: def create_person(request): serializer = PersonSerializer(data=request.data, many=False) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) urls.py urlpatterns = [ path('', views.getRoutes, name='routes'), path('notes/', views.getNotes, name='notes'), path('notes/create/', views.createNote, name='create-note'), path('notes/<str:pk>/update/', views.updateNote, name='update-note'), path('notes/<str:pk>/delete/', views.deleteNote, name='delete-note'), path('notes/<str:pk>/', views.getNote, name='note'), ] -
Download pd dataframe to csv dynamically with django
Created an django website which scrapes the github repo and show it as table . That table data is dataframe. So, i want that dynamic user data to be downloaded as csv when user clicks the button or url. I have not used any models and all. How it can be done in a simple way ? This is hosted website RepoLoader. I don't know the right method to do that. -
Why am i getting this error when i run python manage.py shell in terminal?
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to -
Share Models Between Two Different Django Projects
I have two different Django projects which should be using exactly the same db & same models and working on different servers. I don’t want to define same models twice in both apps since the models might change and changes should be done on both sides. What would be the best solution to define models once and use the same models in both projects? -
Django query fail using diacritic
My ListView in Django is: class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username = self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') When User ID contains lettes like č, ć, š, it fails with: GET http://myapp.local/user/ITeri%C4%87 404 (Not Found) How can I fix this? I use same code on my PC and it works. I uploaded the same code to the company server and only this wont work. -
I am getting the date instead of date and time data in a POST request
I have a date range picker on my website. When a user inputs the date and time range, I want to send separately within the form the startDate and the endDate daterangepicker code: $('input[name="datetimes"]').daterangepicker({ timePicker: true, timePickerIncrement: 5, startDate: moment().startOf('hour'), endDate: moment().startOf('hour').add(32, 'hour'), locale: { format: 'YYYY-MM-DD hh:mm' }, opens: 'center', drops: 'auto' }); And this is what I tried: $('#formid').submit(function(e) { e.preventDefault(); let startDate = ($('#datetimes').data('daterangepicker').startDate).format('YYYY-MM-DD hh:mm'); let endDate = ($('#datetimes').data('daterangepicker').endDate).format('YYYY-MM-DD hh:mm'); $(this).append('<input type="hidden" name="start_date" value='+startDate+' /> '); $(this).append('<input type="hidden" name="end_date" value='+endDate+' /> '); this.submit(); }); Before the this.submit(); I did a console.log(startDate) and thi is what I am getting: I am getting the date and the time (as expected), but then if I try doing a print(request.POST) in the view (django back-end), this is what I get: Somehow, during the POST the HH:mm disappeared. How can I keep the values of hh:mm during the POST? -
DJANGO multi db transaction with nested transaction.atomic
I've been searching a good way to implement cross db transaction in DJANGO, but there seem to be no good answer. I did see this post Django transaction using multi-db which suggested using nested trasaction.atomic(using='different_data_base_name'). However I wonder how does this work. With each nested block, django identifies a different connection, and all the checks and operations are performed specific to this connection, so I think the nested transaction.atomic could not guarantee cross-db transaction. Could someone help me understand why the nested transaction.atomic could work? Or if not, any suggestions on how to go about it? -
Automatically generate chatroom when onclick button
I wanna make a chat app that when clients click on the button, they will connect and chat with the admin. Each admin has a button only and he can chat with many clients. Each client can chat with many admin too. 1 chatroom has only 2 users (admin+client). My solution is when clients click the button, it will generate a chatroom and add user_id of admin and client into its. But now I'm struggling to find way to automatically generate a chatroom with random id or name. Hope you guys can help me <3 -
How can I create a unique primary integer key of fixed length?
I want Django to automatically create a unique key of fixed length. This is what I have so far: card_id = models.AutoField(primary_key=True) This method will create keys starting from a very low number and it is not of fixed length. I want to have it a fixed length of 7 chars/digits and have it be composed of integers (a string with number chars is fine as well) e.g. 1543534. I call this from views.py to create a new entry in the database: BORROWER.objects.create(ssn=Ssn, bname=Name, address=Address, phone=Phone) Notice that card_id is not specified, so I want to have Django auto-create it. -
python manage.py takes too much time to run in Django
I am working on Python rest framework and after setting up python 3.8.12 on my mac, when I tried to up the server with python manage.py runserver command for Django, it takes around 2 minutes and in-between it gives some connectionpool logs described as below. 2021-11-26 11:24:04,249 DEBUG urllib3.connectionpool : Starting new HTTP connection (1): 169.254.169.254:80 2021-11-26 11:24:05,252 DEBUG urllib3.connectionpool : Starting new HTTP connection (2): 169.254.169.254:80 2021-11-26 11:24:06,586 DEBUG urllib3.connectionpool : Starting new HTTP connection (3): 169.254.169.254:80 2021-11-26 11:24:07,590 DEBUG urllib3.connectionpool : Starting new HTTP connection (4): 169.254.169.254:80 2021-11-26 11:24:09,527 DEBUG urllib3.connectionpool : Starting new HTTP connection (1): 169.254.169.254:80 2021-11-26 11:24:09,528 DEBUG urllib3.connectionpool : Starting new HTTP connection (2): 169.254.169.254:80 2021-11-26 11:24:09,821 DEBUG urllib3.connectionpool : Starting new HTTP connection (3): 169.254.169.254:80 2021-11-26 11:24:09,822 DEBUG urllib3.connectionpool : Starting new HTTP connection (4): 169.254.169.254:80 2021-11-26 11:24:10,154 DEBUG urllib3.connectionpool : Starting new HTTP connection (5): 169.254.169.254:80 2021-11-26 11:24:10,155 DEBUG urllib3.connectionpool : Starting new HTTP connection (6): 169.254.169.254:80 Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. This is a headache because every time it takes this much time for any change. I can't find any solution over web. Please Help. All solutions are welcomed. Thanks in advance ;)