Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating two separate models for patient and doctor using Django
I want to create registration as a patient and as a doctor such that when user login my website they get two options(as patient or as doctor).How to achieve this using Django? Registration form has different fields for Doctor and Patient. I want code.I'm not able to understand relationship.Also urls.py for this project. -
Django Ñ problem? ValueError: source code string cannot contain null bytes
I'm working on Django and connecting to a remote SQL Server database. I managed to make the connection to the database using the MSSQL engine, but when I run inspectdb, the generated file contains errors due to the character "Ñ", in the file they appear as ±. So when I try to run the server, I get the following error: ValueError: source code string cannot contain null bytes. refering to the generated file with inspectdb I suspect that the problem is related to the database encoded in Modern_Spanish_CI_AS and also Ñ character is causing trouble. So far, I've tried the following: In settings.py, in database options: 'unicode_results': True Also, 'extra_params': 'ClientCharset=utf8' Modifying in base.py: mssql: unicode_results = options.get('unicode_results', True) Some less elegant solutions like opening the generated file with Notepad and saving it in UTF-8 or ISO 8859-1 -
When posting on django website it posts it to a different page
Making a website that has a forum for text posts and a greenhouse page for images, when I try to post on the forum page it posts it to the greenhouse page, and when i try to add a comment on a post in the forum page I get: PlantPost matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/greenhouse/create_comment/1/ Django Version: 5.0.4 Exception Type: DoesNotExist Exception Value: PlantPost matching query does not exist. Exception Location: C:\Users\hurle\OneDrive\Documents\Desktop\profile_env\Lib\site-packages\django\db\models\query.py, line 649, in get Raised during: greenhouse.views.create_comment Python Executable: C:\Users\hurle\OneDrive\Documents\Desktop\profile_env\Scripts\python.exe Python Version: 3.12.1 Python Path: ['C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\bloomhub4', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\hurle\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\profile_env', 'C:\\Users\\hurle\\OneDrive\\Documents\\Desktop\\profile_env\\Lib\\site-packages'] forum create_comment.html {% extends "home.html" %} {% block content %} <h2>Add Comment</h2> <form action="{% url 'forum:create_comment' post.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %}``` **forum create_post.html** ```{% extends "home.html" %} {% block content %} <h2>Create Post</h2> <form action="{% url 'create_post' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} forum models.py from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() image = models.ImageField(upload_to="forum_images/", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content … -
Can I add the controller part of the MVC pattern to the MTV pattern in Django?
I'm trying to develop a multiplayer web game using Django. I understand that in Django's MTV Pattern, the view part takes on the role of the controller. But the view part needs a user in the frontend who accesses the website in order to be able to carry out actions. But in my WebGame there are also actions that need to be executed in the background, which need to be executed at certain times without any user in the frontend. So can I insert a folder in my Django code with the controller classes and specify when which function should be executed regularly? If I'm on the wrong path when it comes to solving my problem, I'm of course also interested in alternative suggestions. I watched a few videos and read a few books, but I couldn't find anything that really matched my problem. -
Calling python package by package name
I want to call my local package utility by its name like in Django django-admin. It has structure like: utility-name [command] I've found the method of calling utility using __ main __.py. Structure of using this method is: python -m myappname. But it isn't what I wanted. So how I can use structure of calling like in django-admin? I'm junior programmer so if this information isn't enough u may ask questions -
Why do I get a Integrity Error when using this code in Django?
I am having issues while learning about SQLite databases in Django. I am trying to check if a specific url is already in the database, but I keep getting a Integrity Error. this is the code that is supposed to check if it is already in the database: if not Songs.objects.filter(tidal_url=song_url): new = Songs(name=name, artist=artist, tidal_url=song_url) new.save() These are my models: from django.db import models from django.contrib.auth.models import User # Create your models here. class Songs(models.Model): name = models.CharField(max_length=255) artist = models.CharField(max_length=255) tidal_url = models.CharField(max_length=255, unique=True) class UserDownload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) song = models.ForeignKey(Songs, on_delete=models.CASCADE) dl_path = models.CharField(max_length=255) Can anyone figure out why this is happening? -
django a filed can not make it althougfh i make makemigrations and migrate
hi i have a filed i cannot make it in database although i make makemigrations and migrte this is models.py ``your text`` class Display(models.Model) : `your text` url=models.URLField(unique=True) `your text` text = models.CharField(max_length=150) `your text` class Display_Data(models.Model) : `your text` displays = models.ManyToManyField(Display,related_name='display_data') `your text` users= models.ForeignKey(UserProfile,on_delete=models.CASCADE,default="1") `your text` choosenum=models.IntegerField() `your text` puplish_date =models.DateTimeField(default=datetime.now) and this is models.py for accounts app `your text`class UserProfile(models.Model): `your text` user=models.OneToOneField(User,on_delete=models.CASCADE) `your text`user_nickname=models.CharField(max_length=150) `your text`nikename_url=models.URLField() `your text`userphoto =models.ImageField(upload_to='imageprofile/%Y/%m/%d/') and this is views.py for display app `your text`def check_url_exists_and_person(url_to_check): `your text`user_info_array = [] `your text`for i in range(1, 6): latest_successful_record = Display_Data.objects.filter(displays__url=url_to_check, choosenum=i).order_by('-puplish_date').first() if latest_successful_record: user_info = { 'user_nickname': latest_successful_record.users.userprofile.nikename, 'url': latest_successful_record.users.userpofile.nikename_url } else: user_info = None user_info_array.append(user_info) return user_info_array i received a mistake from Django 'Unknown column 'display_display_data.users_id' in 'field list'") why database have not a filed user_id although i make it in models.py i make a new database and delete files of migrations in application display and app userprofile and the filed is not create -
I am getting NoReverseMatch error when adding students data in django admin panel
I am a beginner and trying to create a basic college portal. I am getting NoReverseMatch at /admin/api/student/add/ error when adding students data in django-admin panel. urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/',admin.site.urls), path('api/',include('api.urls')), ] admin.py from django.contrib import admin from .models import Student, Instructor, Course, Enrollment @admin.register(Student) class StudentAdmin(admin.ModelAdmin): list_display = ['std_id', 'firstname', 'lastname', 'date_of_birth', 'cgpa'] @admin.register(Course) class CourseAdmin(admin.ModelAdmin): list_display = ['course_id', 'coursename', 'cred_hrs'] @admin.register(Instructor) class InstructorAdmin(admin.ModelAdmin): list_display = ['instructor_id', 'instructor_name'] @admin.register(Enrollment) class EnrollmentAdmin(admin.ModelAdmin): list_display = ['enrollment_id', 'student', 'course', 'instructor'] models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Student(models.Model): std_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) date_of_birth = models.DateField() cgpa = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(4)] ) class Course(models.Model): CREDIT_HOURS_CHOICES = [ (1, '1 credit hour'), (2, '2 credit hours'), (3, '3 credit hours'), ] course_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) coursename = models.CharField(max_length=100) cred_hrs = models.IntegerField(choices=CREDIT_HOURS_CHOICES) class Instructor(models.Model): instructor_id = models.CharField(max_length=6,primary_key = True, unique=True , editable=False) instructor_name = models.CharField(max_length=100) class Enrollment(models.Model): enrollment_id = models.AutoField(primary_key=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) instructor = models.ForeignKey(Instructor,on_delete = models.CASCADE) I am new to this kind of stuff so yeah... … -
Group by or distinct for django to remove the row which has the duplicate column
I have table like this below Table A ID name score 1 aaa 100 2 bbb 200 3 ccc 300 4 bbb 100 5 kkk 600 6 ccc 300 Now name bbb and ccc is duplicated so, I want to remove then and depict like this, ID name score 1 aaa 100 2 bbb 200 3 ccc 300 5 kkk 600 I found out that django model doesn't have groupby so, I guess need to use annotate or distinct So my idea is like this below, MyModel.objects.annotate(Count('name')) However it doesn't work as I hope. Any help or hint? -
Passing information from view to form with FormWizard
I'm trying to pass data from my view to my form class using WizardView. Without WizardView, I do this using get_forms_kwargs() like the below: def get_form_kwargs(self): kwargs = super(MenuAdd, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs And in my form class I use: def __init__(self, *args, **kwargs): self.month = kwargs.pop('month', None) All good - I'm able to use 'month' for validation in e.g. clean(). When I'm using WizardView though, I'm specifying the step in get_forms_kwargs() as follows, per the docs: def get_form_kwargs(self, step=0): kwargs = super(MenuAddWizard, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs My get_form() doesn't like this: File "python312\Lib\site-packages\formtools\wizard\views.py", line 311, in post return self.render_next_step(form) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "python312\Lib\site-packages\formtools\wizard\views.py", line 322, in render_next_step new_form = self.get_form( ^^^^^^^^^^^^^^ File "myproject\views.py", line 1614, in get_form form = super().get_form(step, data, files) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "python312\Lib\site-packages\formtools\wizard\views.py", line 432, in get_form return form_class(**kwargs) ^^^^^^^^^^^^^^^^^^^^ TypeError: BaseFormSet.__init__() got an unexpected keyword argument 'month' Any idea how to properly pass kwargs (or any other way) to a form with Django Form Wizard? -
I don't understand why the Django built in 'Reverse' function is not working
I am trying to learn Django in python, when today, I stumbled upon this error: "NoReverseMatch at /downloader/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name." I am not sure why this is happening, but here is my code: (this is the views.py code) if not request.user.is_authenticated: return HttpResponseRedirect(reverse("login")) (here is my urls.py) urlpatterns = [ path("", views.index, name="index"), path("add/", views.add, name="add"), path('scrape/', views.scrape_all, name='scrape_all'), path('find_url/', views.find_song_urls, name='find_song_urls'), path('downloader/', views.downloader, name="downloader"), path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("create_acount/", views.create_account, name="create_account") ] I was just trying to make a login function with my project but I don't get what I am doing wrong. -
How to know if the syntax of my urls is a valid django url syntax?
I generate my URLs dynamically and I want to know if there is a way to check if the syntax is valid or not. Because I'll create my URL from the Django admin panel, and if the syntax isn't correct for Django, the code will crash. For example, if I make a mistake and create a URL like this: test/<:custom_pk>/`, the app will crash, and I won't be able to modify it from the admin panel because of the crash. The error is : File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 307, in init self.converters = _route_to_regex(str(route), is_endpoint)[1] File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 277, in _route_to_regex raise ImproperlyConfigured( django.core.Exceptions.ImproperlyConfigured: URL route 'test/<:custom_id>' uses parameter '<:custom_id>' which isn't a valid Python identifier. I try to send to my urlpatterns an url which had an incorrect syntax and i except this error : File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 307, in init self.converters = _route_to_regex(str(route), is_endpoint)[1] File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 277, in _route_to_regex raise ImproperlyConfigured( django.core.Exceptions.ImproperlyConfigured: URL route 'test/<:custom_id>' uses parameter '<:custom_id>' which isn't a valid Python identifier. -
A very faulty Django when it comes to rendering image in my template
Right lets try this again. My Django images are not showing in my template. Despite setting this up correctly. This is my setup - a fully replicable setup -, as follows: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #urls.py from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.views.static import serve urlpatterns = [ path('<uuid:uuid>', views.details), ] # Only for development. Do not use this in production. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import MediaModule def details(request, uuid): articles = MediaModule.objects.all().values() article = get_object_or_404(MediaModule, uuid=uuid) title = article.article_headline return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles}) #media-article.html <img src="{{article.article_image.url}}" alt="{{article.article_image.url}}"/> #models.py from django.db import models import uuid # Create your models here. class MediaModule(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_image = models.ImageField(upload_to='media/assets') This is my file directory layout: Root-| media-| templates-| models.py views.py urls.y media-article.html media-| assets-| image.jpg Is there a valid reason as to why, hen I go to the debug console in my browser - does it give me a 404 error despite the … -
bypassing integrityError gotten from unique field in a django model
I want a unique field generated at database level. The way unique=True works is it raises an error if it see's a duplicate value in the database. I don't want that though, I want it to simply generate a new unique number instead of raising an error. This is the model that gives a user an account number, Any help will be much appreciated class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) account_number = ShortUUIDField(unique=True,length=10, max_length=25, prefix="217", alphabet="1234567890") -
In django how can I resolve a reverse error when copying text from an html table row and attempting to write it to a text file?
I have a django app with a page that shows a data table of text strings populated from a model. Each string is a website url. I need to be able to click on any one of these rows and have that url string written to a text file. What I have so far results in a 'reverse' error as soon as the server tries to load the home page. Here is the model: class Environment(models.Model): url = models.CharField(max_length = 250, null=True, blank=True) def __str__(self): return self.url Here is the view for the home page, which displays a list of urls populated from the model: def home(request): envs = Environment.objects.all() f = open('environment.txt', 'r') file_content = f.read() f.close() context = {'title':'Home Page', 'year':datetime.now().year, 'envs':envs, 'file_content':file_content} return render(request, 'app/home.html', context) here is the view for the writing of the url text to the file: def write_url_to_file(request, url): with open('environment.txt', 'w') as file: file.write(url) file.close() return redirect('app:home') Here is the url pattern: path('write-url/<str:url>/', views.write_url_to_file, name='write_url_to_file'), Here is the template tag. The idea is to click a url to write it to a text file: <table> <tr> <th>Environment</th> </tr> {% for env in envs %} <tr> <td><a href="{% url 'app:write_url_to_file' env.url %}">{{ env.url … -
Why do I get a server side HTTP 400 error when I try to access my django server with my mobile phone?
I have set up a simple, local running django server which provides buttons to trigger some bash commands on the server (currently my MacBook Pro). The output of these commands is then displayed on the website. Anyways: The website is working fine as long as I access it from the DuckDuckGo Browser on my MacBook. I also tried with the Brave Browser installed on my Desktop PC - works fine. Now, as I try to access the website from my iPhone, a connection is established, the buttons are working and also, the text on the buttons disappeared. But more importantly, I get a strange error on the server inside the console which is running the server. The error says: [26/Apr/2024 11:33:04] code 400, message Bad request version ('p¤\x99é4rÙu*\x08\x8dÎ\x06¨A©\x06\x8f?l\x19\x9fz\x97\x00,êê\x13\x01\x13\x02\x13\x03À,À+Ì©À0À/̨À') [26/Apr/2024 11:33:04] You're accessing the development server over HTTPS, but it only supports HTTP. Using WireShark, I compared the package traffic between the iPhone and the server, and between the desktop / macbook and the server. It was obvious that the phone tries to use HTTPS / TLS to connect to the server while the desktop / macbook connect using HTTP. But as this fails, the TLSv1 package contains the following alert … -
Why is Django randomly deleting images from my template for no reason
Django never ceases to baffle me with completely uncalled for actions. I I have a media article template which is derived from a Django model. All works a treat and looks awesome, except for the images. One minute they're present, the next Django needs a new glasses prescription as it suddenly decides it can't see the image which is blatantly in the directory with which I have set up. Here's my full reproduceable example and see if anyone can figure out why Django decides its not going to show the image: #models.py from django.db import models import uuid # Create your models here. .... uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_image = models.ImageField(upload_to='media/assets') .... In my views.py, I have the following: def details(request, uuid): articles = MediaModule.objects.all().values() article = get_object_or_404(MediaModule, uuid=uuid) title = article.article_headline return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles}) The file directory is as follows: Root| |- media |- template | - media-article.html |- media | - assets | - image.jpg #media-article.html <img src="{{article.article_image}}" alt="{{article.article_image}}"/> Just why does Django think "Ah-hah, there's the image!", and then says "Actually, I'm going to deliberate pretend the image is not there, because I am going to be difficult now" Why does it … -
"Error: InconsistentMigrationHistory - Django migration admin.0001_initial applied before its dependency Users.0001_initial"
I am encountering an error while running `python manage.py migrate` in my Django project. The error message is as follows: It appears that there is an inconsistency in the migration history of my Django project. Specifically, the `admin.0001_initial` migration is being applied before its dependency `Users.0001_initial`. How can I resolve this issue and ensure that migrations are applied in the correct order? Thank you for your assistance. i tried python manage.py makemigrations and then python manage.py migrate Database connection is good even im able to see dabase table on server but on local machine there is no table \dt List of relations Schema | Name | Type | Owner --------+---------------------+-------+-------- public | django_content_type | table | cc_app public | django_migrations | table | cc_app (2 rows) -
Django-tables2 linkify to other app of project: TemplateDoesNotExist error
Since my project is a bigger one, I have several apps with each app having some database tables (with each table in its own file): project --project -all -overview -home In all/probe_list.html I have a table which displays Probe objects. I want to link the probe name to a details page that is in the overview app (overview/probe_details.html). The link works and shows the correct URL 127.0.0.1:8000/overview/probe_detail/1 but I get TemplateDoesNotExist error since django searches for all/probe_detail.html. project/urls.py urlpatterns = [ path('', include('home.urls')), path('all/', include('all.urls', namespace='all')), path('overview/', include('overview.urls', namespace='overview')), ] all/urls.py app_name = 'all' urlpatterns = [ path('probe_list', views.AllProbesView.as_view()), ] all/models/probe.py class Probe(Compound): targetName = models.CharField(max_length = 100, verbose_name="Target(s)") inVivoActivity = models.CharField(max_length=10, verbose_name="In vivo use"); mechanismOfAction = models.CharField(max_length = 255, verbose_name="Mechanism") def get_absolute_url(self): return reverse('overview:probe_detail', args=[str(self.id)]) def __str__(self): return f'{self.name}, {self.targetName}, {self.mechanismOfAction},{self.inVivoActivity}' class Meta: app_label = 'all' all/tables.py class AllProbesTable(tables.Table): name = tables.Column(linkify=True) class Meta: model = Probe template_name = "django_tables2/bootstrap5-responsive.html" sequence = ("targetName", "name", "mechanismOfAction" ,"inVivoActivity",) exclude = ("id",) all/views.py class AllProbesView(SingleTableView): model = Probe table_class = AllProbesTable queryset = Probe.objects.all() template_name = "all/probe_list.html" all/templates/all/probe_list.html {% load render_table from django_tables2 %} {% render_table table %} overview/urls.py app_name = 'overview' urlpatterns = [ path('probe_detail/<int:pk>', views.ProbeDetailView.as_view(), name="probe_detail"), ] overview/views.py (not ready … -
PostgreSQL: How to tag every table in my database? Generic Foreign Keys, array column, or other method
I'm currently designing a PostgreSQL database where I need to implement a tagging functionality. Essentially, any item from any table in my database can be tagged via key-value tags, very much like Azure tags. I'm considering different approaches for implementing this feature and I'm confused about the best approach: Using Django's Generic Foreign Keys: One approach I'm considering is leveraging Django's Generic Foreign Keys functionality to create a versatile "Tags" table that can reference any other table in the database. This allows flexibility and avoids complex logic. However, there might be drawbacks like performance implications or the database not making sense without Django's ORM. Manual Implementation in a single table, without Generic Foreign Keys: Another option is to implement the "Tags" table manually without relying on Django's Generic Foreign Keys. I would create a separate table that can reference any other table in the database, but without the use of formal foreign keys. This would require to either store some logic in the database or the backend, being more complex to maintain. Separate cross-reference tags table for each table: Alternatively, I could create a separate table (i.e. car_tags, house_tags, person_tags) for each table in my database that requires tagging. This … -
How do I setup "Django" to generate multiple 'STATIC_ROOT' deployment directories in its settings.py?
Here's the problem, when migrating multiple 'STATICFILES_DIRS', I am good to go, and the server continues to run with no errors... ... Here's the snippet to my 'STATICFILES_DIRS' ... ... STATIC_URL = 'Application/' #Multiple Static Directories STATICFILES_DIRS = [ os.path.join('Application', 'Bootstrap'), os.path.join('Application', 'html'), ] #End of Multiple Static Directories STATIC_ROOT = 'Application/templates/Application' ... ... As for the actual problem I've encountered during the "python3 manage.py runserver" command, the snippet error is this ... ... STATIC_URL = 'Application/' #Multiple Static Directories STATICFILES_DIRS = [ os.path.join('Application', 'Bootstrap'), os.path.join('Application', 'html'), ] #End of Multiple Static Directories #Multiple Static Root Directories STATIC_ROOT = [ os.path.join('Application', 'templates/Application'), os.path.join('Domains', 'https://example.com'), ] #End of Multiple Static Root Directories ... ... Are there any ways to solve this error for Django to read/generate multiple 'STATIC_ROOT' deployment directories? Regards, ~ Rickey Kenneybrew -
Create SQL function using Django migrations command
I am using Django Framework in Python with MySQL Database. For adding a table in the database, I create a class in models.py and then run python manage.py makemigrations. This creates the migration file in my app with the table columns details. Now, similarly, I want to create a new function in my database. For now, I create a new empty migration file in my app using python manage.py makemigrations --empty myApp and then add the SQL code to the migration file operations[ migrations.RunSQL('Create function SQL Code') ] This editing migration file can be done on a local or testing environment but is not advisable in the production environment. Is there any better way to create the MySQL function through Django Migrations command or models.py that works similarly to tables and creates functions only 1 time when we use the migrate command? -
Django: Change Datatable by input value [closed]
I have an input field where the user can input specific 'year', and it will show all related rows. It's not the search function that I want, this one is different. There are multiple rows that has the same information, so if I use the search bar, it won't give me rows from other 'year'. So all the info in my datatable will depend on what is in the input field. I'm not sure if you get what I mean. Thank you! -
How do I update status to either expired or active depending on date and time?
I have an application built in Django. The application allows businesses to manage their day-to-day operations and has features like; HR Management, Sales, Point of Sale, Accounting, etc. For businesses to be able to attach discounts on their products, I have created a Discount model: class Discount(CommonField): name = models.CharField(max_length=255, blank=True, null=True) discount = models.DecimalField(max_digits=15, decimal_places=2) discount_type = models.CharField(max_length=255, choices=DISCOUNT_TYPE_CHOICES, blank=True, null=True) discounted_products_count = models.PositiveSmallIntegerField(default=0) start_date = models.DateTimeField(blank=True, null=True) expiry_date = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=255, default="inactive", choices=DISCOUNT_STATUS) objects = DiscountModelManager() Discounts have a start date and an expiry date which have been included in the model, they also have a status field that will determine if the status is expired, active, or inactive. One of the challenges I was facing had to do with at what point I should update the status of discounts. To overcome this challenge, I created a Model Manager to have a central place where the logic of updating the status is placed; class DiscountModelManager(TenantAwareManager): def get_queryset(self): queryset = super().get_queryset() self.change_promo_code_if_end_date_extended(queryset) self.activate_discount_if_start_date_reached(queryset) self.expire_discount_if_expiry_date_reached(queryset) return super().get_queryset() def change_promo_code_if_end_date_extended(self, queryset): """ Activates promo codes if expiry_date has been extended and the status is expired. """ queryset.filter(expiry_date__gte=timezone.now(), status="expired").update(status="active") def activate_discount_if_start_date_reached(self, queryset): """ Activates promo codes if start_date has … -
Provider in create Social App in Django Administration is blank
I tried to do google auth in Django but got stuck when there wasn't any provider in the create social app i already creates the sites as my local host and tried changing site Id to 1 and 2 still it didnt show the problem INSTALLED APPS TEMPLATES I wanted to implement sign in with google but seeing a vid from youtube but i got stuck at the providers. In providers it should show google but it didn't i tried most things i know even though a beginner. Kindly help me. And it didnt show any error though. I can show u the code if u asked its just if i upload it notes as spam