Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrate from CharField to LocalizedCharField
I am integrating django-localized-fields and have to save current data in char field at least in default language. For example: from django.db import models class FineModel(models.Model): title = models.CharField(max_length=128) needs to migrate to from localized_fields.models import LocalizedModel from localized_fields.fields import LocalizedCharField class FineModel(LocalizedModel): title = LocalizedCharField(blank=True, null=True, required=False) and text from title column should be transferred to updated title column like that: new_obj.title.en = old_obj.title I tried to add new temporary field title_l and use 3 migrations to transfer all data from title field to title_l field delete title field rename title_l to title and delete title_l from model but this is not working, because first of these migrations will fail on production contour because title_l is not presented in FineModel. Any advices appreciated, I believe this can be done in single migration. -
How to render react images on django
After developing my react application, i decided to render it in my django using the npm run build command, which I have successfully done and it's working efficiently. But the only problem is that my images are not being rendered. Please any suggestion on how i can make django render my images. Django keeps saying this "Not Found: /images/blog/b2.webp [08/Aug/2023 17:43:02] "GET /images/blog/b2.webp HTTP/1.1" 404 3104" each time the app runs I created a static root to render all static files and also a media root for all media files. Here is the code STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'reactapp/myschool/build/static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'reactapp/myschool/build/media') -
Custom authentication backend works but doens't work with Django Rest's Token Authentication
My User model has an email field and a username field. `USERNAME_FIELD' is set to email. But I wrote an authentication backend to also support logging in using username: class UsernameAuthBackend(BaseBackend): def authenticate(self, request, email=None, password=None): try: user = User.objects.get(username=email) if user.check_password(password): return user return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None settings.py: AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "accounts.authentication.UsernameAuthBackend", ] This works fine but it I can't use usernames with obtain_auth_token to get a user's token. (It also doesn't work on Django's admin panel.) -
For my perceptrons, I need to know the session duration per user
For my perceptrons, I need to know the session duration per user, the visited links, etc. The issue with these two elements is that I'm having trouble; JavaScript must capture this information, and upon exiting the website, send it to Django so that my AI can aggregate them later. var centi = 0; var mili = 0; var sec = 0; var sec_; var afficher; var compteur; var reglage; function updateDisplay() { if (sec < 10) { sec_ = "0" + sec; } else { sec_ = sec; } afficher = sec_ + ":" + centi + mili; document.getElementById("time").innerHTML = afficher; } function chrono() { reglage = setInterval(function() { mili++; if (mili > 9) { mili = 0; centi++; if (centi > 9) { centi = 0; sec++; } updateDisplay(); } }, 100); updateDisplay(); } function arret() { clearInterval(reglage); document.parametre.lance.disabled = ""; document.parametre.pause.disabled = "disabled"; document.parametre.zero.disabled = ""; document.parametre.intermediaire.disabled = ""; document.parametre.rappel.disabled = ""; } function raz() { clearInterval(reglage); document.parametre.zero.disabled = "disabled"; document.parametre.intermediaire.disabled = "disabled"; document.parametre.rappel.disabled = "disabled"; centi = 0; mili = 0; sec = 0; compteur = ""; updateDisplay(); document.getElementById('presenter').style.visibility = 'hidden'; document.getElementsByName('intermediaire')[0].style.backgroundColor = 'rgba(50,205,50, 0.25)'; } function inter() { compteur = document.getElementById("time").innerHTML; document.getElementsByName('intermediaire')[0].style.backgroundColor = "orange"; } function … -
Django: TruncDate datetime retunrs always datetime
I'm using Django 3.2.12 and mysql 8.0.27 for Win64 on x86_64 (MySQL Community Server - GPL) and have this models class Anomalie(models.Model): dateajout = models.DateTimeField(auto_now_add=True, null=True) I am trying to get all Anomalie per day so I'm using this: items = Anomalie.objects.annotate(date=TruncDate('dateajout')).values('dateajout').annotate(count=Count('id')).values('dateajout', 'count') but I get this when I print items: <QuerySet [{'dateajout': datetime.datetime(2023, 7, 4, 1, 58, 15, 509978, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 7, 10, 12, 56, 9, 682396, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 7, 11, 12, 23, 54, 838830, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 7, 12, 13, 5, 38, 557618, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 8, 6, 3, 57, 31, 69749, tzinfo=), 'count': 1}, {'dateajout': datetime.datetime(2023, 8, 6, 14, 15, 38, 704047, tzinfo=), 'count': 1}]> As you can see, I always get "'count': 1", even if 2 anomalies were created on same day (2023, 8, 6)... I think it's because TruncDate returns a datetime instead of a date... I searched on many forums like https://forum.djangoproject.com/t/problem-with-count-and-truncdate/10122 or Formatting dates for annotating count in Django + Python 3 but I don't know what I'm doing wrong... Any idea please? -
customize django admin whith jquey dosent work
i have a model in my django project for phone types .I want to hide the count of phone when phone is not available . i used jquery but it dosent work and i dont now why . if u can pls help me . this is my model class PhoneModel(models.Model): phone_brand = models.ForeignKey('Brand', on_delete=models.CASCADE, verbose_name="برند") phone_model = models.CharField("مدل تلفن همراه", max_length=300 ,unique=True) price = models.IntegerField("قیمت", validators=[ MinValueValidator(0, "مقدار مورد نظر باید بیشتر از 0 باشد") ]) color = models.CharField("رنگ محصول",max_length=200) phone_size = models.IntegerField("سایز گوشی همراه", validators=[ MinValueValidator(0, "مقدار مورد نظر باید بیشتر از 0 باشد.") ]) availability = models.BooleanField("موجود", default=False) count = models.IntegerField("تعداد",blank=True, validators=[ MinValueValidator(0, "مقدار مورد نظر باید بیشتر از 0 باشد") ]) country = models.CharField("کشور", max_length=300) def __str__(self): return self.phone_model class Meta: db_table = 'phone' verbose_name = 'گوشی' verbose_name_plural = 'گوشی ها' this is my jquery code: (function($) { $(document).ready(function() { var $availability = $('#id_availability'); var $count = $('#id_count'); function toggleCharFieldVisibility() { if ($availability.is(':checked')) { $count.parent().show(); } else { $count.parent().hide(); } } toggleCharFieldVisibility(); $availability.on('change', toggleCharFieldVisibility); }); })(django.jQuery); and at last this is my admin.py: @admin.register(PhoneModel) class PhoneAdmin(admin.ModelAdmin): list_display = ["phone_model", "phone_brand"] class Media: js = ("phone/js/custom_admin.js",) i found this jquery code from web and dont now few … -
`no tests ran` in Pytest in Django
I have test1_ex.py in tests/ as shown below. *I use Pytest in Django: django-project |-core | └-settings.py |-my_app1 |-my_app2 |-tests | |-__init__.py | |-conftest.py | └-test1_ex.py # Here |-pytest.ini ... And, this is pytest.ini: # "pytest.ini" [pytest] DJANGO_SETTINGS_MODULE = core.settings python_files = test_*.py And, there is fixture1() in tests/conftest.py as shown below: # "tests/conftest.py" import pytest @pytest.fixture def fixture1(): print('fixture1') And, there is test1() in tests/test_ex1.py as shown below: # "tests/test_ex1.py" import pytest def test1(fixture1): print('test1') Now, I ran the command below: pytest -q -rP Then, I could run test1() as shown below: $ pytest -q -rP . [100%] ============================================ PASSES ============================================ ____________________________________________ test1 _____________________________________________ ------------------------------------ Captured stdout setup ------------------------------------- fixture1 ------------------------------------- Captured stdout call ------------------------------------- test1 1 passed in 0.11s Next, I put test1_ex.py in tests/test1/ as shown below: django-project |-core | └-settings.py |-my_app1 |-my_app2 |-tests | |-__init__.py | |-conftest.py | └-test1 | |-__init__.py | └-test1_ex.py # Here |-pytest.ini ... But, I could not run test1() as shown below: $ pytest -q -rP no tests ran in 0.10s So, how can I run test() in tests/test1/? -
Django Validation not working, prevent whitespace only
So I'm creating a blog project using Django. The user has the ability to comment on a blog post, edit and delete etc. I want to provide an error if a user tries to enter an empty comment. If the comment contains just whitespaces, or perhaps they click on the submit button without any comment at all. In my forms.py I added the clean_body function as per django documentation. They also mention using '{{ form.non_field_errors }}' in my Template which I've included. Does 'forms' need to be replaced with the form name from forms.py? Now when I load the blog post, the comment field instantly says 'This field is required' and also if I put a comment with whitespaces, the page will refresh and the same 'This field is required' is displayed instead of the unique error message I have added. Finally to add, I have put 'from django.core.exceptions import ValidationError' in my forms.py file. HTML <div class="card-body"> {% if user.is_authenticated %} <h3>Leave a comment:</h3> <p>Posting as: {{ user.username }}</p> <form id="commentForm" method="post" style="margin-top: 1.3em;"> {{ comment_form | crispy }} {{ form.non_field_errors }} {% csrf_token %} <button id="submitButton" type="submit" class="btn btn-primary primary-color btn-lg">Submit</button> </form> {% else %} <h3>Log in or … -
Can't import module with django-extension RunScript
Im trying to create backend for my app with django. I have some data that I want to load into my database from scripts I have created. Finally I found django-extensions runscript that can help me do that. But when running python manage.py runscript import_data_script I get this error: (.venv) PS C:\Users\carle\Vscode_desktop\Mat_app\backend_django> python manage.py runscript import_data_script Traceback (most recent call last): File "C:\Users\carle\Vscode_desktop\Mat_app\backend_django\.venv\Lib\site-packages\django_extensions\management\commands\runscript.py", line 204, in my_import t = importlib.import_module(full_module_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\carle\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\carle\Vscode_desktop\Mat_app\backend_django\mat\scripts\import_data_script.py", line 2, in <module> from exeee import livsmedelsverket_lista ModuleNotFoundError: No module named 'exeee' Cannot import module 'mat.scripts.import_data_script': No module named 'exeee'. No (valid) module for script 'import_data_script' found Try running with a higher verbosity level like: -v2 or -v3 CommandError: An error has occurred running scripts. See errors above. I seems like the script "import_data_script" can't find a module it is trying to import named "exeee". This exeee file is also situated within the … -
Django honeypot problems with url
I'm trying to use the honeypot admin for my 3.2 Django projet On docs they said we need to use a URL like this: urlpatterns = patterns('' ... url(r'^admin/', include('admin_honeypot.urls', namespace='admin_honeypot')), url(r'^secret/', include(admin.site.urls)), ... ) But it seems url is old now and we had to use re_path. I tried to use, re_path,URL, and path but still, I get this error: Traceback (most recent call last): File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/mehdi/Desktop/mynewproject/venv/lib/python3.11/site-packages/admin_honeypot/models.py", line 2, … -
unable to load data in django models form a json file
I am trying to upload JSON file data in my model using pandas but it is causing an error in loading the data here is my model in which i want to load data class Jsondata(models.Model): region = models.CharField(max_length=50, blank=True) start_year = models.IntegerField() published = models.CharField(max_length=100, blank=True) country = models.CharField(max_length=100, blank=True) def __str_(self): return self.country here is my load_data.py file import json import pandas as pd from django.core.management.base import BaseCommand from users.models import Jsondata class Command(BaseCommand): help = 'Load data from JSON file using pandas' def add_arguments(self, parser): parser.add_argument('json_file', type=str) def handle(self, *args, **kwargs): json_file_path = kwargs['json_file'] with open(json_file_path, 'r') as json_file: data = json.load(json_file) # Create a DataFrame from JSON data df = pd.DataFrame(data) # Iterate through DataFrame rows and populate the database for index, row in df.iterrows(): item = Jsondata( region=row['region'], start_year=row['start_year'], published=row['published'], country=row['country'], ) item.save() self.stdout.write(self.style.SUCCESS('Data loaded successfully')) and i tried this command to load data in my data python manage.py load_data media\json_files\jsondata.json and my json file look like { "region": "Central America", "start_year": "", "published": "January, 18 2017 00:00:00", "country": "Mexico", }, any other method to achieve so will also be helpful -
failed to saving multiple instance in one form in django admin
I am new to Django and I am trying to create an account form where you select a user and check the platforms you want and it creates an account in the account table for the user with each platform checked. so : I have three models: users, platforms, and accounts in the model.py file class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Platform(models.Model): platform_name = models.CharField(max_length=255) platform_link = models.CharField(max_length=255) class Account(models.Model): platform = models.ForeignKey(Platform, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) I then created an AccountForm class class AccountForm(ModelForm): platforms = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Platform.objects.all()) class Meta: model: Account fields = ["user", "platforms"] widgets = {'platform': forms.HiddenInput()} in the admin.py class AccountAdmin(admin.ModelAdmin): list_display = ["id", "platform", "user"] form = AccountForm def save_form(self, request: Any, form: Any, change: Any) -> Any: platforms = form.cleaned_data["platforms"] if platforms: accounts_to_save = [] for platform in platforms: account = form.save(commit=False) form.instance.platform = platform accounts_to_save.append(account) Account.objects.bulk_create(accounts_to_save) else: return super().save_form(request, form, change) return super().save_form(request, form, change) I tried iterating through the checked platforms and saving each time, but it keeps saving the instances with only the last value of in the platforms list. so if we select user 2 and checked platform 1 and platform 2 >> it saves … -
connection close or what the problem with cron
I have success doing daily backup code by crontab -e like this sshpass -p "password" scp user@ip:/bath /bathto/bakup/$(date +%H:%M_%Y-%m-%d).sql but Only an incomplete part of the file been transferred when the task work, the full file size about 170M but the the transferred fille come 70-100M maximum . how to make cron transfer the file completely when the task run? -
Unknown field(s) (passward1, passward2) specified for User
I am new to django and trying to make login and log out and register form for user consisting of username, email, passward1, and passward2 (for confirm passward). when i remove passward1 and passward2 two fields from fields in meta class , I can get a form but without email field forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'passward1', 'passward2'] views.py from django.shortcuts import render,redirect from .forms import UserRegistrationForm from django.contrib.auth import authenticate, login from django.contrib.auth.forms import UserCreationForm # Create your views here. def register(request): form = UserCreationForm return render(request, 'register.html', {"form": form} ) -
Static files are not being loaded correctly in the browser when I access my site
Problem Description: I'm trying to set up a directory structure in my Django project where the static folder is inside the user folder, which is in turn inside the templates folder. My intention is to have static files located close to the template files. However, I'm having difficulties getting Django to properly serve static files from this directory structure. Directory Structure: project/ ├── templates/ │ └── user/ │ ├── index.html │ └── static/ │ └── css/ │ └── main.css └── ... Additional Details: I've configured STATIC_URL in settings.py: STATICFILES_DIRS = [os.path.join(BASE_DIR,'/templates/user/static/')] STATIC_URL = '/static/' In my index.html file, I'm using the <link rel="stylesheet" href="{% static 'css/main.css' %}"> tag to reference static files. Issue Faced: Despite adjusting the settings, I'm unable to make Django serve static files properly from this specific directory structure. I've tried different configurations, such as changing STATIC_URL, but I still haven't succeeded. Any help would be greatly appreciated. -
Wagtail always uses default site for URLs
I am using the Django site framework with wagtail. Wagtail correctly gives me the settings I specified for each site. I as of now have 2 sites registered: 127.0.0.1 172.1.16.155 So, when I visit 127.0.0.1, I get all the site settings for 127.0.0.1, and vice versa. The issue is, I have 172.1.16.155 as my default site. When I navigate to a URL from 127.0.0.1, (example: 127.0.0.1/home/) it will go to 172.1.16.1 (172.1.16.155/home/), and the same thing the other way around if I set the default site to the loopback addr. I have tried using both page.full_url and page.url, but to no avail. I have tried adding http://127.0.0.1 to the site settings (though I know this is incorrect), also to no avail. Some possibly relevant Django settings: # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env("SECRET_KEY",default="django-insecure-#=($lwdhz$drt5@h752_puh!y^5aqxh!bn($t_$^x(qd#1p5=e") DEBUG = str(env("DEBUG", default="False")).lower() in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] SECURE_CROSS_ORIGIN_OPENER_POLICY = None ALLOWED_HOSTS = env("DJANGO_ALLOWED_HOSTS",default="127.0.0.1 localhost").split(" ") CSRF_TRUSTED_ORIGINS = env("CSRF_TRUSTED_ORIGINS",default="http://127.0.0.1 http://localhost").split(" ") # Search # https://docs.wagtail.org/en/stable/topics/search/backends.html WAGTAILSEARCH_BACKENDS = { "default": { "BACKEND": "wagtail.search.backends.database", } } # Base URL to use when referring to full URLs within the Wagtail admin backend - # e.g. in notification … -
Isolating User Sessions for AWS Credentials in a Django-Kubernetes Web Application
I am currently developing a web application using Django that takes AWS credentials from the user and retrieves data from their specific AWS bucket. Each user has distinct AWS credentials and accesses different AWS buckets. The AWS credentials are used temporarily for the duration of the user session until logout. The application is set up such that it uses the AWS credentials to retrieve data through Python code, using these credentials for the duration of the session. The goal is to deploy this application on a Kubernetes cluster. Now, I am facing a scenario where multiple users could be accessing the application simultaneously. Here are the specifics: User 1 logs in to the application on Computer 1 using AWS Credentials 1. User 2 logs in to the application on Computer 2 using AWS Credentials 2. In the given scenario, it is crucial that User 1 only sees data from the AWS bucket associated with AWS Credentials 1, and User 2 only sees data from the AWS bucket associated with AWS Credentials 2. The data shown to one user should not be mixed up or reflected on the other user's screen, even upon page refreshes. My question is, how can I … -
I dont understand how to integrate mattermost API into the companies product
I am an intern at a company and I need to integrate the Mattermost chat API into my product. Its an angular application that uses graphql and django on the backend. I understand the basics of APIs but I dont know how to actually implement this so that people can chat with eachother on the website. I added a chat icon in the navigation bar. And I specified the API I wanted to use. But I am confused on how to move forward. I dont need a fully functioning feature that will be pushed to prod, its just a basic proof of concept. Its my first internship, im really scared and I dont want to disapoint. Any help is appreciated. -
UUID value as function argument - Uncaught SyntaxError
Good day dear Community! I have a simple JS function which takes an "id" as argument: <script> function deleteBl(id){ fetch('', { method: 'DELETE', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'id': id }), credentials: 'same-origin', }) } </script> and below Django template: {% for item in bl_query_set %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ item.bl_number }}</td> <td class="text-center">{{ item.cargo_name }}</td> <td>{{ item.cargo_quantity }} {{ item.cargo_measurement }}</td> <td> <a onclick="deleteBl({{ item.id }})"> <i class="fas fa-trash-alt"></i> </a> </td> </tr> {% endfor %} and it works pretty well, there are no any console errors if I use default Id as primary key. But I need to use UUID as a primary key and in that case I get an error: "Uncaught SyntaxError: Invalid or unexpected token". See below screenshot please So, how I can resolve mentioned issue? Thanks for any help in advance! -
How can i make shuffle in django Forms?
I have got a project like quiz. But i need to shuffle the answers in questions. here is my code: template.html <form method="post"> {% csrf_token %} <h3>{{ current_question.text }}</h3> {{ form.selected_answer }} <button type="submit">Next</button> </form> views.py if request.method == 'POST': form = QuestionForm(request.POST, question=current_question) if form.is_valid(): user_answer = form.cleaned_data['selected_answer'] user_test.useranswer_set.update_or_create(question=current_question, defaults={'selected_answer': user_answer}) return redirect('test', test_id=test_id) else: form = QuestionForm(question=current_question) There is my django form. I try like this but it doesn't work: from django import forms from .models import Answer import random from django.db.models.query import QuerySet class QuestionForm(forms.Form): selected_answer = forms.ModelChoiceField( queryset=Answer.objects.none(), widget=forms.RadioSelect, empty_label=None ) def __init__(self, *args, question=None, **kwargs): super().__init__(*args, **kwargs) if question: answers = list(question.answer_set.all()) random.shuffle(answers) self.fields['selected_answer'].queryset = answers -
Got AttributeError when attempting to get a value for field 'field_name' on serializer `MySerializer`
I'm using django to create RESTApi with django-rest-framework. I've view that returns all subscriptions of student. In view, I should filter Subscriptions by company, and student and return it. But @api_view(['GET']) @permission_classes([permissions.ProfileLevelPermission]) def my_view(request, pk): try: company = models.Profile.objects.get( user=request.user, is_active=True).company except: return Response("Company is not found", status=status.HTTP_400_BAD_REQUEST) try: student = models.Student.objects.get( id=pk, company=company, status='1') except: return Response("Student is not found", status=status.HTTP_400_BAD_REQUEST) history = models.Subscription.objects.filter( student__id=student.pk, company__id=company.pk) data = serializers.SubscriptionSerializer(history).data return Response({"data": data}, status=status.HTTP_200_OK) And here is my 'serializer' class SubscriptionSerializer(ModelSerializer): class Meta: fields = ('__all__') model = models.Subscription And here is my models class Subscription(models.Model): STATUS_TYPES = ( ('0', "Permanently deleted"), ('1', "Active") ) cost = models.CharField(max_length=255) month = models.DateTimeField(default=timezone.now()) group = models.ForeignKey(Group, on_delete=models.PROTECT) student = models.ForeignKey(Student, on_delete=models.PROTECT) company = models.ForeignKey(Company, on_delete=models.CASCADE) status = models.CharField(choices=STATUS_TYPES, max_length=15) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.student.name If I send GET request, I'm getting this error I have no idea what kind of error I'm getting. -
django - get serializer output into another serializer
I want to get the output of one serializer 'RoomSerializer' into 'JoinRoomSerializer's fields. I have tried to get the 'RoomSerializer' as a variable into 'JoinRoomSerializer' and then pass it in 'fields', but im getting the following error: Got AttributeError when attempting to get a value for field room_extends on serializer JoinedRoomSerializer. The serializer field might be named incorrectly and not match any attribute or key on the UserRoom instance. Original exception text was: 'UserRoom' object has no attribute 'room_extends'. The Room model has field name and JoinRoom model has foreign key to room My serializers: class RoomSerializer(serializers.ModelSerializer): """Serializer for displaying all fields of the Room""" class Meta(): model = Room fields = ['name'] class JoinedRoomSerializer(serializers.ModelSerializer): """Serializer for displaying the following fields of the joined UserRoom table""" room_extends = RoomSerializer(many=True) class Meta(): model = UserRoom fields = ['room_extends', 'date_joined'] -
Django HttpResponse takes much CPU time
Django takes way too much CPU time to send response to localhost using the development server (same thing happens with gunicorn but a worker timeout occurs). The response size shouldn't be more than 15KB so the content size isn't the problem. I am using a virtual environment (venv) on Ubuntu 22.04. My code is the following: def time_series(request: HttpRequest) -> JsonResponse | HttpResponseBadRequest: """ This view returns a set of time series based on the user's query. Args: request (HttpRequest): The request object passed by django. Returns: JsonResponse | HttpResponseBadRequest: An object containing the time series or an error response. """ # Check this StackOverflow thread to see how group by works in Django: # https://stackoverflow.com/a/629691/11718554 if (patents := get_patents(request)) is None: return HttpResponseBadRequest("No patent query in the current session.") print(len(get_patent_ids(request))) applications_per_year = list( patents.values("application_year") .annotate(count=Count("id")) .order_by("application_year") .values("application_year", "count") ) granted_patents_per_year = list( patents.values("granted_year") .annotate(count=Count("id")) .order_by("granted_year") .values("granted_year", "count") ) granted_patents_per_type_year = list( patents.values("granted_year", "type") .annotate(count=Count("id")) .order_by("granted_year", "type") .values("granted_year", "type", "count") ) granted_patents_per_office_year = list( patents.values("granted_year", "office") .annotate(count=Count("id")) .order_by("granted_year", "office") .values("granted_year", "office", "count") ) pct_protected_patents_per_year = list( patents.filter(pct_data__granted=True) .values("granted_year") .annotate(count=Count("id")) .order_by("granted_year") .values("granted_year", "count") ) granted_patents_per_cpc_year = list( patents.annotate(cpc_section=Substr("cpc_groups__cpc_group", 1, 1)) .values("granted_year", "cpc_section") .annotate(count=Count("id")) .order_by("granted_year", "cpc_section") .values("granted_year", "cpc_section", "count") ) citations_made_per_year = … -
TailwindCSS grid-columns don't apply in Django Template
I'm using TailwindCSS in a Django template. I want to display all elements of a form in 3 columns, but somehow they all get displayed within one column. When I change to 2 columns, it works, but in all other n-columns (3, 4, 5, 6 ...) it doesn't. Anybody knows what the issue is here? Here's the template: <form method="get"> <div class="grid grid-cols-3 md:grid-cols-3 sm:grid-cols-3 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-3"> {% for elem in filter.form %} <div class="">123</div> {% endfor %} </div> <button type="submit">Go!</button> </form> -
Unable to create Google Meet Link in python with django
I'm trying to create a Google Meet event using the Google Calendar API in Python, but I'm encountering an HttpError. Here's the code I'm using to create the event: import logging import uuid from google.oauth2.service_account import Credentials as GoogleCredentials from googleapiclient.discovery import build from googleapiclient.errors import HttpError from courses.models import Teacher logger = logging.getLogger('google_calendar') def create_google_meet_event(teacher: Teacher, start_time, end_time, summary, description): # Retrieve the service account file path service_account_file_path = teacher.service_account_file.path # Use service account credentials credentials = GoogleCredentials.from_service_account_file(service_account_file_path, scopes=['https://www.googleapis.com/auth/calendar']) service = build('calendar', 'v3', credentials=credentials) event = { 'summary': summary, 'description': description, 'start': { 'dateTime': start_time.isoformat(), 'timeZone': 'UTC', }, 'end': { 'dateTime': end_time.isoformat(), 'timeZone': 'UTC', }, 'conferenceData': { 'createRequest': { 'requestId': uuid.uuid4().hex, 'conferenceSolutionKey': { 'type': 'hangoutsMeet' }, } } } try: # Insert the event into the teacher's calendar created_event = service.events().insert(calendarId='primary', conferenceDataVersion=1, body=event).execute() # Get the Google Meet link meet_link = created_event.get('hangoutLink') return meet_link except HttpError as error: # Handle the error as appropriate in your Django view logger.error(error) raise Exception(error) I have ensured that the service_account_file_path is correct, and the teacher object contains the correct credentials. Exception: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?conferenceDataVersion=1&alt=json returned "Invalid conference type value.". Details: "[{'domain': 'global', 'reason': 'invalid', 'message': 'Invalid conference type value.'}]"> Ive …