Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
disable post button after clicked [duplicate]
(new to js) I am having an issue where the user can click the submit button multiple times and the post gets posted multiple times. To fix this I found this JavaScript that is supposed to disable the post button after it is clicked. However when the button is click the post request is not sent and nothing happens. How can I still submit the form but disable the button after the click <form method="post" enctype="multipart/form-data" id="PostForm" data-models-url="{% url 'ajax' %}" novalidate> <!--id="modelForm"--> {% csrf_token %} <fieldset class="django-ckeditor-widget"> <legend class="border-bottom mb-4">New Car</legend> {{ postForm.stuff}} ..... </fieldset> <div class="form-group"> <button id="submit-btn" class="action-btn" type="submit">Post</button> </div> </form> <script type="text/javascript"> document.getElementById("PostForm").addEventListener("submit", function (event) { event.preventDefault(); }); </script> -
Timer is stoping |Django
I've got problem 'cause I created site in django which has chatrooms and thoose chatrooms should be deleted after 300 seconds and my problem is that it sometimes work fine but sometimes timer is freezing and not working. views.py: from django.shortcuts import render, redirect from .models import ChatRoom, Message, Time import random, time from .forms import MessageForm from threading import Thread from django.core.mail import send_mail import datetime def Odliczanie(timer,c): t = int(timer.time) while t > 0: t -= 1 timer.time = str(t) timer.save() time.sleep(1) c.delete() def Create(request): if request.method == 'POST': code = random.randrange(1, 10_000_000_000) if request.POST.get("private") == "clicked": privatecheck = True else: privatecheck = False c = ChatRoom(name = str(code), isprivate = privatecheck) c.save() t = c.time_set.create(time = 300) Thread(target=Odliczanie, args=(t,c)).start() return HttpResponseRedirect('/%i' %int(c.name)) return render(request, 'main/create.html',{}) models.py: import random class ChatRoom(models.Model): name = models.CharField(max_length=10_000_000_000) isprivate = models.BooleanField(default = False) def __str__(self): return self.name class Message(models.Model): ChatRoom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) text = models.CharField(max_length=500) liked = models.BooleanField(default = False) author = models.CharField(max_length= 50, null=True) def __str__(self): return self.text class Time(models.Model): ChatRoom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) time = models.CharField(max_length = 4) I deleted some code in views.py which isn't related to problem -
How do I create a custom format in Django for the following: YYYY-NNNN, where YYYY represents the year and NNNN represents a 4 digit numeric value
I been trying to find ways to create a custom format for a value input for a model. I can't seem to find the adequate way to create a a year then 4 digit number after the slash. I would really appreciate if you could help. -
How would you add a crsf token inside the html
form="<form action='addAppointment/' method='POST' enctype='multipart/form-data'><button type='submit'>Book now</button></form>" I am currently adding the form element to a page through html the goal of this is to book an appointment. How would I go about adding the crsf_token into this or use button instead. {% csrf_token %} Traceback Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. -
Filter data of a JavaScript chart by date range - Django Project
I want to create a Javascript chart with a date selector in my Django project like this example: https://plotlydash.com/pie-chart-with-drop-down-list-and-date-picker-range-in-plotly-dash/ I've already created a date selector input in my chart.html file, which allows me to append the input date value to URL when I click "generate report". (For example: it will append: ?start=2022-02-02&end=2022-02-24). I was also able to call these two dates by {{request.GET.start}} and {{request.GET.start}} in my HTML. My chart data is based on a list of dictionaries, which is defined in views.py: I count the number of records with Mike, Jane and Jack. mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] mike=len(tuple(d for d in mylist if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in mylist if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in mylist if d['Receiver'] == 'Jack')) count = [mike, jane, jack] My JavaScript chart: <!-- pie Chart --> <div class="col-xl-4 col-lg-4"> <div class="card shadow mb-4"> <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between"> <h6 class="m-0 font-weight-bold">Team Chart ({{request.GET.start}} - {{request.GET.end}} )</h6> </div> <!-- Card Body --> <div class="card-body"> <div class="chart-area"> <canvas id="myPieChart"></canvas> <script> var ctx = document.getElementById("myPieChart"); var startDate = … -
"<Post:>" needs to have a value for field "id" before this many-to-many relationship can be used
When i'm trying to add a Post through django admin i get an error that the Post im trying to add needs to have a value for field id. Do you have any idea why? now = datetime.now() class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(unique=True) class Meta: verbose_name_plural = "categories" def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) excerpt = models.CharField(max_length=200) main_image = models.ImageField() author = models.ForeignKey(users.models.CustomUser, on_delete=models.CASCADE, related_name='blog_posts', null=True) content = models.TextField(null=True) created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField(editable=False) category = models.ManyToManyField(Category, related_name='post_category') class Meta: ordering = ['-created_at'] def save(self, *args, **kwargs): if not self.id: self.created_at = now self.updated_at = now def __str__(self): return self.title -
Can't import google api modules in python (vs code)
i'm wondering why i can't import the following modules: I'm using django with a virtual environment to create a web app. I can access to venv with a command pipenv shell but even though the google-api files are in pip freeze folder i still can't manage to use them. I've installed google-api with this pip command: pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib -
Error running WSGI application: ModuleNotFoundError: No module named '_overlapped'
I stuck on this problem. I don't know what should I do. My error throws an error about WSGI. When I saw Error Log, it is working with my local server but getting problem on live 2022-02-23 18:47:32,893: Error running WSGI application 2022-02-23 18:47:32,910: ModuleNotFoundError: No module named '_overlapped' 2022-02-23 18:47:32,910: File "/var/www/lrnglobal_pythonanywhere_com_wsgi.py", line 17, in <module> 2022-02-23 18:47:32,910: application = get_wsgi_application() 2022-02-23 18:47:32,910: 2022-02-23 18:47:32,910: File "/home/lrnglobal/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2022-02-23 18:47:32,910: django.setup(set_prefix=False) 2022-02-23 18:47:32,910: 2022-02-23 18:47:32,910: File "/home/lrnglobal/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup 2022-02-23 18:47:32,910: apps.populate(settings.INSTALLED_APPS) 2022-02-23 18:47:32,911: 2022-02-23 18:47:32,911: File "/home/lrnglobal/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate 2022-02-23 18:47:32,911: app_config.import_models() 2022-02-23 18:47:32,911: 2022-02-23 18:47:32,911: File "/home/lrnglobal/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models 2022-02-23 18:47:32,911: self.models_module = import_module(models_module_name) 2022-02-23 18:47:32,911: 2022-02-23 18:47:32,911: File "/home/lrnglobal/portal/lrnadmin/models.py", line 1, in <module> 2022-02-23 18:47:32,911: from asyncio.windows_events import NULL 2022-02-23 18:47:32,911: 2022-02-23 18:47:32,911: File "/usr/local/lib/python3.9/asyncio/windows_events.py", line 3, in <module> 2022-02-23 18:47:32,911: import _overlapped 2022-02-23 18:47:32,911: *************************************************** 2022-02-23 18:47:32,912: If you're seeing an import error and don't know why, 2022-02-23 18:47:32,912: we have a dedicated help page to help you debug: 2022-02-23 18:47:32,912: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2022-02-23 18:47:32,912: this is my working directory and this is my wsgi file it seems correct import os import sys path = '/home/lrnglobal/portal' if … -
How to add a simple navbar to all my pages?
I'm trying to create a taking notes app in Django framework. I just want to add a simple navigation bar between homepage, adding notes and administration notes. My question is? Where do i locate my html file with the navbar? And how the code should look like? So far i have the following configuration where index.html represents the file for the navbar. I also tried to include the navbar notes_app folder near the other 3 html file, but that does not work. Also,my code for my navbar looks like: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link" href="/notes_app">Homepage</a> <a class="nav-link" href="/notes_app/adaugare">Adaugare</a> <a class="nav-link" href="/notes_app/administrare">Administrare</a> </div> </div> </div> </nav> </body> </html> I want to mention that the language is in Romanian so the meanings for HTML files are: adaugare.html -> the page where i will add new notes adminstrare.html -> the page where i will edit the content of notes … -
How to write query nested subquery using Djnago ORM?
please help me to write something like this query using Django ORM: SELECT label from ( SELECT DISTINCT on (label) unnest("auditorial"."labels") AS "label" FROM "auditorial" ) as subQ WHERE upper(label) LIKE upper('%rec%') ORDER BY label If I have model like this: class Auditorial(models.Model): labels = ArrayField( models.CharField(max_length=64, blank=True) ) I need to provide "suggestions" into select input on website Thank you! -
Avoid changing the address while send GET request (django)
I have url http://127.0.0.1:8000/profile/question/1/ and on the address i have form i want to have like or dislike button on post. everything work fine but url change is the problem. it's my code- > def get_context_data(self, *args, **kwargs): self.object=self.get_object() context = super(QuestionDetail, self).get_context_data(**kwargs) if "like" or "dislike" in self.request.GET: if "like" in self.request.GET: if bool(Like.objects.filter(user=self.request.user, question=self.get_object())) == True: pass else: Like.objects.create(user=self.request.user, question=self.get_object()) elif "dislike" in self.request.GET: if bool(DisLike.objects.create(user=self.request.user, question=self.get_object())) == True: pass else: DisLike.objects.create(user=self.request.user, question=self.get_object()) try: question = Question.objects.get(id=self.kwargs["pk"]) context['detail'] = question except ObjectDoesNotExist: return reverse("Profile:error") <form class="float-right block"> <button type="submit" name="like" class="block mb-2"></button> <button type="submit" name="dislike" class="block"></button> </form> when i click for example like button, url changed and it's http://127.0.0.1:8000/profile/question/1/?like= how to avoid this problem? and what is the problem? thank you -
prevent multiple form submissions
I have been looking for a way to prevent users from clicking the submit button on a form multiple times resulting in the post being submitted multiple times. Most of the post I found on stack were at least 5 years old and they all offered different ways to solve the issue, there didn't appear to be a best practice method on how to remedy this issue. I took a quick look in the docs to see if they have added anything but I didn't see anything. In 2021 what is the best practice to prevent multiple form submissions. -
Expected view Equation1View to be called with a URL keyword argument named "pk"
I'm trying to get data directly from request body in json. Making calculations in API will be main part of my Django REST Api. In the future I'm going to add database from which I'll be getting some data that will be used in calculations. I'm having a problem with error AssertionError: Expected view Equation1View to be called with a URL keyword argument named "pk". Fix your URL conf, or set the 'lookup_field' attribute on the view correctly. I don't know where should I put the pk parameter. Using the api below I should be able to send {"name":"xxx", value:1.23} in request body and get {"emission":1.23} in json response. Ofcourse it will be more complicated in future as getting more data from request body and connecting it with data from db but now I have to make it simple. api urls.py: from .views import Equation1View from django.urls import path urlpatterns = [ path('equation/1', Equation1View.as_view()) #path('equation/2'), #path('equation/3'), ] views.py from aiohttp import request from rest_framework import generics from .serializers import EmissionSerializer, EquaSerializer # Create your views here. class Equation1View(generics.RetrieveAPIView): queryset = '' serializer_class = EquaSerializer(context={'request':request}) serializers.py from rest_framework import serializers class EquaSerializer(serializers.Serializer): emission = serializers.SerializerMethodField('perform_equation') def perform_equation(self): request = self.context.get("request") if … -
Bootstrap Modal close button does not close the modal
I am using the pypi.org boostrap modal as explain in the site. Everything work fines fine as expected but the problem is when I click a button for eg addFoo button and I decided to close the modal using either the close button or X button the modal does not close. -
django.db.utils.OperationalError: unable to open database file f
I have this kind of error File"C:\Users\ComputerPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\ LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 205, in get_new_connection conn = Database.connect(**conn_params) django.db.utils.OperationalError: unable to open database file while this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'myapp', 'USER' : 'postgres', 'PASSWORD': 'er1234', 'HOST': 'localhost' } } -
DJANGO ADMIN TabularInline in TabularInline
I have 3 models models.py class TestObj(models.Model): name = models.CharField('Название', max_length=30) description = models.TextField('Описание теста') topic = models.ManyToManyField(Topic, verbose_name='Тема теста') class Question(models.Model): text = models.TextField('Вопрос') testobj = models.ForeignKey(TestObj, on_delete=models.CASCADE, verbose_name='Тест') many = models.BooleanField('Много ответов', default=False) class Answer(models.Model): text = models.TextField('Ответ') status = models.BooleanField('Верный?', default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='Вопрос') I want to create tests through the admin panel. I want to create quiz questions and answers for each question on the quiz page class AnswerInline(admin.TabularInline): model = Answer class QuestionInline(admin.TabularInline): model = Question @admin.register(TestObj) class TestObjAdmin(admin.ModelAdmin): inlines = (QuestionInline,) how do i add AnswerInline in QuestionInline? -
No file was submitted error when trying to do an axios POST between react and django rest frame work
I am trying to simply upload a file in my react front-end and send it to my Django rest framework back-end API but keep getting no file was submitted. I have tried setting the filefield to require=false however this just posts null. I am not sure what I am doing wrong if anyone can help. model.py class Upload(models.Model): file_uploaded = models.FileField(upload_to='Apps') def __str__(self): return f"{self.file_uploaded}" serializer.py class UploadSerializer(ModelSerializer): class Meta: model = Upload fields = ('file_uploaded',) views.py class UploadViewSet(viewsets.ModelViewSet): queryset = Upload.objects.all() serializer_class = UploadSerializer parser_classes = (MultiPartParser, FormParser,) print(Upload.objects.all()) def post(self, request, *args, **kwargs): fileSerializer = UploadSerializer(data=request.data) if fileSerializer.is_valid(): fileSerializer.save() return Response(fileSerializer.data, status=status.HTTP_201_CREATED) else: return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST) react upload and submit functions handleUpload = (files) =>{ var file = new FormData(); file.append(files.target.files[0].name, files.target.files[0]) this.setState({mfile_JsonFile: file}); } createApp = e => { e.preventDefault(); axios.post( "http://127.0.0.1/api/upload/", this.state.mfile_JsonFile).then(() => {alert("posted")}); }; -
How to apply timezones to Django Model DateTimeFields
When a Django model contains a DateTimeField the date is always saved in UTC timezone. If you add a date that had a time zone the information is translated and will be retrieved differently. This happens even if the TIME_ZONE has been set in settings.py and the date was created using timezone.localtime(timezone.now()). The same issue happens when the date is added dynamically, like with models.DateTimeField(auto_now_add=True) or models.DateTimeField(auto_now=True). How can I retrieve or save date times in the correct timezone? -
drf - how to access field of parent serializer in child serializer
I have 3 models models.py class First(models.Model): is_available = models.BooleanField(default=False) class Second(models.Model): some_field = models.BooleanField(default=False) class Third(models.Model): first = models.ForeignKey(First, null=True, blank=True, on_delete=models.CASCADE) second = models.ForeignKey(Second, null=True, blank=True, on_delete=models.CASCADE) serializers.py class SecondSerializer(serializers.Serializer): some_field = serializers.BooleanField() is_available = serializers.BooleanField() # field from models.First class ThirdSerializer(serializers.Serializer): second = SecondSerializer() views.py class ThirdViewSet(mixins.ListModelMixin, GenericViewSet): ......... def get_queryset(self): return Third.objects.select_related('first', 'second') I have to send the response through ThirdSerializer but First.is_available should be sent in SecondSerializer. How can I achieve that? -
I am trying to use Django paginator with HTML, What am I doing wrong?
I am trying to use pagination in one of my learning projects which is an Ecommerce website. I am trying to load products on the Products page. I followed the django docs tutorial and some youtube. The paginator works like the page 1,2 etc but on all the pages it show every product while I specified in views.py on three. views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() paginator = Paginator(products, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'products': products, 'cartItems': cartItems, 'paginator': page_obj} return render(request, 'store/products.html', context) products.html: <!--Pagination--> <div class="container p-4"> <div class="pagination justify-content-center"> <span class="step-links"> {% if paginator.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ paginator.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ paginator.number }} of {{ paginator.paginator.num_pages }} </span> {% if paginator.has_next %} <a href="?page={{ paginator.next_page_number }}">next</a> <a href="?page={{ paginator.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> <!--end of Pagination--> -
how to install redis 6 on centos 7
Whenenver I install redis on centos it installs version 3.2 which is not compatible with my django channels-redis. I have used commands- sudo yum install redis sudo yum install redis -y Now How do I install my desired version of redis? And I have uninstalled redis as advised( removed the files before uninstall). Thank you. -
Django:Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class DomainUserAdmin
I want to add a phone number field on the admin site when i want to create a new user manually from the admin page, i have proceed doing this by this code: in admin.py from django.contrib.auth.admin import UserAdmin class DomainUserAdmin(UserAdmin): form = DomainUserChangeForm add_fieldsets = ( (None, {'fields': ('email','first_name', 'last_name', 'phone', )}), ) + UserAdmin.add_fieldsets forms.py class DomainUserChangeForm(UserChangeForm): phone = forms.CharField(label='phone') class Meta(UserChangeForm.Meta): model = DomainUser help_texts = { 'username': _('Required. 150 characters or fewer. Letters, digits and \/@/./+/-/_ only.'), # NOQA } models.py: class DomainUser(User): class Meta: proxy = True def __init__(self, *args, **kwargs): self._meta.get_field( 'username' ).validators[0] = DomainUnicodeUsernameValidator() super().__init__(*args, **kwargs) --->it gives me an error: Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class DomainUserAdmin. HELP PLEASE, How i can add a field phone number when i want to signup(create a new user) from the admin page. -
Bootstrap collapsible card not collapsing within a for loop
I am having trouble getting the collapsible cards to collapse when clicked. When a card is clicked, the card does not collapse like it suppose to. I have already linked the Jquery and bootstrap as well. What am I missing? My current methods is from https://www.bootstrapdash.com/bootstrap-4-tutorial/collapse/ <div class="container-fluid p-5"> {% for section in sections %} <div id="accordion" role="tablist" aria-multiselectable="true"> <div class="card"> <div class="card-header" role="tab" id="heading{{section.id}}"> <h5 class="mb-0"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{section.id}}" aria-expanded="true" aria-controls="collapseOne"> Section {{forloop.counter}} </a> </h5> </div> <div id="collapse{{section.id}}" class="collapse show" role="tabpanel" aria-labelledby="heading{{section.id}}"> <div class="card-body"> {% for i in section.coursematerial_set.all %} <p>{{i.lecture_name}}</p> {% endfor %} </div> </div> </div> </div> {% endfor %} </div> -
Exception in thread django-main-thread, SECRET_KEY already installed
I cloned my own repository in GitHub and after installing the necessary dependencies I tried to run my project with: python3 manage.py runserver But when I do that, I get this exception in the thread and I can't see any particular error Exception in thread django-main-thread: Traceback (most recent call last): File "/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 6, in … -
How can i refactor this to remove DRY
I have two serializers implemented here with same methods that is to validate the files 1 and 2 how can i refactor my code here so that i take care of DRY serializers.py class FilecreateSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'file', ) def create(self, data): user = self.context['request'].user if not user.is_anonymous: validated_data.update({'uploaded_by': user.person}) return super().create(data) def file_checking(self, file): ca = pd.read_excel(file, dtype=str) if not something(): raise ValidationError() return file class FileUpdateSerializer(serializers.ModelSerializer): class Meta: model = Mymodel fields = ('file_2',) def file_2_checking(self, file): ca = pd.read_excel(file, dtype=str) if not something(): raise ValidationError() return file