Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to optimize queries in Django Rest Framework serializers (DRF)?
info: I have component model with search_tags field which is a many to many field with Search model and i have a serializer for Component model which is ComponentSerializer and i using get_videos method to get videos for each component and i want to get videos for each search tag in search_tags field and store them into a filtered_data_list and return it as a response The response time is very slow and i want to optimize it and i don't know how to do it (I am new to django and rest framework) These are methods i studied but i don't know how to use them in my case and i don't know if they are the best way to do it or not: prefetch_related and select_related but it didn't work. Use raw sql query but i don't know how to do it. Use django cache but i don't know how to do it. Use django cache and raw sql query but i don't know how to do it. class ComponentSerializer(serializers.ModelSerializer): ''' component serializer ''' videos = serializers.SerializerMethodField() class Meta: model = Component fields = ['title', 'slug', 'videos'] def get_videos(self, obj): filtered_data_list = [] for search in obj.search_tags.select_related('component').filter(is_active=True): ''' Thumbnails … -
Stylesheets to use in django-ckeditor
I'm using django-ckeditor which is a TextArea WYSIWYG editor for creating and editing posts in a future blog. The editor produces beautiful posts, but when I save to the database and go to view it, it appears without the style I initially created in the editor. See the following code: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MyDomain | {{post.title}}</title> <link href="{% static 'ckeditor/ckeditor/contents.css'%}" rel="stylesheet"> </head> <body> <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|linebreaks }} </body> </html> My question is: which styles do I import to present the same view as when I created the post? -
Optimizing dynamic filter
I have this funciton def get_documents_by_metadata(self, params): filters = {} result_filtered = None for index, key in enumerate(params.keys()): filters["metadocument__meta_config__field"] = key filters["metadocument__value__contains"] = params.get(key) if index == 0: result_filtered = super().get_queryset().filter(**filters) else: result_filtered = result_filtered.filter(**filters) return result_filtered I need to filter by dynamic values ( KEY/VALUE metadata registered in my DB), I can't predict what keys Im goint to recieve. My first idea is filter and filter again the result, but I'm sure that exist better way. Ty! -
what are best solutions for hold OTP
I want to create a no password system so user login with email and i sent verification code to the user. user enter email and send request server check email if exist send the otp number to user’s email server need hold otp number so later on compare with user number i want to now in the server side what is the best solution for hold otp code db, file, etc I want to achieve best security and speed for APIs. -
Looking for best practices for Django queries in Python classes
Say I have a Django model Model1 and I have a python class Class1. Class1 has some properties that are derived from values in Model1. What is the best way to accomplish this? Gain access to Mode1 in the Class1 __init__ method, or access Model1 in the Class1 property? Not sure how to define "best way" - more pythonic, more efficient, etc? A very contrived example of what I am asking: class Model1(models.Model): model_id = models.AutoField(primary_key=True) field1 = models.CharField() field2 = models.CharField() class Class1: def __init__(self, value1, value2): self.value1 = value1 self.value2 = value2 self._model1 = Model.objects.get(model_id=self.value1) @property def value3(self): return self._model1.field1 * 10 @property def value4(self): field2 = Model.objects.get(model_id=self.value2).field2 return field2 * 22 Which paradigm is "better" - the property for value4 or value3? I am going to guess the the property for value4 is more efficient because the Model1 query set does not hang around in memory as it does when it is contained in the Class1 __init__. Thanks! -
html2pdf Resize and Fix Copying Onto Same Page
I have the following below: <div> <button id="btn">screenshot</button> </div> <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js"></script> <script> window.onload = function () { console.log("Window is loaded") document.getElementById('btn').addEventListener("click", function () { html2canvas(document.getElementById('test')).then(function (canvas) { document.body.appendChild(canvas); var imgdata = canvas.toDataURL("image/jpg"); var doc = new jspdf.jsPDF(); doc.addImage(imgdata, "JPG", 10, 10); doc.save("sample.pdf"); }); }) } </script> It works BUT not well. The two problems I can't solve are: It opens a PDF with a screenshot of a small section of the page, like it's too zoomed in. It also puts a screenshot of the page on the page itself, this screenshot is stored in my browser session and goes away on a fresh reload. I don't know which part of the code is responsible for that, so I don't how to stop it from doing this. If there was a way to get that screenshot copied to another .html page and the user can view it from there, that might be a workaround. However, I don't know how to manipulate the code to get it to do that and I am only a beginner with javascript/html2pdf; Python is the only language I know right now. I am using DJANGO as my framework if this matters. Thank you! I … -
Django is not rendering my static file (css, images, etc)
I am able to view my site (html)in the browser but none of my mark-up is working. I have checked my stylesheet links for types, settings.py, but I am at a lost. When I run my site I am getting the below responses in my terminal. `[10/Nov/2022 20:46:23] "GET / HTTP/1.1" 200 168 [10/Nov/2022 20:46:23] "GET /static/css/main.css HTTP/1.1" 404 1795 [10/Nov/2022 20:46:23] "GET /static/images/6%2Bcart.png HTTP/1.1" 404 1810` I have tried going over everything possible but cannot locate the issue, any and all feedback would be greatly appreciated. I am not allowed to post images yet so unfortunately, I could not include. I have re-coded, deleted and remade static folder, scoured the internet with no luck yet. -
JWT token authentication in Github Social Authentication
I am working with django github social authentication using dj_rest_auth. I am trying to add JWT token authentication in it. I am trying to get access_token and refresh_token. To get it i want to enter username and password in api view.In social authentication login there is no password. we have Only username and mail id. Is it possible to access token by using only username? If Yes. How is it possible? -
Restrict users to see detailview based on model field value in Django
I am learning and have a change management project where my model contains field confidential which is by default False, however during instance creation so called initiator could tick it as True. This basically means that only users which are part of current record so called signees could open and see the instance. I am trying to apply get_queryset override on my DetailView: # MOC DetailView class MocDetailView(LoginRequiredMixin, DetailView): model = Moc template_name = 'moc/moc_detail.html' def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) for obj in qs: print(obj) confidential = obj.confidential initiator = obj.initiator coordinators = obj.coordinators.all() reviewers = obj.reviewers.all() approvers = obj.approvers.all() preimplements = obj.preimplements.all() authorizers = obj.authorizers.all() postimplements = obj.postimplements.all() closers = obj.closers.all() if initiator and initiator == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(initiator=self.request.user)) return qs for signee in coordinators: coordinator_name = signee.coordinator_name if coordinator_name and coordinator_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(coordinators__coordinator_name=self.request.user)) return qs for signee in reviewers: reviewer_name = signee.reviewer_name if reviewer_name and reviewer_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(reviewers__reviewer_name=self.request.user)) return qs for signee in approvers: approver_name = signee.approver_name if approver_name and approver_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) … -
Django Model Serializer manyToMany relationship
I have problem with Django 4.1.2 (Python 3.8.9). I have 2 entities: Idea and IdeaTheme, which have manyToMany relationship. class Idea(models.Model): short_name = models.CharField(max_length=70) description = models.TextField(null=True, blank=True, default='') class State(models.IntegerChoices): CREATED = 0, _("Создано") TEAM_SEARCHING = 1, _("Поиск команды") IN_PROCESS = 2, _("Реализация") READY = 3, _("Готово") state = models.IntegerField(choices=State.choices, default=State.CREATED) wanted_skills = models.ManyToManyField(to=UserSkill) themes = models.ManyToManyField(to=IdeaTheme, null=True, blank=True) class IdeaTheme(models.Model): name = models.CharField(max_length=70, verbose_name="Название") background_photo = models.ImageField(blank=True, null=True, verbose_name="Изображение для фронта") Also I have ModelSerializer class IdeaSerializer(serializers.ModelSerializer): class Meta: model = Idea fields = '__all__' depth = 1 extra_kwargs = { 'state': { 'read_only': True }, 'pk': { 'read_only': True } } And when I using CreateAPIView in order to create Idea I face the problem, that I must provide IdeaTheme pks. But in the model there are Null and Blank option and I want to create idea without IdeaThemes. I tried to specify IdeaTheme serializer inside IdeaSerializer like this, but Django still require not empty array of IdeaTheme. themes = IdeaThemeSerializer(many=True, required=False) Could someone help me, please, who already has experience using built-in serializers? -
Uploading Image from angular to Django using Rest Api Angular 13 / Django 4.1 Rest Framework
I'm trying to upload an image from Angular to Django using Rest framework, When I try uploading i got the following error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 177: invalid start byte So i tryied most of all the answers but no success. Angular v13 Django v4.1 This is My class Model that I'm trying to fetch : ` class Product(models.Model): famille = models.ForeignKey(Famille, on_delete=models.CASCADE) tva = models.ForeignKey(Tva, on_delete=models.CASCADE) poidsUnity = models.ForeignKey(Poids, on_delete=models.CASCADE, null=True) tailleUnity = models.ForeignKey(Taille, on_delete=models.CASCADE, null=True) couleur = models.ForeignKey(Color, on_delete=models.CASCADE, null=True) marque = models.ForeignKey(Marque, on_delete=models.CASCADE, null=True) poids = models.FloatField(null=True) taille = models.FloatField(null=True) photo = models.ImageField(upload_to='pics', null=True, blank=True) ``` ` This is My Serializer Class : class ProductSerializer(serializers.ModelSerializer): photo = Base64ImageField( max_length=None, use_url=True, allow_empty_file=True, allow_null=True, ) class Meta: model = Product fields = '__all__' ``` ``` ``` ` This is My Views : @csrf_exempt def productCrud(request, id=0): if request.method == 'GET': if id != 0: products = Product.objects.filter(id=id).first() products = ProductSerializer(products) else: products = Product.objects.all() products = ProductSerializer(products, many=True) return JsonResponse(products.data, safe=False) elif request.method == 'POST': product = JSONParser().parse(request) product = ProductSerializer(data=product) if product.is_valid(): product.save() return JsonResponse(product.data, safe=False) return JsonResponse(product.errors, safe=False)` ` urls.py : ` urlpatterns = [ # full path /product/ [get, post, … -
Django - Form that lists the fields for every foreign key
I have this 2 models: class AccountsPlan (models.Model): code = models.CharField(max_length=7, unique=True) name = models.CharField(max_length=100, unique=True) active = models.BooleanField(default=True) class Planning (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT, limit_choices_to={'active': True}) month = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2) This form: class PlanningForm(forms.ModelForm): accountplan = ModelChoiceField(queryset=AccountsPlan.objects.filter(active=True).order_by('code')) month = forms.DateField(required=True) amount = forms.DecimalField(max_digits=14, decimal_places=2, required=True, localize=True) class Meta: model = Planning fields = '__all__' And this view: def new_planning(request): if request.method == 'POST': form = PlanningForm(request.POST) if form.is_valid(): form.save() else: form = PlanningForm() return render(request, 'app/pages/planning/new_planning.html', context={ 'form': form, }) The form works as intended, but right now, I have more than a 100 entries in the AccountsPlan model and this number will increase overtime. The user needs to fill the PlanningForm every month for every foreign key in the AccountsPlan model, so filling one by one is not ideal. Since the month field will be the same for every foreign key and only the amount field is different, what I'm trying to do is this: The form lists every foreign key with an amount field for each one and a single month field. The user selects de date and enter just the amount and that saves the data. I tried this answer and managed … -
Unable to load css while running django in docker
If I access http://0.0.0.0:8000/admin/ The console says the following and the css does not load. The Cross-Origin-Opener-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can also use the 'localhost' origin instead. See https://www.w3.org/TR/powerful-features/#potentially-trustworthy-origin and https://html.spec.whatwg.org/#the-cross-origin-opener-policy-header. My settings is as follows: ALLOWED_HOSTS = ['0.0.0.0', '127.0.0.1', 'localhost'] DISABLE_COLLECTSTATIC = 0 # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "books.apps.BooksConfig", "debug_toolbar", "corsheaders", "django.contrib.postgres", "django_celery_beat", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "corsheaders.middleware.CorsMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "debug_toolbar.middleware.DebugToolbarMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ] ROOT_URLCONF = "search.urls" LOGIN_REDIRECT_URL = "home" LOGOUT_REDIRECT_URL = "home" CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'https://localhost:8000', 'http://0.0.0.0:8000', 'https://0.0.0.0:8000', 'http://127.0.0.1:8000', 'https://127.0.0.1:8000' ) TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] STATIC_URL = "/static/" -
Get Data Problem with Foreignkey Models QuerySet (Django)
I am making django practising. I found a repo and edited to myself. When i came to the get data from models with foreignkey, i get query instead of data. I think my function is a little bit spagetti or my template file. Full repo is here https://github.com/eseymenler/demo2 Here is the output of my codes. First red square is query, but i want second red square datas. Hasta Adı: {{ patient.name }} Hastanın Sağlık Problemi: {{ prob }} Hastanın Boyu: {{ vital }} Hastanın Sigara Kullanım Durumu: {{ social }} First data {{ patient.name }} is very good for me. Thats what i want. But when i get write {{ prob.problem }} it gives me nothing. So where is my fault. But also when i make for loop like this, i get data which i want. So how can i fix this. {% for y in prob %} {{ y.problem }} {% endfor %} And my views.py @login_required() def patienttumbilgiListView(request, id): patient = Patient.objects.get(aadhaarId = id) prob = ProblemList.objects.filter(patient = patient) vital = VitalSign.objects.filter(patient = patient) social = SocialHistory.objects.filter(patient = patient) return render( request, 'patient_records/patient-problem-tum.html', context={'prob': prob, 'vital': vital, 'social': social, 'patient': patient }) and my template file {% extends … -
(MacOS) Django can't find the MySQL driver ... but, why?
Here's the traceback: Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib' Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so' Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file) And here's the problem: $ locate libmysqlclient [...] /usr/local/mysql-8.0.31-macos12-x86_64/lib/libmysqlclient.21.dylib So, the library is there, but Django isn't finding it. So, before I "bang my head uselessly against this thing," especially given that it used to work, will someone out there kindly give me a nudge in the right direction? What am I missing here? I particularly notice that the package is trying the path, /usr/lib... when that is not in fact the proper location here. In particular: I see in the text a reference to @rpath which I am sure is the root cause of the problem – obviously, the value is wrong. (I notice that it does have the library-name right.) I'm frankly not familiar with this @rpath thing, nor exactly what sets it. Thank you kindly in advance ... -
Django Channels Freezes when calling internal Django-Filters API
I am using django-nextjs which required me to install Django Channels. Now this works fine until my frontend makes an API call to a DRF APIView which in turn makes an API call to Django-Filters to return a queryset. This freezes the entire server until the connection times out. Do you have an idea how this could be fixed? My asgi.py import os from django.core.asgi import get_asgi_application from django.urls import re_path, path os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django_nextjs.proxy import NextJSProxyHttpConsumer, NextJSProxyWebsocketConsumer from django.conf import settings http_routes = [re_path(r"", django_asgi_app)] websocket_routers = [] if settings.DEBUG: http_routes.insert(0, re_path(r"^(?:_next|__next|next).*", NextJSProxyHttpConsumer.as_asgi())) websocket_routers.insert(0, path("_next/webpack-hmr", NextJSProxyWebsocketConsumer.as_asgi())) application = ProtocolTypeRouter( { # Django's ASGI application to handle traditional HTTP and websocket requests. "http": URLRouter(http_routes), "websocket": AuthMiddlewareStack(URLRouter(websocket_routers)), # ... } ) And here is my APIView with the internal API call to Django Filters class SearchAPI(APIView): permission_classes = [] def get(self, request, *args, **kwargs): received_params = {} ... full_request = f"{settings.BASE_URL}api/filter-recipes/?{col_to_search}__icontains={search_term}{additional_filters}" print('full_request: ', full_request) response = httpx.get(full_request) print('response: ', response) response = response.json() response = response["results"] if "results" in response else response ... return Response(json.dumps(final_response)) Everything freezes upon calling the get: 'response = httpx.get(full_request)', is there anyway I … -
Filter the logged in Users groups in before saving Django
Hi upon registering a new user all the groups are listed for the user to select from the drop down. I am trying to filter this to only the groups that the logged in user is part of. views.py from .forms import UserRegisterForm @login_required(login_url='login') def addUser(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() group = form.cleaned_data['group'] group.user_set.add(user) return redirect('login') else: form = UserRegisterForm() return render(request, 'base/adduser.html', {'form':form}) forms.py from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ['username', 'password1', 'password2', 'group'] adduser.html > {% extends 'main.html' %} > > {% block content %} <style> > .home-container{ display:grid; grid-template-columns: 1fr 4fr; > > } </style> <div class="home-container"> > > > > <div> > > </div> > <div> > {% include 'settingmenu.html' %} > > </div> > <div></div> > <div> > <form method="POST" action=""> > {% csrf_token %} > > {{form.as_p}} > > <input type="submit" value="Add User" /> > </form> > > > > </div> </div> {% endblock %} -
Why django admin is not reading the __str__ method?
I'm trying to add a str method in my models.py file to my administrative page show me the objects I've register with their own name and not like a 'UserObject(1)' But when I add this method that's what is happening: AttributeError at /admin/crud_app/user/ 'User' object has no attribute 'first_name' models.py -> from django.db import models class User(models.Model): """ A normal class that represents an User object, the attributes are those bellow: """ first_name = models.CharField(name="First Name", max_length=30) last_name = models.CharField(name="Last Name", max_length=30) cpf = models.CharField(name="CPF", max_length=30) age = models.IntegerField(name="Age") email = models.EmailField(name="email", max_length=30) def __str__(self): return self.first_name admin.py -> from django.contrib import admin from .models import User admin.site.register(User) I try to add the str method and I'm was expecting to recive the name that I give to my object registered instead of 'Name object(1)' -
How can I create an index with django that takes into account multiple columns and most importantly a 5 second interval
I want to create an interval for a table that says "each entry will be unique based on it's col a, col b, col c, and a 5 second interval" For example I want to be able to do something like this: class Meta: indexes = [ models.Index(fields=['col_a',]), models.Index(fields=['col_b',]), models.Index(fields=['col_c',]), models.Index(expression='five second interval') ] Is this possible? If so what's the right way to do something like this? -
Why setUpTestData has an argument and setUp doesn't?
Pretty much the title. In django, when creating tests, we have two options, setUp and setUpTestData. I understand that setUp will be called each time a single test runs, while setUpTestData will be called only once and be used in multiple tests. I don't understand what the cls does in setUpTestData(cls), though. And why setUp() doesn' t have that argument? -
django custom admin login page
I have a custom auth mechanism for users and I want to use the same for django admin. All works fine for authenticated users but if an unauthenticated user opens the url /admin he is redirected to /admin/login with the std. login page for admin. I want to redirect to auth/sign-in or block the page. urlpatterns = [ path('admin/', admin.site.urls), path('admin/login', SignInView.as_view(), name='admin/login'), ... Redefining the url like in the code block does not work. Any idea? -
Django Form is not submitting (No POST action on HTML form)
I have created a Django Form but it does not submit after hitting the submit Button. It seems like the HTML is broke because if i hit the submit button Django doesn´t output a POST Action. Template is as follows: <form method="POST"> {% csrf_token %} <div class="relative transform overflow-hidden rounded-lg bg-gray-800 text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg"> <div class="bg-gray-50 dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4"> <div class="sm:flex sm:items-start"> <div class="mt-3 text-center text-gray-200 sm:mt-0 sm:ml-4 sm:text-left"> {{ addForm.email }} {{ addForm.givingLessons }} </div> </div> </div> </div> <input type="submit" class="inline-flex w-full justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-base font-medium text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 sm:ml-3 sm:w-auto sm:text-sm" value="Update" /> </form> views.py def manage_students(request): if request.method == "POST": form = addStudentGivingLessons(request.POST) if form.is_valid(): lessons = form.cleaned_data.get('givingLessons') print(lessons) return redirect('home') else: print("form is not Valid") else: Forms.py class addStudentGivingLessons(forms.Form): email = forms.EmailField() givingLessons = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, queryset = Faecher.objects.all()) -
Django GROUP BY without aggregate
I would like to write the following query in Postgresql using Django ORM: SELECT t.id, t.field1 FROM mytable t JOIN ... JOIN ... WHERE .... GROUP BY id Note that there is NO aggregate function (like SUM, COUNT etc.) in the SELECT part. By the way, it's a perfectly legal SQL to GROUP BY primary key only in Postgresql. How do I write it in Django ORM? I saw workarounds like adding .annotate(dummy=Count('*')) to the queryset (but it slows down the execution) or introducing a dummy custom aggregate function (but it's a dirty hack). How to do it in a clean way? -
is_valid() don't work with my form in Django
i'm a beginner with Django 4.1. I'm using model to edit a form and render it in a webpage. This run correctly. When i click on submit, my function recognize the POST method but never validate the form. I'm sure that i have to fix a bug in my models or my form but i don't know where. in models.py class Auction(models.Model): HOUSE = "HOU" MOTORS = "MOT" PROPERTY = "PPT" HOBBIES = "HOB" INFORMATION_TECHNOLOGY = "IT" MUSIC = "MUS" BOOK = "BOK" CATEGORY_CHOICES = [ (HOUSE, "All for your House"), (MOTORS, "Car, Moto, Boat"), (PROPERTY, "Houses, flats, manors"), (HOBBIES, "Hobbies"), (INFORMATION_TECHNOLOGY, "Laptop, Desktop, Mobile Phone"), (MUSIC, "CD, Musical Intrusments"), (BOOK, "Books, Comics,...") ] ONE = 1 THREE = 3 SEVEN = 7 FOURTEEN = 14 DURATION_CHOICES = [ (ONE, "1 day"), (THREE, "3 days"), (SEVEN, "7 days"), (FOURTEEN, "14 days") ] title = models.CharField(max_length=64) description = models.TextField(max_length=500, blank=True) creation_date = models.DateTimeField(auto_now_add=True) image = models.URLField(null=True, blank=True, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="seller") duration = models.CharField(max_length=7, choices=DURATION_CHOICES, default=SEVEN) category = models.CharField(max_length=3, choices=CATEGORY_CHOICES, default=INFORMATION_TECHNOLOGY) price = models.DecimalField(max_digits=12, decimal_places=2, default=0.0) def __str__(self): return f"{self.id}: {self.title}" in forms.py class CreateListingsForm(forms.ModelForm): class Meta: model = Auction fields = ["title", "description", "image", "category", "duration", "price"] and … -
How to automatically and regularly update database for a web application?
I am new to web development and I have a fundamental question on developing a website that takes queries from the users and searching inside a database. I am developing a website that takes queries from users and searches in an existing database. I already developed the web app part with Django. The app takes some keywords, searches the database, and displays the returned data in a table form. The database is made out of several csv files that are irregularly updated, say every one or two weeks. They are located in some local storage, say /home/james/csv_files/. To develop the website, I first processed the csv files in my local machine and made them into db.sqlite3 file, the default(?) database that comes with Django. I uploaded these to GitLab, including the db.sqlite3, and deployed to see if it works, and it worked file. But current implementation always searches in the uploaded db.sqlite3. I am looking for an automatic way that regularly process the csv files in /home/james/csv_files/ to update the database and let the web app to use the updated database. Where should I start? Currently, there is a python script that reads /home/james/csv_files/*.csv and merge them into /home/steven/project/db.sqlite3. Application …