Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IsAuthenticated Permission Error Cannot Input Token from Login
how to authenticate using tokens in django DRF? I'm trying to create a token authentication system using rest_framework.permissions.IsAuthenticated in views, but I can't input tokens, token status has not been entered, I create views like this, I read it here (https://www.django-rest-framework.org/api-guide/permissions/), and I adjusted it like the documentation but it still doesn't work, I tried using postman to check the response but it's still the same, can anyone help? -
Need to get the Foreign key value instead of ID in the database table using Django
model class Project(models.Model): project_name = models.CharField(max_length=20) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(Default_User,related_name='users',default=None) description=models.TextField() type=models.TextField() #dropdown start_date = models.DateTimeField(max_length=10) end_date=models.DateTimeField(max_length=10) technical_contact_name = models.CharField(max_length=30) email=models.EmailField(max_length=254,default=None) phone = PhoneField(blank=True) delivery_head_contact_name=models.CharField(max_length=30) class Meta: db_table ='Project' def __str__(self): return self.project_name model class Job(models.Model): job_name=models.CharField(max_length=50) user= models.ForeignKey(Default_User,on_delete=CASCADE) project = ChainedForeignKey(Project,chained_field="user", chained_model_field="user",related_name='projects',show_all=False, auto_choose=True, sort=True) date = models.DateField(max_length=10,default=None) class Meta: db_table ='Job' def __str__(self): return '{}'.format(self.job_name) serializers class ProjectSerializers(serializers.ModelSerializer): class Meta: model= Project fields= '__all__' class Job_Serializers(serializers.ModelSerializer): job = serializers.StringRelatedField() class Meta: model= Job fields= ('id','job_name','user','project','date','job',) I need to get the foreign key value displayed in the database table of Job model but as per the above code it is displaying the Foreign key ID. For example I linked the project model in the Job model and in the db table it is showing the Project_id as(1,2,3) but i need to return the values of that id as(app, learning etc). Please help me to get the values of the foreign key value instead of ID in the database table. -
Can't connect to Postgres from Django using a connection service file (on Windows)
I have successfully set up Django and Postgres, and I can get them to work together when I put all of the Postgres parameters in the Django settings.py file. However, as shown in the Django documentation, I want to use a Postgres connection service file instead. I've created a service file (C:\Program Files\PostgreSQL\14\etc\pg_service.conf) that looks like this: [test_svc_1] host=localhost user=django_admin dbname=MyDbName port=5432 Launching Postgres from the command line with this file seems to work fine, as it prompts me for the password: > psql service=test_svc_1 Password for user django_admin: However, when I try to make migrations with Django, I get the following error: Traceback (most recent call last): File "C:\...\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\...\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\...\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\...\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\...\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\...\psycopg2\__init__.py",line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: definition of service "test_svc_1" not found There were other exceptions related to this one, such as: django.db.utils.OperationalError: definition of service "test_svc_1" not found but they all pointed back to not finding the service "test_svc_1". Here is an excerpt … -
ModuleNotFoundError virtual environment pythonanywhere in scheduled task
I am trying to schedule a task, but when running the script I get: ModuleNotFoundError: No module named 'clients' Even this is an installed app within my django project. I already added a hashbang/shebang as: #!/usr/bin/venv python3.9 #!/usr/bin/python3.9 Either option gets me the same error message. I think my code for the schedule task is good, but here it is anyways: cd /home/myusername/myproject/maintenance && workon venv && python3.9 mantenimientosemanal.py Any help will be really appreciated. Thanks. -
Writing a manuall (command line) triggered script to bulk change some DB values in Django?
I know that the best practice is to generally use these https://docs.djangoproject.com/en/4.0/topics/migrations/#data-migrations, but I have been told that automatic migrations are risky and the powers that be want me to write a manual script that can be triggered manually on production instead. What would be the best way to go about doing this? Where would be the best place for it to live in the Django repo? How do I import everything I need? Anyone have an example? -
Django: calling a function and let it run in different thread with out waiting and affecting the main thread
I'm trying to work out how to run a process in a background thread in Django. Here is a api view which gets called by user and i need that (Crawler.crawl(request.user)) function to run independently and complete the work. User hitting this api view will not have to wait or the request time out will also not be an issue. class CrawlApiView(APIView): permission_classes = [IsAdminUser, ] def get(self, request, format=None): Crawler.crawl(request.user) response = { "Crawl has Started ", } return Response(response, status=status.HTTP_201_CREATED) -
How to get past 12 months total applicants number in months wise in django
I want to get last 12 months applicants data in months wise view. If this is March then i need to get data of [3,2,1,12,...,4] in this scenario. Here is my model: class Applicant(models.Model): full_name = models.CharField(max_length=200, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, auto_now=False) ..... While i try query: Applicant.objects.values('created_at__month')annotate(total = Count('created_at__month')) it return values like [{'created_at__month': 2, 'total': 3}, {'created_at__month': 3, 'total': 13}]. If I have 2022's month March total applicant 22 and 2021's month March total applicant 20, this query return value 42 in created_at__month: 3, but I need only past 12 months data from this month. How can I write this query efficiently? -
How do I join together two Django querysets that are themselves results of joins (four tables involved)?
I have four related models in my Django app, and while I've got the basic and moderately advanced query syntax down I'm struggling with how to get this particular advanced query to work. My app is a scheduling app for a mountain biking team. For a given event (table 1), I want to combine together team member's (table 2) RSVPs (table 3) along with their relative rankings (table 4) for that event (back to table 1), which is information we use to group attending riders by their abilities. Since riders' skills change throughout the season and we want to track that, their rank is not a single number that we can just store as a single attribute on the TeamMember model (though that would definitely simplify this particular query). Here are the models (minus some irrelevant details for clarity): class TeamMember(AbstractUser): class Category(models.TextChoices): STUDENT = 'S', 'Student Athlete' PARENT = 'P', 'Parent' RIDE_LEADER = 'R', 'Ride Leader' COACH = 'C', 'Coach' category = models.CharField('Category', choices=Category.choices, max_length=1) # Also has first_name, last_name, etc from AbstractUser, # along with some other fields not relevant for this question class Event(models.Model): class EventType(models.TextChoices): PRACTICE = 'P', 'Practice' RACE = 'R', 'Race' type = models.CharField('Event … -
How do I show a form and 2 inputs to upload multiple images in the template and in the view?
I want to make an input that uploads multiple images. I have been reviewing some tutorials and my experience makes me not understand many things. I placed a view but in the template, where the input should appear, this appears: <QuerySet []> Obviously that should not be there, the input should appear that uploads the images when clicked. Can you see my code? can you give me a hint? html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="col-md-4"> <div class="mb-3"> <label class="form-label">Insurance company</label> {{ form.compañia_seguros }} <div class="invalid-feedback"> Please provide a website. </div> </div> </div> </div> <div class="row mb-3"> <div class="col-md-4"> <div class="mb-3"> <label>Cliente</label> {{ form.cliente }} </div> </div> </div> <div class="tab-pane" id="pictures" role="tabpanel"> <div> {{ images }} <label for="file-input" class="btn btn-outline-success">Upload images</label> <p id="num-of-files">No files chosen</p> <div id="images"></div> </div> </div> <div class="tab-pane" id="warranty" role="tabpanel"> <div> {{ garantias }} <label for="file-inputz" class="btn btn-outline-success">Upload images</label> <p id="num-of-filez">No files chosen</p> <div id="imagez"></div> </div> <br> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </div> </form> views.py def create_carros(request): if request.method == "POST": form = CarroForm(request.POST) images = request.FILES.getlist('fotosCarro') garantias = request.FILES.getlist('garantia') for image in images: Carro.objects.create(fotosCarro=image) for garantia in garantias: Carro.objects.create(garantias=garantia) form = CarroForm(request.POST) images = FotosCarro.objects.all() garantias = Garantia.objects.all() return render(request, 'carros/carros-form-add.html', {'images': images,'garantias': … -
How do I use localstorage.getItem or setItem to send a post request in my react application?
I am using jwt in authentication backend. According to a tutorial, I was able to successfully send a get request in react frontend using the following code. export const load_user = () => async (dispatch) => { if (localStorage.getItem("access")) { const config = { headers: { "Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem("access")}`, Accept: "application/json", }, }; try { const res = await axios.get( `${process.env.REACT_APP_API_URL}/api/auth/users/me/`, config ); dispatch({ type: USER_LOADED_SUCCESS, payload: res.data, }); } catch (err) { dispatch({ type: USER_LOADED_FAIL, }); } } else { dispatch({ type: USER_LOADED_FAIL, }); } }; However, I am unable to send post request, I have tried coming up with my own code but still no success. Here is my code: export const client_information_create = (age, phone_number, country, city, alergy, gender) => async (dispatch) => { if (localStorage.getItem('access')) { const config = { headers: { "Content-Type": "application/json", "Authorization": `JWT ${localStorage.getItem('access')}`, "Accept": 'application/json' }, }; const body = JSON.stringify({ age, phone_number, country, city, alergy, gender, }); try { const res = await axios.post( `${process.env.REACT_APP_API_URL}/api/list/InformationView/`, body, config ); if (res.data != null){ dispatch({ type: INFORMATION_SUCCESS, payload: res.data, }); } else { dispatch({ type: INFORMATION_FAIL, }); } } catch (err) { dispatch({ type: INFORMATION_FAIL, }); } } }; How do … -
Filtering certain queries in Django ORM
I am struggling to query certain data by filtering it and then displaying it on my template. I am trying to display on my template each branch_cc from a given data set that I have already uploaded, how many loans where issued for each branch_cc with a funded_date in 2021 and the total amount of all those loans for each branch_cc. models.py from django.db import models class Loan(models.Model): funded_date = models.DateTimeField(auto_now_add=False, blank=True) respa_date = models.DateTimeField(auto_now_add=False, blank=True) loan_amount = models.FloatField(null=True, blank=True, default=None) branch_cc = models.IntegerField(default=0, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py from django.shortcuts import render from .models import Loan import datetime from django.db.models import Sum def index(request): # Funded Dates all_loans = Loan.objects.all() filter = Loan.objects.filter(funded_date__year=2021).count() context = { 'all_loans': all_loans, 'filter': filter, } return render(request, 'index.html', context) index.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <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>Document</title> </head> <body> <h1> 2021 Funded Date Loans </h1> <table class="table"> <thead> <tr> <th scope="col">Branch CC</th> <th scope="col">Count</th> <th scope="col">Amount</th> </tr> </thead> <tbody> {% for loan in all_loans %} <tr> <th scope="row"> {{loan.branch_cc}} <br> </th> {%endfor%} </tr> {% for count in filter %} <tr> <th scope="row"> {{count}} </th> {% endfor … -
Custom django pagination in CSS
I would like that the buttons of pagination have a little space between them ! Not like what I have right now : I do not get how the parameter display and justify work together. What should I change in the css to space them. Thank you for your help. Here is my code : html <div class="pagination"> {% if files.has_previous %} <a class="pagination-action" href="?page=1"> <i class='bx bx-chevrons-left' aria-hidden="true"></i> </a> <a class="pagination-action" href="?page={{ files.previous_page_number }}"> <i class='bx bx-chevron-left' aria-hidden="true"></i> </a> {% endif %} {% for num in files.paginator.page_range %} {% if files.number == num %} <span class="pagination-number pagination-current">{{ num }}</span> {% elif num > files.number|add:'-3' and num < files.number|add:'3' %} <a class="pagination-number" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if files.has_next %} <a class="pagination-action" href="?page={{ files.next_page_number }}"> <i class='bx bx-chevron-right' aria-hidden="true"></i> </a> <a class="pagination-action" href="?page={{ files.paginator.num_pages }}"> <i class='bx bx-chevrons-right' aria-hidden="true"></i> </a> {% endif %} </div> css .pagination { display: flex; margin-top: 15px; align-items: center; justify-content: center; } .pagination a { text-decoration: none; } .pagination-number { padding: 12px 17px; border-radius: 2px; color: #fff; background-color: #6D85C7; } .pagination-number:hover, .pagination-current { background-color: #3354AA; } .pagination-action { margin: 0 2px; display: flex; padding: 1px 2px; color: #fff; font-size: … -
Use django_filters to query a list that contains any item in query params
^^ I'm having a Django model that contains a JSON field to store a list, like so: class Movie(models.Model): tags = JSONField() As such, a movie mymovie contains a list of tags, such as: mymovie.tags = ["horror", "love", "adventure"]. And now, I want a query to fetch all movies having at least one tag of a list of tags, like so: GET /movies?tags=horror,cowboy In my previous example, the query will get mymovie, because it has horror in its tag, even if it doesn't have cowboy. Using *django_filters, I managed to do it with the following implementation: class CharInFilter(BaseInFilter, CharFilter): pass class MovieFilter(FilterSet): class Meta: model = Movie fields = ["tags"] tags = CharInFilter(method="tags_filter") def tags_filter(self, queryset, name, value): # value will contain a list of tags, and we want any movie that at least one of # its tag is in the list of provided tags query = Q() for tag in value: query |= Q( tags__icontains=tag ) if query: queryset = queryset.filter(query) return queryset It works, but it feels very hacky, and I won't be surprised if an ad hoc implementation of this exist. Can someone have a better idea ? Thank youuuu ^^ -
Populate stock predictions in django database with models
I have a code which outputs the prediction of stocks. I've been trying to figure out how to populate the predictions into the database. Every time the code runs, it should modify the database with the new predictions. This is my 'predictions.py': import yfinance as yf import numpy as np # Processing data as arrays import pandas as pd # Used to create a dataframe that holds all data from keras.models import load_model # Used to load existing models import datetime import joblib def models_loader(folder, name, days = [1, 5, 30]): model = [] for i in days: model.append(load_model(folder+'/'+ name + '_' + str(i) + '.h5')) return model days = [1,5,14,30,90] #Day intervals scaler = joblib.load('scaler.sav') models = models_loader('ML Model','Model', days) #Load models has_Run = False companies = ['TSLA', 'AAPL','SIRI','GGB','PLUG'] while True: print("Has started") time = datetime.datetime.today() schedule = datetime.time(17,0,0) if time.hour == schedule.hour and has_Run==False: #change second time hour to schedule hour last = datetime.date.today() td = datetime.timedelta(100) start = last - td for symbols in companies: print(symbols) predINV= [] data = yf.download(symbols,start = start, end = last) data = data.filter(['Close']) if len(data.index) > 59: INPUT = data.values INPUT = INPUT[-60:] scaled_input = scaler.fit_transform(INPUT) scaled_input = np.reshape(scaled_input, (-1,60,1)) for … -
Django deployment to Heroku error: python: can't open file '/app/backend.manage.py': [Errno 2] No such file or directory , is this a Procfile error?
I've once again come to beg stackoverflow for help. I am attempting to deploy a django project to Heroku and I'm getting slapped left and right with errors but hopefully this is the last one. 2022-03-07T22:03:09.363036+00:00 heroku[release.9772]: Starting process with command `/bin/sh -c 'if curl https://heroku-release-output.s3.amazonaws.com/log-stream?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJ3LIQ2SWG7V76SVQ%2F20220307%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220307T220304Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=ddb760b1c36e913b7c0cc984428e3b853cdac67755e4cfa6038cef77a37b6a25 --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2022-03-07T22:03:10.031451+00:00 heroku[release.9772]: State changed from starting to up 2022-03-07T22:03:10.527868+00:00 app[release.9772]: python: can't open file '/app/backend.manage.py': [Errno 2] No such file or directory 2022-03-07T22:03:10.706087+00:00 heroku[release.9772]: Process exited with status 2 2022-03-07T22:03:10.901301+00:00 heroku[release.9772]: State changed from up to complete 2022-03-07T22:02:37.000000+00:00 app[api]: Build started by user email@protonmail.com 2022-03-07T22:03:03.734406+00:00 app[api]: Deploy 922870fe by user email@protonmail.com 2022-03-07T22:03:03.734406+00:00 app[api]: Running release v26 commands by user email@protonmail.com 2022-03-07T22:03:05.039171+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2022-03-07T22:03:05.039171+00:00 app[api]: chmod u+x /tmp/log-stream 2022-03-07T22:03:05.039171+00:00 app[api]: /tmp/log-stream /bin/sh -c '"'"'python backend.manage.py makemigrations - - no-input'"'"' 2022-03-07T22:03:05.039171+00:00 app[api]: else 2022-03-07T22:03:05.039171+00:00 app[api]: python backend.manage.py makemigrations - - no-input 2022-03-07T22:03:05.039171+00:00 app[api]: fi'` by user email@protonmail.com 2022-03-07T22:03:12.919074+00:00 app[api]: Release v26 command failed by user email@protonmail.com 2022-03-07T22:03:15.000000+00:00 app[api]: Build succeeded And when I try to run the program in a virtual environment on my local machine using the command … -
django admin: best way to update ForeignKey field (using AutocompleteSelect) for multiple objects at once
I'm pretty new to django and having some trouble trying to update an admin autocomplete_field for multiple rows at once. In the list page of PrimaryModelAdmin, I'd like to find an efficient way to update the foreign_field to the same value for multiple PrimaryModel objects. It seems like the best way to achieve this is with a custom action that has an intermediary page. I'm just having real trouble on how to use the AutocompleteSelect widget on this page. Does anyone have any ideas or advice on whether I'm even going down the right path? Cheers # in models.py class PrimaryModel(models.Model): ... foreign_field = models.ForeignKey( ForiegnModel, null=True, blank=True, on_delete=models.RESTRICT ) class ForeignModel(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255, null=False) # in admin.py @admin.register(models.PrimaryModel) class PrimaryModelAdmin(admin.ModelAdmin): autocomplete_fields = ["foreign_model"] -
Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework
I use in my study project django rest framework.I get an error 403 Forbidden (CSRF token missing or incorrect, when I try to save using the POST method. Here is my code html <form id = "product_form" method = "post"> {% csrf_token %} <input type = "hidden" name = "id" id = "id"> <p>Назвние:<input name = "name" id = "name"></p> <p><input type = "reset" value = "Oчистить"></p> <input type = "submit" value = "Сохранить"> </form> Here is my code js: let productUpdater = new XMLHttpRequest(); productUpdater.addEventListener('readystatechange', () => { if (productUpdater.readyState == 4) { if ((productUpdater.status == 200) || (productUpdater.status == 201)) { listLoad(); name.form.reset(); id.value = ''; } else { window.alert(productUpdater.statusText) } } } ); name.form.addEventListener('submit', (evt) => { evt.preventDefault(); // let vid = id.value, url, method; let vid = id.value; if (vid) { url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/'; method = 'PUT'; } else { url = 'http://127.0.0.1:8000/books/api_category/'; method = 'POST'; } let data = JSON.stringify({id: vid,nameCategory: name.value}); productUpdater.open(method, url, true); productUpdater.setRequestHeader('Content-Type', 'application/json'); productUpdater.send(data); }) Here is my views.py: @api_view(['GET', 'POST']) def api_products(request): if request.method == 'GET': productsAll = CategoryMaskarad.objects.all() serializer = CategorySerializer(productsAll, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return … -
How to see Django admin panel elements reordered in another tabs?
I want to reorder my django models in admin panel. I found the django-modeladmin-reorder package and installed it. I did everything according to the documentation, but I still have a problem. Reordering elements are being shown only on the main page of the website, if I click on a model to add or edit I see the old reorder. How can I see the new reorders in other tabs ? Good order: https://i.imgur.com/69N1CRs.png Bad order: https://i.imgur.com/9UYLXbX.png This is the code in settings.py ADMIN_REORDER = ( # First group {'app': 'website', 'label': 'Postări', 'models': ('website.Article', 'website.Research', 'website.Reports', 'website.Advocacy', 'website.Document', 'website.Domain', 'website.News', ) }, # Second group: same app, but different label {'app': 'website', 'label': 'Categorii', 'models': ('website.ArticleTag', 'website.ResearchTag', 'website.ReportsTag', 'website.AdvocacyTag', 'website.DocumentTag', 'website.DomainTag', 'website.NewsTag', ) }, {'app': 'website', 'label': 'Video', 'models': ('website.Video', 'website.MainVideo', ) }, {'app': 'website', 'label': 'Rapoarte', 'models': ('website.Reports', ) }, ) -
Django rest_framework DefaultRouter() class vs normal url
I'm using REST in Django, And I couldn't understand what is the main difference between classic URL and instantiating DefaultRouter() for registering URL by ViewSet. Is it possible to use classic URL in URLS.py instead of instantiating the object for a ViewSet View ? I just know HTTP method in ViewSet translate methods to retrieve, list and etc... Thanks for your help. -
django how to hide url and show renamed value?
I am using django-tables2 and trying to hide url and rename it on field. for example, url link is www.youtube.com but on actual field, I want it to show as 'link' instead of revealing entire url link. how do I achieve this? tables.py class MyVideoTable(tables.Table): class Meta: model = PPVideo fields = ('title', 'url') models.py class PPVideo title = models.CharField('Title', max_length=100, null=True) url = models.URLField('URL', max_length=150, null=True) -
Django AWS tutorial working for tutorial but not for full project
I'm following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I follow the tutorial exactly, except use Django 4.0.3 and Python 3.8. It works for deploying a sample project, but when I make the settings.py exactly the same and try to put up my full project, I get the follow errors: health degraded 502 Bad Gateway nginx/1.20.0 failed (111: Connection refused) while connecting to upstream I tried to add gunicorn too but nothing was changing. But why would the same setup work for a simple sample project but not for my larger personal project? -
Python manage.py runserver is showing that python is not installed on my system
Whenever I run python manage.py runserver on my terminal I keep getting Python was not found, run without arguments to install from Microsoft -
How to add logic to a model getter that uses inheritance?
I have a model for a Task class Task(BaseTask): class Meta: db_table = 'task' verbose_name_plural = 'Tasks' def __str__(self): return f'Task {self.id}' def __unicode__(self): return f'Task {self.id}' that is inherited from BaseTask class BaseTask(BaseModel): class Meta: abstract = True task_status = models.CharField( choices=TASK_STATUS_CHOICES, blank=True, max_length=200, default=WAITING ) expiration_date = models.DateTimeField(blank=True, null=True, default=None) I want the task_status for Task to return FAILED if the current date is past the expiration date. I thought I could add a getter to Task like: def get_task_status(self): return FAILED if self.expiration_date and \ check_task_is_expired(self) else self.task_status but that doesn't seem to be working. How can I accomplish adding logic to task_status so it returns FAILED after the expiration date? I'm aware of @property but other models depend on BaseTask and Task so I don't want to change the field name. -
django-registration sending activation and reset emails
I am trying to send activation and reset email in Django, but I am facing some challenges and I would be grateful if someone could kindly help me out.onfigurations in settings.py file as below #setting.py EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST ='smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER ='email@gmail.com' EMAIL_HOST_PASSWORD ='gmailpasword' EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = ‘mail.mysite.com’ DEFAULT_FROM_EMAIL = 'noreply@mysite.com' EMAIL_HOST_USER = 'noreply@mysite.com' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_USE_TLS = True EMAIL_PORT = port The first configuration is with Gmail which work fine in development but in production (shared Linux server) it does not work at all. The second configuration with an email I set up on webmail(cPanel) which is not working in either development or production. -
Getting the length of a certain row Django ORM
I am trying to query how many loans had a funded_date in the year 2021 and the total amount of those loans then show it on a template. I think I have the total amount right but am struggling on how to query and display how many loans had a funded_date in the year 2021 Views.py from django.shortcuts import render from .models import Loan import datetime from django.db.models import Sum def index(request): branch_cc = Loan.objects.filter(funded_date__year=2021) sum = branch_cc.aggregate(Sum('branch_cc')) number = branch_cc context = { 'all_loans': Loan.objects.all(), 'sum': sum, "branch_cc": branch_cc } return render(request, 'index.html', context) index.html <!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>Document</title> </head> <body> <h1> {{sum}} <br> </h1> </body> </html> models.py from django.db import models class Loan(models.Model): funded_date = models.DateTimeField(auto_now_add=False, blank=True) respa_date = models.DateTimeField(auto_now_add=False, blank=True) loan_amount = models.FloatField(null=True, blank=True, default=None) branch_cc = models.IntegerField(default=0, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)