Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Selenium multiple drivers (windows)
I'm creating API that is based on web-scraping via Selenium. And I've just figured out that: if user1 makes request, as long as he's waiting for response (selenium is scraping page for needed data) user2 must wait for user's1 chromedriver to stop session and only after that selenium starts scraping data for user2, that's not efficient at all ;(I'm pretty sure it's possible to run multiple drivers at the same time (one driver for each request) just like Django-channels run multiple channels. How can I achieve that? I'M NOT TESTING, I'M SCRAPING WEB-PAGES -
DRF Nested serializers
I'm kind of confused in writing the nested serializer in django rest framework. If I have tow models Account and UserProfile. In which UserProfile is ForeignKey to Account and when writing serilaizer should I call UserProfile Serializer in Account's Serializer or call Account Serilaizer in UserProfile Serializer. #Models.py Class Account (AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True Class USerProfile(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) address_line_1 = models.CharField(max_length=100) address_line_2 = models.CharField(max_length=100) phone = models.IntegerField(null=True) And in writing serializer I'm confused. So please explain to me in detail how to write nested serializer. #Serializers.py class AccountSerializer(ModelSerializer): class Meta: model = Account fields = ["first_name", "last_name", "email", "password"] extra_kwargs = { "password": {"write_only": True}, } class UserProfileSerializer(ModelSerializer): user = AccountSerializer() class Meta: model = UserProfile fields = "__all__" def create(self, validated_data): #Didn't write the logics here as of now. return super().create(validated_data) So Is this this correct way to write nested serializer? -
process 'forkPoolworker-5' pid:111 exited with 'signal 9 (SIGKILL)'
hello every one who helps me? python:3.8 Django==4.0.4 celery==5.2.1 I am using python/Django/celery to do something,when I get data from hive by sql,my celely worker get this error "process 'forkPoolworker-5' pid:111 exited with 'signal 9 (SIGKILL)'",and then,my task is not be used to finish and the tcp connect is closing! what can I do for it to solve? I try to do: CELERYD_MAX_TASKS_PER_CHILD = 1 # 单work最多任务使用数 CELERYD_CONCURRENCY = 3 # 单worker最大并发数 CELERYD_MAX_MEMORY_PER_CHILD = 1024*1024*2 # 单任务可占用2G内存 CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 24 * 3 -Ofair but these is not using for solving. -
Function trigger other function and ends before result
I'm developing an API with Django Rest Framework for handling some subscriptions I wanted do make the registration in 2 steps. First, i would register user in my database, after that i want to register user to other service (email marketing, for example). I have to do it in two steps because the registering of the user in external services may take some time (or the service can be unavailable at the time of request) and i don't want users to wait everything so they can go to other pages. My idea is: After registering user into my database, i would return http 200_ok to the front-end so user can go to other pages, and in my backend i would use that data to try to register the user in external services as many times as needed (e.g: waiting if other services are unavailable). But rest_framework only allows me to return Response() (i'm using class-based views), so i only can return http 200_ok, but if i return the function ends and my other functions (that will take more time to run) will end aswell. Is there a way to do this? -
Django Multiprocessing Error on Server But Works Fine on Localhost - __init__() got an unexpected keyword argument 'initializer'
When I Run my Django App on my computer it works fine. But when pushed to Ubuntu Server I am now getting the error. __init__() got an unexpected keyword argument 'initializer' Here is my View Code def verifyt(request): listi = get_listi() print("verifyt",listi) with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor: results = executor.map(wallet_verify, listi) return HttpResponse("done") Ive upgraded my python from 3.6.9 to 3.7.5 still same error. -
I want to add 'created_by' and 'modified_by' fields to my Django models, How do I do that?
My custom user model in account.models.py: class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('abc', 'abc'), ('def', 'def'), ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default=None) designation=models.CharField(max_length=70) is_active=models.BooleanField() is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username A model in sample.models.py: class LockData(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE, default=None) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None, blank=True, null=True) lock=models.BooleanField(default=False) date=models.DateField(default=datetime.date.today) created_on=models.DateTimeField(auto_now_add=True) modified_on=models.DateTimeField(auto_now=True) So, along with created_on and modified_on fields, I also want 'created_by' and 'modified_by' fields. How can I do that? -
django path issue with filebrowser in tinymce
When inserting an image through tinymce in django, there is a problem with the src path of the img. The media is browsed through filebrowser and the image is inserted into tinymce, but the image path is <img src="../../../../media/path/to/img.file"> instead of a url. to be designated How can I make that path a full url path <img src="/media/path/to/img.file">? I tried applying the following settings in settings.py but it doesn't work. Django Tiny_MCE and FileBrowser leading ../../../ TINYMCE_DEFAULT_CONFIG = { 'remove_script_host' : 'false', 'convert_urls' : 'false', } -
Prevent error when missing key in Django Rest Framework
I'm building an API for handling database and email-marketing data for other websites of mine. I have an endpoint for deleting users from database and ActiveCampaign, to prevent making any delete requests by mistake, i'm checking if there's a key:value pair in the request body, if 'delete': true, proceed, if not, i want to return an error message with status code for letting me (or other that i may include in project in the future) know what was the mistake. My is: While checking if there is a key named 'delete' i get an error and my program stop working. I wish to know if there's a way of only "doing stuff" after some checking, but without breaking my program, if something not expected would happen, it would send an error back to request origin. Here's the class/function i'm trying to make work: class Leads(APIView): @staticmethod def delete(request): if request.data["delete"]: delete_from_db = Lead.objects.filter(email=request.data["email"]) lead = LeadHelper(email=request.data["email"] if request.data["email"] else "") lead.delete_from_activecampaign() return Response([delete_from_db], status=status.HTTP_200_OK) else: payload = { "message": "Denied because 'delete': 'true' was not found in request, did you sent this by error?" } return Response(payload, status=status.HTTP_401_UNAUTHORIZED) My main problem is that if there's no 'delete' key, it don't … -
django - having trouble selecting values based on FK relationship in views.py
I have two models that look like; class Body(models.Model): body_id = models.AutoField(primary_key=True) is_adult = models.BooleanField(default=False) body = models.TextField() add_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) add_date = models.DateTimeField() edit_user = models.CharField(max_length=25, blank=True, null=True) edit_date = models.DateTimeField(blank=True, null=True) category = models.ForeignKey(Category, models.CASCADE) class Meta: managed = True db_table = 'jdb_body' class BodyTag(models.Model): body_tag_id = models.AutoField(primary_key=True) body = models.ForeignKey('Body', models.CASCADE) tag = models.ForeignKey('Tag', models.CASCADE, db_column='tag') class Meta: managed = True db_table = 'jdb_body_tag' def __str__(self): return self.tag I have a view that looks like; def index(request): latest_body_list = Body.objects.all().order_by('-body_id') context = { 'latest_body_list': latest_body_list } return render(request, 'index.html', context) That view gives me a list Body records no problem. I am trying to display Body records with their corresponding BodyTag records. What am I doing wrong? -
Import project's subpackages in Python
i'm experimenting with DDD in Python so i've decided to implement a toy project. I've created different directories in other to separate shared concepts from specific bounded contexts concepts. As i try to import these files, i'm facing a No module named error exceptions For example, with this project structure: . └── src/ ├── Book/ │ ├── application │ ├── domain/ │ │ ├── Book.py │ │ └── __init__.py │ ├── infrastructure │ └── __init__.py └── Shared/ ├── application ├── domain/ │ ├── Properties/ │ │ ├── __init__.py │ │ └── UuidProperty.py │ ├── ValueObjects/ │ │ ├── __init__.py │ │ └── BookId.py │ └── __init__.py └── infrastructure On src/Book/domain/Book.py i have: from Shared.domain.ValueObjects.BookId import BookId class Book: bookId: BookId pages: int As i've seen in other answer (pretty old ones) it can be fixed by adding these folders to PYTHONPATH or PATH like sys.path.insert(*path to file*) but i'm wondering if there is a more pythonic way to achieve that. I've also tried to add an __init__.py file to src and import as from src.Shared.domain.ValueObjects.BookId import BookId but none of previous attempts worked for me On other repos i've saw that they use setuptools to install the src package in … -
Fail to pass/use string argument for img to html file in Django app?
I am very new to Django and was trying to pass one argument as a string to my html file so that I can call to use my image. I have the below code to call static image: {% load static %} <img src= "{{ user_age_pic_name }}" width=950 height=450px padding = 40px alt="" > However, this is not working (I also tried deleting the double quote). I know the image is correct because when I call <img src= "{% static 'research/used_viz/comparative/age/12-15.jpg' %}" width=950 height=450px padding = 40px alt="" > The img works perfectly. I also try to just print out the text and it seems to work fine. I think it should be cause by limited understanding of HTML arguments. Could someone guide me through this? Any input is appreciated! -
how to dynamically set the choices of a choice field in django DRF serializer through __init__ or __new__ method?
I am trying to dynamically set the choices of a choice field in django serializer class I want to pass the choices (dynamically) to it and it set it for me The simplified version of the project is this # urls urlpatterns = [ path("cat", CatView.as_view(), name="cat") ] I have tried different things and they don't work. I am sharing one of them here I even had to use the private methods (which I would prefer not to) of the field but still not successful # serializers class CatSerializer(serializers.Serializer): name = serializers.ChoiceField(choices=[]) def __new__(cls, *args, **kwargs): name_choices = kwargs["names"] f = CatSerializer._declared_fields["name"] f._set_choices(name_choices) f.__dict__["_kwargs"]["choices"] = name_choices obj = super().__new__(cls) return obj def __init__(self, *args, **kwargs): kwargs.pop("names") super().__init__(self, *args, **kwargs) # views class CatView(APIView): def __init__(self, *arg, **kwargs): super().__init__(*arg, **kwargs) self.names = ['a', 'b', 'c'] def get_serializer(self, *args, **kwargs): serializer_class = CatSerializer return serializer_class( *args, **kwargs, names=self.names ) def post(self, request): request_body = request.body serializer = self.get_serializer( data=json.loads(request_body), ) is_data_valid = serializer.is_valid() if is_data_valid: serialized_data = serializer.data return Response({"message": "success", "serialized-data": serialized_data}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I now see this error: AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `CatSerializer`. The serializer field might be … -
Sum using Django Template syntax?
I have an exercise that consists of sets, I assign sets to this exercise model. I am able to calculate the total volume of a single set. But how do I calculate the total volume for the exercise. Is it possible to return the sum value of a for loop? When I do it in the view I am only able to return the sum of .all() like this def homeview(request): set = ExerciseSetModel.objects.all() sum = 0 for obj in set: sum += obj.setvolume() context = { 'sum': sum, # returns the sum of everything but I want the single exercise } return TemplateResponse(request, 'poststemplates/posthome.html', context) model: class ExerciseModel(models.Post): exercisename = models.TextField(max_length=500, verbose_name='text', blank=True, null=True, default="text") class ExerciseSetModel(models.Post): exercise = models.ForeignKey(ExerciseModel, on_delete=models.CASCADE, default=None,) repsnumber = models.IntegerField(default=1, null=True, blank=True) weightnumber = models.IntegerField(default=1, null=True, blank=True) def setvolume(self): return self.repsnumber * self.weightnumber views: @login_required def homeview(request): exercises = ExerciseModel.objects.all() context = { 'exercises': exercises, } return TemplateResponse(request, 'poststemplates/posthome.html', context) template: {% for exercise in exercises %} {% for set in exercise.exercisesetmodel_set.all %} {{set.setvolume}} {% endfor %} {% endfor %} now let's say that I have two sets inside a single exercise, I'm able to calculate the set volume for each set, but how … -
How to properly render form fields with django?
I am currently working on a login page for a django webapp. I am trying to include the login form within the index.html file. However, the form fields are not being rendered. My urls are correct I believe but I'm not sure where I am going wrong. Here is my views.py, forms.py and a snippet of the index.html. (I do not want to create a new page for the login I'd like to keep it on the index page) # Home view def index(request): form = LoginForm() if form.is_valid(): user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password'], ) if user is not None: login(request, user) messages.success(request, f' welcome {user} !!') return redirect('index_logged_in.html') else: messages.info(request, f'Password or Username is wrong. Please try again.') return render(request, "index_logged_out.html") class LoginForm(forms.Form): username = forms.CharField(max_length=63) password = forms.CharField(max_length=63, widget=forms.PasswordInput) <!-- Login --> <section class="page-section" id="login"> <div class="container"> <div class="text-center"> <h2 class="section-heading text-uppercase">Login</h2> </div> <form> {% csrf_token %} {{form}} <center><button class="btn btn-primary btn-block fa-lg gradient-custom-2 mb-3" type="submit" style="width: 300px;">Login</button></center> </form> <div class="text-center pt-1 mb-5 pb-1"> <center><a class="text-muted" href="#!">Forgot password?</a></center> </div> <div class="d-flex align-items-center justify-content-center pb-4"> <p class="mb-0 me-2">Don't have an account?</p> <button type="button" class="btn btn-outline-primary"><a href="{% url 'register' %}">Create New</a></button> </div> </form> </div> </section> -
ExcelResponse doesn't send file correctly
I'm using django-excel-response 2.0.5 to download Excel sheet using Django. sheet = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6], [7, 8, 9]] response = ExcelResponse(sheet, 'test') return response Instead of downloading file, it doesn't open anything and response.data is byte version of file, like PK�����5���� ��GEp,���L�v��>�ݾ��cb�x����Ш=���0����E &o��PK Is there a problem in Django rest settings, or I'm using lib wrong? I tried to change view class, different response classes, but nothing helped -
Integrating Vite (VueJs) frontend with Django Login Form
I am looking to understand how once it is checked that a user is authenticated using a django login form, how they can then be taken to a vue frontend made using vite? Many examples I have seen make use of webpack loader however, I am using vite. I am developing locally, so is it a matter of just directing the user to a local server url only if authenticated? The idea is depending on the authenticated user, certain information will need to be gathered associated with them. -
How to send audio file from front end to django backend through websockets for processing at the backend
I have made a website in django that uses websockets to perform certain tasks as follows : From frontend I want to take audio using MediaRecorder as input api through javascript I want to send this audio back to the backend for processing and that processed data is again send back through the connection in realtime. I have tried various things for the purpose but haven't been successful yet. The bytes data that I've been receiving at the backend when I'm converting that into audio then I'm getting the length and size of the audio file but not getting the content of the file. Means the whole audio is silent but the same audio which I'm listening in the frontend is having some sound. but I don't know what's happening at the backend with the file. Consumer.py : import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["username"] self.room_group_name = "realtime_%s" % self.room_name self.channel_layer.group_add( self.room_group_name, self.channel_name) await self.accept() print("Connected") async def disconnect(self , close_code): await self.channel_layer.group_discard( self.roomGroupName , self.channel_layer ) print("Disconnected") async def receive(self, bytes_data): with open('myfile.wav', mode='bx') as f: f.write(bytes_data) audio.js : <script> navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => { if (!MediaRecorder.isTypeSupported('audio/webm')) return alert('Browser not supported') … -
Isolation level doesn't change even if setting "SERIALIZABLE" to 'OPTIONS' in settings.py in Django
Following the documentation, I set SERIALIZABLE isolation level to 'OPTIONS' in settings.py for PostgreSQL as shown below. *I use Django 3.2.16 on Windows 11: # "settings.py" import psycopg2.extensions DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', }, 'OPTIONS': { # ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ Here ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE, }, } Then, I created person table with id and name with models.py as shown below: person table: id name 1 John 2 David # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) Then, I created and ran the test code of non-repeatable read which runs two transactions with two threads concurrently as shown below: # "store/views.py" from django.db import transaction from time import sleep from .models import Person from threading import Thread from django.http import HttpResponse @transaction.atomic def transaction1(flow): while True: while True: if flow[0] == "Step 1": sleep(0.1) print("<T1", flow[0] + ">", "BEGIN") flow[0] = "Step 2" break while True: if flow[0] == "Step 2": sleep(0.1) print("<T1", flow[0] + ">", "SELECT") person = Person.objects.get(id=2) print(person.id, person.name) flow[0] = "Step 3" break while True: if flow[0] == "Step 6": sleep(0.1) print("<T1", flow[0] … -
Why can't I add a photo in the Django admin panel
I'm making a Django store site and I have a product class that includes an "image" field. I am using Models.ImageField and adding any! photos(I installed the Pillov library), pictures, the admin panel gives an error. I am attaching the class Product(models.penter image description herey), from django.db import models from django.urls import reverse # Create your models here. # class Shop_element(models.Model): name_element = models.CharField('Название товара', max_length=100, default='') description_element = models.TextField('Описание товара', max_length=250, default='') id_element = models.IntegerField('Уникальный id,не должен повторяться', max_length=10) #count_element = models. def __str__(self): return self.title class meta(): verbose_name = 'Товар' verbose_name_Plural = 'Товары' class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.PROTECT) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d') # description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_detail', args=[self.id, self.slug]) Tried to fix it myself but failed. -
django htmx change hx-get url after user input from radio buttons
This is forms.py: class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs = { "hx_get": reverse("planner:detail", kwargs={"slug": self.instance.venue}), "hx_target": "#services", } class Meta: model = Order fields = ["venue"] widgets = {"venue": forms.RadioSelect()} HTML: <div id="venue-options" class="p-3"> {% crispy form %} </div> This is the error when you click one of the radio buttons: The current path, planner/detail/None/, matched the last one. It says None/ because when you join the page none of the radio buttons are clicked so there is no slug to replace it. I need a way to replace None with the slug / id of the object chosen by the user. I need the url to be changed everytime the choise is changed. I am open to using apline.js but i would like a way of doing it in htmx/django. Thank you so much. -
What are these weird symbols in bash terminal in vs code. I am working with Django. How to fixed it?
$ python manage.py migrate ?[36;1mOperations to perform:?[0m ?[1m Apply all migrations: ?[0madmin, auth, contenttypes, my_app, sessions ?[36;1mRunning migrations:?[0m Applying my_app.0001_initial...?[32;1m OK?[0m Tried to make it look like this. -
Validate models in django admin with inlines (when I save several models at the time)
I'm maiking a quiz on django. On the picture below you can see 3 models (Quiz, QuizQuestionQuizAnswer) on 1 page. I used NestedStackedInline and NestedTabularInline for that. I need to need validate quiz before save. For example: I need to check if at least one answer is marked as correct. If answers more than one. etc models.py class Quiz(models.Model): title = models.CharField('Название теста', max_length=200) description = models.TextField('Описание', max_length=2000, blank=True) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) pass_score = models.PositiveIntegerField(help_text='Минимальный результат (в процентах) для прохождения теста', default=60, validators=[ MaxValueValidator(100), ]) created_at = models.DateTimeField('Дата создания', auto_now_add=True, ) updated_at = models.DateTimeField('Дата обновления', auto_now=True, ) def get_quiz_question(self): return self.quizquestion_set.all() def __str__(self): return self.title class QuizQuestion(models.Model): """ Вопросы для квиза""" quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.CharField('Вопрос', max_length=1000) created_at = models.DateTimeField('Дата создания', auto_now_add=True, ) updated_at = models.DateTimeField('Дата обновления', auto_now=True, ) def __str__(self): return self.question class Meta: verbose_name = 'Тест' verbose_name_plural = 'Тесты' class QuizAnswer(models.Model): """ Варианты ответов """ question = models.ForeignKey(QuizQuestion, on_delete=models.CASCADE) text = models.CharField('Варианты ответа', max_length=250) is_correct = models.BooleanField('Отметьте правильные', default=False) class Meta: verbose_name = 'Ответ' verbose_name_plural = 'Ответы' def __str__(self): return f'Вариант ответа' admins.py from quiz.models import * from django.contrib import admin from nested_inline.admin import NestedStackedInline, NestedModelAdmin, NestedTabularInline class AnswerInLine(NestedTabularInline): """ Делаем вложенную модель в админке""" … -
is it good to use flask api with django rest framework?
I and my friend was discussing a project idea and I wanted to do it using DRF with vue.js on the front end. then he told me that using flask API with DRF will make the performance better. I really don't remember how and why. do you agree with him and why? -
Hide specific field in drf_yasg django swagger documentation
I have a project with drf_yasg, there is a serializer with a to_internal_value method which is writing a field('mobile_operator_codes') for me. The field is overriden, so we don't need to input it in request. Though we need to output it in response. Documentation(drf_yasg) takes fields='all' and writes everything in request, though we don't need the 'mobile_operator_codes' in request blog. We don't expect it in the request. Serializer is as follows: class ClientSerializer(serializers.ModelSerializer): tags = ClientTagsField(required=False) mobile_operator_code = serializers.CharField(required=False) class Meta: model = Client fields = '__all__' def to_internal_value(self, data): data_overriden = data.copy() if 'phone' in data: data_overriden['mobile_operator_code'] = get_operator_code_from_phone(data['phone']) return super().to_internal_value(data_overriden) View is as follows: class CreateClientView(mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = ClientSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) Model: class Client(models.Model): phone = models.CharField(max_length=11, verbose_name="номер телефона клиента") mobile_operator_code = models.CharField(max_length=3, verbose_name="код мобильного оператора") tags = models.JSONField(null=True, blank=True, verbose_name="теги") timezone = models.CharField(max_length=50, verbose_name="временная зона") # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones def __str__(self): return str(self.phone) + ' ' + str(self.tags) if self.tags else str(self.phone) Swagger documentation: swagger documentation What I tried: read_only in field makes this field not writeble by to_internal_value excluding the field from fields just puts empty value in it(given (required=False)) you cannot use different serializer, because you will still have to … -
Django forms: how to use optional arguments in form class
I'm building a Django web-app which has page create and edit functionality. I create the page and edit the pages using 2 arguments: page title and page contents. Since the edit and create code is very similar except that the edit code doesn't let you change the title of the page I want to make some code that can do both depending on the input. This is the current code I'm using right now. class createPageForm(forms.Form): page_name = forms.CharField() page_contents = forms.CharField(widget=forms.Textarea()) class editPageForm(forms.Form): page_name = forms.CharField(disabled=True) page_contents = forms.CharField(widget=forms.Textarea()) I know that if I wasn't using classes, but functions I could do something like this: def PageForm(forms.Form, disabled=False): page_name = forms.CharField(disabled=disabled) page_contents = forms.CharField(widget=forms.Textarea()) PageForm(disabled=True) PageForm(disabled=False) That is the kind of functionality I'm looking for^^ I tried the following: class PageForm(forms.Form): def __init__(self, disabled=False): self.page_name = forms.CharField(disabled=disabled) self.page_contents = forms.CharField(widget=forms.Textarea()) class PageForm(forms.Form, disabled=False): page_name = forms.CharField(disabled=disabled) page_contents = forms.CharField(widget=forms.Textarea()) Both didn't work and got different errors I couldn't get around. I was hoping someone could lead me in the right direction, since I'm not very familiar with classes.