Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do dynamic nested serialization in django rest framework
For an API that serves multiple quizzes, each of which have varying questions, I have the following models:- class Quiz(models.Model): name = models.CharField() class QuizQuestion(models.Model): quiz = models.ForeignKey(related_name="questions", Quiz) question = models.CharField() class QuizCompletion(models.Model): completed_by = models.ForeignKey(User) quiz = models.ForeignKey(Quiz) class QuizAnswer(models.Model): quizquestion = models.ForeignKey(QuizQuestion) quizcompletion = models.ForeignKey(related_name="answers", QuizCompletion) answer = models.CharField() I am trying to write the serializers and views I need in order to allow the QuizCompletion to be created but I'm having some problems with the validation side of things, as the questions each quiz has (and therefore the answers that it needs) are dynamic. So, each quiz has different questions. My serializers look like this:- class QuizQuestionSerializer(serializers.ModelSerializer): class Meta: model = QuizQuestion fields = ["question"] class QuizSerializer(serializers.ModelSerializer): questions = QuizQuestionSerializer(many=True) class Meta: model = Quiz fields = ["name", "questions"] class QuizAnswerSerializer(serializers.ModelSerializer): quizquestion = QuizQuestionSerializer() class Meta: model = QuizAnswer fields = ["quizquestion"] class QuizCompletionSerializer(serializers.ModelSerializer): quiz = QuizSerializer() answers = QuizAnswerSerializer(many=True) class Meta: model = QuizCompletion fields = ["completed_by", "quiz", "answers"] The problem is, how do I validate the request when a user tries to complete a quiz to make sure that they've given an answer to all of that Quiz's questions? My gut feeling is that … -
Need to write custom User model in DJango and return pre stored json file in response
Just started learning Python/Django 5 days back. Need to write an API where it gets 'username', 'password', 'password2' in request and it should store username in some User object. And if the username already exists in User, then just return simple error message: "username is duplicate". I am using User class from django.contrib.auth.models. Which returns a BIG error response , if username is duplicate. Question 1: I want to return simple one line error message in response. from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password class RegisterSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) if attrs['usename']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Question 2: I want to write an API, which on a GET call , returns pre-stored simple json file. This file should be pre-stored in file system. How to do that? -
user models in django
I created the "Account" model but the contents on the admin dashboard and the model I created are not the same I have manually set the fields for admin in the account section, as shown below enter image description here but what appears on the admin dashboard is like the following imageenter image description here Can anyone help me to remove the fields I don't need? -
How to solve djongo.exceptions.SQLDecodeError when i migrate?
i was creating a chatapplication with MongoDB as my storage. everything was fine and i was using JWT to authenticate user. but it all started crashing the moment i turned one Blacklist=True in JWT settings and added 'rest_framework_simplejwt.token_blacklist', in installed apps. & it's showing me this error: PS E:\py\projects\Django\Chat-application\backend\chat_backend> python manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions, token_blacklist Running migrations: Applying token_blacklist.0002_outstandingtoken_jti_hex...This version of djongo does not support "schema validation using NULL" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0003_auto_20171017_2007... OK Applying token_blacklist.0004_auto_20171017_2013...This version of djongo does not support "COLUMN SET NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0005_remove_outstandingtoken_jti...This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0006_auto_20171017_2113... OK Applying token_blacklist.0007_auto_20171017_2214...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ OK Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__ self._query = self.parse() File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse raise e File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 857, … -
django click on pagination links on Detailview not updating detailview content
for django project based on tutorial project https://github.com/mdn/django-locallibrary-tutorial project I want to show first, previous,next, last pagination links . when clicked on next link I want to load bookdetail of next book and when clicked on previous link I want to load previous book details. I made following change in views.py of catalog app class BookListView(generic.ListView): """Generic class-based view for a list of books.""" model = Book paginate_by = 10 # class BookDetailView(generic.DetailView): """Generic class-based detail view for a book.""" # model = Book class BookDetailView(generic.DetailView, MultipleObjectMixin): """Generic class-based detail view for a book.""" model = Book paginate_by = 1 def get_context_data(self, **kwargs): object_list = Book.objects.all() context = super(BookDetailView, self).get_context_data(object_list=object_list, **kwargs) return context It shows booklist with pagination as shown in screenshot It shows pagination link on bookdetail page as shown in screenshot but when next or previous link is clicked bookdetails content is not updated, it remains same. what change is needed so that on each Bookdetail page when next/previous link is clicked next/previous bookdetails is loaded and to show first bookdetail and last bookdetail link on each bookdetail page -
Attribute error on Django REST framework, 'Quiz' object has no attribute 'question'
These are my models class Quiz(models.Model): title = models.CharField(max_length=255) topic = models.CharField(max_length=255) difficulty = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Question(models.Model): text = models.TextField() quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) def __str__(self): return self.text class Choice(models.Model): options = models.TextField() is_correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return self.text class QuizResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) score = models.IntegerField() date_taken = models.DateTimeField(auto_now_add=True) def _str_(self): return f"{self.user.username} - {self.quiz.title} - {self.score}" And here is my serializer.py from rest_framework import serializers from ..models import Quiz, Question, Choice class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = ['options', 'is_correct'] class QuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True) class Meta: model = Question fields = ['text', 'choices'] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(source = 'question',many=True) class Meta: model = Quiz fields = ['title', 'topic', 'difficulty', 'questions', 'created_by'] def create(self, validated_data): questions_data = validated_data.pop('question') quiz = Quiz.objects.create(**validated_data) for question_data in questions_data: choices_data = question_data.pop('choices') question = Question.objects.create(quiz=quiz, **question_data) for choice_data in choices_data: Choice.objects.create(question=question, **choice_data) return quiz When I send a post request to QuizCreateAPIView it shows an error Got AttributeError when attempting to get a value for field questions on serializer QuizSerializer. The serializer field might be … -
Hindi fonts not showing correctly in reportlab generated PDF
I want to generate PDF file in Marathi font, the font is not support properly in reportlab I am trying the code mentioned in the image but it is not working properly I am expecting like this -I marked that the expected result should look like this -
When using JavaScript to dynamically update content,the Django message doesnt show up
When I write a template about registration,I need a JavaScript code to dynamically change the info to show.However,doing this causes the reminding info disappear.How can I solve it? Here are the template Code and the view {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}">{{ message }}</div> {% endfor %} {% endif %} <div class="form-group"> <label for="id_role">Select role:</label> <select class="form-control" id="id_role" name="role"> <option value="teacher">Teacher</option> <option value="student" selected>Student</option> </select> </div> <div class="form-group" id="teacher-fields" style="display: {% if form.role.value != 'student' %}block{% else %}none{% endif %}"> ... <div class="form-group" id="student-fields" style="display: {% if form.role.value == 'student' %}block{% else %}none{% endif %}"> ... <button type="submit" class="btn btn-primary">Register</button> </form> <script> // Listen for changes to role selection and update form fields const roleSelect = document.getElementById('id_role'); const teacherFields = document.getElementById('teacher-fields'); const studentFields = document.getElementById('student-fields'); roleSelect.addEventListener('change', () => { if (roleSelect.value === 'teacher') { teacherFields.style.display = 'block'; studentFields.style.display = 'none'; } else { studentFields.style.display = 'block'; teacherFields.style.display = 'none'; } }); </script> def register(request): if request.method == 'POST': if request.POST.get('role') == 'teacher': form = TeacherRegistrationForm(request.POST) else: form = StudentRegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your account has been created! You are now able to log in') return redirect('account/login') else: for field, errors … -
DRF - list of optionals field in serializer meta class
I have a model with about 45 fields that takes information about a company class Company(models.Model): company_name = models.Charfield(max_length=255) . . . last_information = models.Charfield(max_lenght=255) I also have a serializer that looks like so, class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = "__all__" # some_optional_fields = ["field_1","field_2","field_3"] however some of the fields are not required (about 20 of them to be precise). Is there a way where I can add those optional fields as a list or iterable of some sort to the metadata, example some_optional_fields = ["field_1","field_2","field_3"], so that I won't have to explictly set those variables required argument to false like so class CompanySerializer(serializers.ModelSerializer): company_name = serializers.Charfield(max_length=255, required=False) . . . last_information = serializers.Charfield(max_lenght=255, required=False) class Meta: model = Company fields = ["field_1","field_2","field_3",...,"field_45"] -
Cannot login user and admin user to the main website
Building a django project and successfully done the registration, login, logout and activate views, the registration is working because a user get a link sent to their email after they signup but I'm having errors saying invalid credentials when I try to login with that created account also same with trying to login with the admin password and email address, can only login to the admin panel. Here is the codes. models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=False): if not email: raise ValueError("Please user must have a email address") if not username: raise ValueError("Please User must have a username") user = self.model( email = self.normalize_email(email), username= username, first_name = first_name, last_name = last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,first_name, last_name, email, username, password): user = self.create_user( email = self.normalize_email(email), username= username, password=password, first_name = first_name, last_name = last_name, ) user.is_admin = True user.is_active = True user.is_staff = True user.is_superadmin = True user.save(using=self._db) return user class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) username = models.CharField(max_length=50, unique=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) #required fields date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superadmin … -
Django models and orm and foreign key problems
i want got all of related model's data, but i got only some of related data. to avoid N+1 problem, i used select_related() and prefetch_related() methods. At first, i have these models: def OrderList(models.Model): order_id=models.CharField(max_length=100) order_status=models.CharField(max_length=100) def ProductInOrder(models.Model): order_key=models.ForeignKey(OrderList, on_delete=models.CASCADE, related_name="order_key") product_id=models.CharField(max_length=100) product_price=models.CharField(max_length=100) def MemosInProduct(models.Model): product_key=models.ForeignKey(ProductInOrder, on_delete=models.CASCADE, related_name="product_key") memo=models.CharField(max_length=100) blahblah some codes... a short explan of this models, one OrderList has got many of ProductInOrder ( one to many ) and one ProductInOrder has got many of MemosInProduct( one to many ) then, i run this codes in django shell: order_list=OrderList.object.select_related("order_key", "product_key").all() i excepted all of OrderList datas with related all of datas combine with it(product, memos): EXCEPTED order_list[0].order_key[0].product_key[0].memo order_list[0].order_key[0].product_key[1].memo order_list[0].order_key[1].product_key[0].memo ... but i got: OUTPUT Invalid field name(s) given in select_related: 'order_key', 'product_key'. Choices are: (none) i also tried this: order_list=MemosInProduct.object.select_related("order_key", "product_key").all() but outputs are not matched i except. -
Object creation testing problem django rest framework
I have a model for PhotoAlbum: class PhotoAlbum(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, auto_created=True) name = models.CharField(max_length=50, verbose_name='Album name') type = models.ForeignKey(AlbumType, on_delete=models.CASCADE, verbose_name='Album type') created_at = models.DateTimeField(auto_now_add=True) I wrote a simple test to create an object of photoalbum, but it fails because the specified album type does not exist, as a creates a completely empty database that has no information about photo album types. def test_create_album(self): url = reverse('album-list') data = {'name': 'SomeAlbum', 'type': 2} response = self.client.post(url, data, format='json') print(response.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(PhotoAlbum.objects.count(), 1) album = PhotoAlbum.objects.get() self.assertEqual(album.name, 'SomeAlbum') self.assertEqual(album.type, 2) Got this error: {'type': [ErrorDetail(string='Invalid pk "2" - object does not exist.', code='does_not_exist')]} What are the solutions to this problem? Is it possible to create a database with album types pre-populated? -
How to create test bucket before running tests by django-minio-backend
I use django-minio-backend in order to integrate Django and Minio. I want to create a test bucket for created media files during tests running. I tried to do that in a custom test runner as follows: class CoreTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): super(CoreTestRunner, self).setup_test_environment() self._make_test_file_storage() def _make_test_file_storage(self): minio_test_bucket = "test-bucket" settings.MINIO_MEDIA_FILES_BUCKET = minio_test_bucket settings.MINIO_PRIVATE_BUCKETS = [minio_test_bucket] call_command("initialize_buckets") The problem is that when I run the test command, Minio creates the test-bucket, but uploads all files to the old bucket (the available bucket before creating test-bucket) The old bucket in settings.py is project-media-bucket and all the files are uploaded in this bucket instead of uploading on test-bucket. How can I solve the problem? -
How to grant permissions to mysql in github actions
I'm trying to do some testing with github actions. previous post: test-not-found-in-github-actions Now that the test is recognized, all that's left is to configure mysql. I'm getting the error "User access is denied" https://github.com/duri0214/portfolio/actions/runs/4250191595/jobs/7391059026#step:4:569 Usually this error goes away by granting privileges to mysql. It has been confirmed on the production server that django works by giving the following nine permissions. -- in VirtualPrivateServer mysql> CREATE DATABASE portfolio_db DEFAULT CHARACTER SET utf8mb4; Query OK, 1 row affected (0.01 sec) mysql> CREATE USER 'python'@'%' IDENTIFIED BY 'XXXXXXXX'; mysql> grant CREATE, DROP, SELECT, UPDATE, INSERT, DELETE, ALTER, REFERENCES, INDEX on portfolio_db.* to 'python'@'localhost'; However, I don't really understand how to type this mysql command. I get an error even if I issue a command to github actions as follows. I was able to confirm that the secret was output https://github.com/duri0214/portfolio/actions/runs/4249942981/jobs/7390568462#step:4:424 mysql -u${{ secrets.DB_USER }} -p${{ secrets.DB_PASSWORD }} -e 'CREATE DATABASE portfolio_db DEFAULT CHARACTER SET utf8mb4;' mysql -u${{ secrets.DB_USER }} -p${{ secrets.DB_PASSWORD }} -e 'CREATE USER '${{ secrets.DB_USER }}'@'localhost' IDENTIFIED BY '${{ secrets.DB_PASSWORD }}';' mysql -u${{ secrets.DB_USER }} -p${{ secrets.DB_PASSWORD }} -e 'grant CREATE, DROP, SELECT, UPDATE, INSERT, DELETE, ALTER, REFERENCES, INDEX on portfolio_db.* to '${{ secrets.DB_USER }}'@'localhost';' Warning: arning] Using a password … -
How to access Oracle DB Link in Django models?
Im trying to access table from different databases using database Link. Im getting error database link not found My model looks like this: from django.db import models # Create your models here. class Customer(models.Model): cust_num = models.CharField(max_length=20) customer_number = models.CharField(max_length=80) class Meta: db_table = '\"MY_SCHEMA\".\"TABLE_NAME\"@\"OTHER_DB\"' managed = False And im getting this error while trying to access it through Python Django shell cx_Oracle.DatabaseError: ORA-04054: database link MY_SCHEMA.CUST_NUM does not exist Any suggestions? Thanks -
PostgreSQL Django migrate error after existing project
django.db.utils.IntegrityError: column "date_of_birth" of relation "account_user" contains null values python manage.py migrate -
I have catcry.jpg why them said error OMGGGGG(its cats cute website)
[enter image descriptionenter image description here here](https://i.stack.imgur.com/Jl1lA.png) [enter image description here](https://i.stack.imgur.com/xsw2O.png) -
I'd like to display the separated Forms and set initial values from Session with Django
I’d like to implement a Shopping Cart (in logged-out status) like Amazon, Rakuten and so on with Django4.1. So, I tried to write codes using Session, not using Database and ModelForm. However, I am stuck and do not know how to do. The Shopping Cart of Rakuten (https://www.rakuten.co.jp/) displays SelectBoxes for quantities and the number of SelectBoxes is same with that of species of Items after we add items to the cart. And when I checked the HTML with developer tool, I found <select name=“units[0]”> and <select name=“units[1]”> in the Rakuten Cart. I could display several Forms, for example CartForm, but all Forms showed <select name=“quality”> in HTML and they were not separated. So, if I change one of the Form, for instance change a quantity to 30, the number of quantity of all Forms become 30. I found these following pages, but it seems they cannot be the solution because they cannot change the “name” attribute dynamically. ・https://progl.hatenablog.com/entry/2017/07/23/185923 ・https://www.appsloveworld.com/django/100/20/change-the-name-attribute-of-form-field-in-django-template-using Besides, I’d like to push the initial numbers, quantities, which are gotten from Session to the each Forms, but I have no idea what to do (in my code, all quantity is 1). I tried, views.py cart_form = CartForm(initial=???) forms.py … -
Can Apache run wsgi.pyd
I am trying to deploy a django project on a windows machine using Apache and mod_wsgi. I have compile the wsgi.py into wsgi.pyd. However, it seems that the apache is not able to run the wsgi.pyd file. -
Django Channels: Real time application, update other rooms when any action appears
For now I've created a consumer that can handle one-to-one connections as a private chat. In my UI I display previous conversations and I'd love to somehow update their content if new message or conversation appears and then apply some actions, so for example slide the previous conversation to the top if it contains a new message. So it's like in any bigger application as instagram or facebook. When you're chatting with someone and if any new message appears from other sender, not the one that you're chatting with, the previous conversations are being updated, so in this case slide the previous or new conversation to the top of conversations. I'm not really familiar with websockets and I want to find the way how can I do that. As I understand if consumer let's two users connect to one room (layer?) how can other messages be updated? websocket does not know anything about it? I've tried brainstorming, but I still didn't get it right. This is my consumer as i've mentioned before, it only can only support two connections between two users. class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.private_chat_room_id = self.scope['url_route']['kwargs']['private_chat_room_id'] self.room_group_name = f'private_{self.private_chat_room_id}' if self.user.is_anonymous: await self.close() … -
'Client' object has no attribute 'text' Django
I have models in my project class Client(models.Model): """Аккаунт, с которого рассылаются сообщения""" name = models.CharField(max_length = 25) last_name = models.CharField(max_length = 25) description = models.TextField(max_length = 70) avatar = models.ImageField('Аватар', upload_to = 'sender/', blank = True) phoneNumberRegex = RegexValidator(regex = r"^\+?\d{8,15}$") phone_number = models.CharField(validators = [phoneNumberRegex], max_length = 16, unique = True) api_id = models.CharField(max_length=9) api_hash = models.CharField(max_length=33) proxy = models.ForeignKey( Proxy, blank=True, on_delete=models.CASCADE ) owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='owner', verbose_name='Владелец', ) class Meta: ordering = ('name',) verbose_name = 'Аккаунт' verbose_name_plural = 'Аккаунты' def __str__(self): return self.text class Sender(models.Model): """Рассылка""" NUMBER_PHONE = 'По номеру телефона' USER_NAME = 'По имени пользователя' SENDER_CHOICES = ( (NUMBER_PHONE, 'По номеру телефона'), (USER_NAME, 'По имени пользователя'), ) name = models.CharField( 'Название рассылки', max_length=10, ) text = models.TextField( 'Сообщение', max_length=4096, ) type = models.CharField( 'Тип рассылки', max_length=30, choices=SENDER_CHOICES, default=NUMBER_PHONE, db_index=True, ) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='Mailer', verbose_name='Автор', ) sender_man = models.ForeignKey( Client, on_delete=models.CASCADE, related_name='Sender_man', verbose_name='Отправитель', null=True, blank=True, ) def __str__(self): return self.name From these models I create forms class SenderForm(forms.ModelForm): class Meta: model = Sender fields = ('name', 'text', 'type', 'author', 'sender_man') class ClientForm(forms.ModelForm): class Meta: model = Client fields = ('name', 'last_name', 'description', 'avatar', 'phone_number', 'api_id', 'api_hash', 'proxy') When I create an … -
Django query stock price a year ago
I want to find the ticker prices which are greater than the price on the same day a year ago. How do I run the django query to get those prices? from django.db import models class Ticker(models.Model): symbol = models.CharField(max_length=50, unique=True) class TickerPrice(models.Model): ticker = models.ForeignKey( Ticker, on_delete=models.CASCADE, related_name="ticker_prices" ) price = models.DecimalField(max_digits=7, decimal_places=2) close_date = models.DateField() I'd like to run the query like below, but couldn't figure out how to get the ticker_price_a_year_ago. TickerPrice.objects.filter(price__gte=ticker_price_a_year_ago). -
Django TemplateDoesNotExist at /inicio/
A url do django está renderizando um caminho que não existe, mesmo estando indicado na view TemplateDoesNotExist at /inicio/ modelo.html Request Method: GET Request URL: http://127.0.0.1:8000/inicio/ Django Version: 4.1.7 Exception Type: TemplateDoesNotExist Exception Value: modelo.html Exception Location: C:\Users\vickc\OneDrive\Área de Trabalho\form_django\venv\Lib\site-packages\django\template\backends\django.py, line 84, in reraise Raised during: sgc.views.IndexView Python Executable: C:\Users\vickc\OneDrive\Área de Trabalho\form_django\venv\Scripts\python.exe Python Version: 3.11.1 Python Path: ['C:\\Users\\vickc\\OneDrive\\Área de Trabalho\\form_django\\form', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Users\\vickc\\OneDrive\\Área de Trabalho\\form_django\\venv', 'C:\\Users\\vickc\\OneDrive\\Área de ' 'Trabalho\\form_django\\venv\\Lib\\site-packages'] Server time: Wed, 22 Feb 2023 21:02:11 -0300 View do app: from django.views.generic import TemplateView # Create your views here. # class ModeloView(TemplateView): template_name = "sgc/modelo.html" class IndexView(TemplateView): template_name = "sgc/index.html" Url do app: from django.urls import path from .views import ModeloView, IndexView urlpatterns = [ #path('endereco/', MinhaView.as_view(), name='nome-da-url') path('modelo/', ModeloView.as_view(), name='modelo'), path('inicio/', IndexView.as_view(), name='inicio'), ] caminho da template está em: templates L__ sgc L__index.html L__modelo.html Já tentei tirar os arquivos html da pasta sgc e deixar apenas na template mas a renderização de outras templates em outros apps dá erro -
How to write to_internal_value for Nested Serializer
I'm trying to build an app using a Django REST API connected to JQuery Datatables Editor. The problem I'm having is that I am unable to use a referenced serailizer due to a key error (I cannot enter data into the InstitutionSerializer due to the added to_internal_value function) The inserted function to_internal_value however is necessary for InvestigatorDatatableSerializer to reference and edit data. For now I am able to get it working by simply having two serializers (ex. InstitutionDatatableSerializer and InstitutionSerializer), but I was wondering if there is a way to add conditions the to_internal_value so I can have a single serializer where it can both make new instances and still check for existing ones. Error This is the error I get while trying to enter data KeyError at /dashboard/api/institution/editor/ 'id' serializers.py class InstitutionDatatableSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = Institution fields = ('__all__') datatables_always_serialize = ('id',) class InstitutionSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) def to_internal_value(self, data): return get_object_or_404(Institution, pk=data['id']) class Meta: model = Institution fields = ('__all__') datatables_always_serialize = ('id',) class InvestigatorDatatableSerializer(serializers.ModelSerializer): institution_name = serializers.ReadOnlyField(source='institution.name') institution = InstitutionSerializer() class Meta: model = Investigator fields = ('id', 'last_name', 'first_name', 'email', 'institution_name', 'institution', ) datatables_always_serialize = ('id',) models.py class Institution(models.Model): id = models.AutoField(unique=True, … -
How to use static image as watermark for every page when printing pdf using django-wkhtmltopdf
I need to be able to use a static image as watermark when printing a pdf from a django template using django-wkhtmltopdf. How can I do it? Here is the watermark I want to use for every page