Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use __str__ children classes methods when calling parent class
I've some classes like these : class Event(models.Model): beginning = models.fields.DateTimeField(null=False, blank=True, default=date.today) end = models.fields.DateTimeField(null=False, blank=True, default=date.today) class Festival(models.Model): name = models.fields.CharField(max_length=100, blank=True) def __str__(self) -> str: return f"{self.name}" class FestivalEdition(Event): type = "festival_edition" father_festival = models.ForeignKey(Festival, default="", on_delete=models.CASCADE, related_name="edition") def __str__(self) -> str: return f"{self.festival_name} {self.year}" As you can see, only the children classes have their __str__ methods. When I use Event (by the admin interface or by shell), the name is like this <Event: Event object (1)>. How can I use the __str__ methods of the children (and children of children) classes when calling the parent class ? I've read the official documentation of Django about inheritance and this post. I tried this : class Event(models.Model): objects2 = InheritanceManager() # The __str__ of Event call the __str__ of children models def __str__(self) -> str: event_name = Event.objects2.filter(pk=self.pk).select_subclasses()[0].__str__() return f"{event_name}" It works well but only with the children but not the children of the children because I get this recursion Error in this case : RecursionError: maximum recursion depth exceeded while calling a Python object. -
Method Not Allowed (POST) in django
I use axious for requests But I get this error POST http://127.0.0.1:8000/dashbaord/Menu/editStatus 405 (Method Not Allowed) What should I do to solve this problem? myscript.js: let changeStatus = (id, place) => { axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios({ method: 'post', url: 'editStatus', data: { 'tes1': 'test', 'tes2': 'test' }, headers: { "content-type": "application/json" } }).then(function (response) { console.log('dsdsdsd') }).catch(function (error) { console.log(error) }); } urls.py path('editStatus', EditMenuItemStatus.as_view(), name="edit_status_item") views.py class EditMenuItemStatus(BaseDetailView): def post(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) -
Datables.net resize column manually resizable colimd
I know this is not a builtin but I have been searching so long for a solution. If anyone knows that would be really great!!! I HAVE TRIED A LOT of solutions but none fit the reorder and other builtins functions... -
WSGI Django Apache, AH01630: client denied by server configuration
I've seen very very similar issues but i don't see how the fixes are relevant to my issue. I have a django server running and working fine, I've setup apache for it to run there with the config file as: Alias /static /home/dev/pidjango/gamificationECM2434/mysite/static <Directory /home/dev/pidjango/gamificationECM2434/mysite/static> Require all granted </Directory> <Directory /home/dev/pidjango/gamificationECM2434/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django python-path=/home/dev/pidjango/gamificationECM2434/mysite python-home=/home/dev/pidjango/djenv WSGIProcessGroup exSeed WSGIScriptAlias / /home/dev/pidjango/gamificationECM2434/mysite/mysite Any help to figure out the issue would be great thank you :) -
Session or Token auth for Backend and two Frontend apps at different locations
I have a Django App which acts backend and some endpoint built with Django REST Framework. There are 2 pieces of frontend interacting with my Django app. I have not implemented auth/login to my app. But before i do that, i have few questions to ask. Below is a picture of the system. Both React_user is a React app BUT React_admin is a low-code app like Retool (drag & drop components to make UI connected via REST API to backend) which is sitting at differnt servers i.e physically seperated at differnt locations React_user is the app for customer where they should be able to login with username and password created by React_admin React_admin is the on who creates customers, create username, password for each customer. Think of this as walk-in account creation as there is no sign-up for customers. So, React_admin creates customer credentials from the React app managed by admin, again is sitting at differnt server. For simplicity, let's say React_admin is hosted at the office itself. To create users, i'm using basic django Users model comes out of the box.So, to create a user, there is a an endpoint made with Django REST Framwork. The endpoint is https://mapp.com/rest/create_user … -
Django Plotting Separate Models By Date Month In Highcharts
I have two models that I'm trying to plot counts of each by month on a single chart in Highcharts class Foo(models.Model): foo_user = models.ForeignKey(User, on_delete=models.CASCADE) foo_title = models.CharField(max_length=200) foo_date = models.DateTimeField() class Bar(models.Model): bar_user = models.ForeignKey(User, on_delete=models.CASCADE) bar_title = models.CharField(max_length=200) bar_date = models.DateTimeField() I get the data, combine the querysets, and sort by month foo_data = Foo.objects.annotate(month=TruncMonth('foo_date')).values('month').annotate(foo=Count('id')).order_by('-month') bar_data = Bar.objects.annotate(month=TruncMonth('bar_date')).values('month').annotate(bar=Count('id')).order_by('-month') data = chain(foo_data, bar_data) ordered_data = sorted(data, key=lambda obj: obj['month'], reverse=True) At this point I'm lost and feel like my whole approach is most likely all wrong, but I can't figure out what to do - I add the data to lists and send to the Highchart plot like so. I've gotten it to work if both Foo and Bar both have items in each month, but as soon as one one has an object in a month where the other doesn't the whole thing is throw off. chart_labels = [] foo_chart_data = [] bar_chart_data = [] for row in ordered_data: if row['month'] not in chart_labels: chart_labels.append((row['month']).strftime("%B %Y")) if 'foo' in row: foo_chart_data.append(row['foo']) else: pass if 'bar' in row: bar_chart_data.append(row['bar']) else: pass This is Highchart setup Highcharts.chart(chartContainer, { chart: {type: 'column'}, title: {text: 'Foos & Bars Created'}, xAxis: {categories: … -
Django Pass tag dynamic to div class
I have a progress bar in a table similar to this: I can pass the value "2" for the percentage, but I cannot pass the value 2 to the aria-valuenow class that sets how fill is shown the progress bar. How could I pass the dynamic value to aria-valuenow so the progress bar shows the right filling? I tried {{value.3}},"{{value.3}}", the same with only one {} and with/without % %. I really run out of imagination. {% for key,value in ctxt.items %} <tr><td>{{value.0}}</td><td>{{value.1}}</td><td> {% if value.3 %} <div class="progress align-content-center position-relative" style="height: 25px;"> <div class="progress-bar" role="progressbar" style="width: 25%;" aria-valuenow= "{% value.3 %}" aria-valuemin="0" aria-valuemax="100"></div> <small class="justify-content-center d-flex position-absolute w-100">{{value.3}}%</small> </div> {% endif %} </td></tr> {% endfor %} *Another battle is to put the "2%" vertically centered and not in the top with the position-absolute commands. If you know this, really appreciated too! -
end points for calendar as PDF in Django REST Framework
Anyone know how to make an end points request(backend) creating a school calendar as a PDF in Django REST Framework? I don't know what to do when comes to generate a PDF. -
django ModelForm validation failing with newly created objects
I have a django ModelForm called AdditionalDealSetupForm with the following code: class AdditionalDealSetupForm(ModelForm): required_css_class = "required" lead_underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), label="Lead Underwriter(s):", required=False, widget=forms.SelectMultiple( attrs={"class": "lead_underwriter kds-form-control"} ), ) underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), required=False, label="Underwriter(s):", widget=forms.SelectMultiple(attrs={"class": "underwriter kds-form-control"}) ) def clean(self): pass def clean_underwriters(self): pass print(self.data.items()) class Meta: model = AdditionalDeal fields = [ "lead_underwriters", "underwriters", ] """ Labels for the fields we didn't override """ labels = {} I want to be able to create new underwriters and lead underwriters, which are both many to many fields linked to the Underwriters Model: class AdditionalDeal(TimestampedSafeDeleteModel): id: PrimaryKeyIDType = models.AutoField(primary_key=True) ModIsDealPrivateChoices = [ ("Y", "Yes"), ("N", "No"), ] # Relations deal_setup: ForeignKeyType[t.Optional["DealSetup"]] = models.ForeignKey( "DealSetup", on_delete=models.SET_NULL, null=True, blank=True, related_name="additional_deal_set", ) if t.TYPE_CHECKING: deal_setup_id: ForeignKeyIDType lead_underwriters = models.ManyToManyField( Underwriters, related_name="DealLeadUnderwriter", validators=[validate_underwriters], ) underwriters = models.ManyToManyField( Underwriters, related_name="DealUnderwriter" ) class Meta: db_table = "Additional_Deal" verbose_name_plural = "Additional Deal" unique_together = ("deal_setup",) The problem is that when the form gets instantiated its failing validation implicitly being called by django. The values that are being passed in the request object’s QueryDict look like this: request.POST: <QueryDict: {'csrfmiddlewaretoken': ['lU65eYaubaCgpTtRFQIou9yM9LdmbRt8GAD1XMowV2PdRhxfVRQAXIjRzozCNKqn'], 'cutoff_date': ['08/01/1900'], 'closing_date': ['08/15/1988'], 'deal_private': ['Y'], 'lead_underwriters': ['2'], 'underwriters': ['1', '2', 'test4']}> You can see above that … -
What is the alternative for this.props.match.params for class based views in react
import React, { Component } from 'react' import {render} from "react-dom" import { withRouter } from 'react-router-dom'; import { useParams } from 'react-router-dom' export default class Items extends Component { constructor(props){ super(props); this.state = { price:0, name: "", description: '', } const { id } = useParams(); this.getProductDetails(); } getProductDetails(){ fetch('/api/get-product' + '?id=' + id).then((response) => response.json()).then((data) => { this.setState({ price: data.price, name: data.name, }) }); } render() { return ( <div><h1>This is the Id{id}</h1></div> ) } } I tried using this.props.match.params but my page didnt render, I've used useParams() and it still doesnt work. I need to get the id from the browser and fetch information from my api is there any solution for this? -
instantiate objects and calling methods from a different class when constructing an object
This is my Django Reconciliation class from mytransactions app (below). Every time I do a Reconciliation, I also want to create a log object from a class called TransactionLog (see below) and call a method check_if_needs_consolidation() from a another app (mymoney) and class (Balance). How can I do it? Reconciliation Class, mytransactions app (models.py): class Reconciliation(models.Model): notes = models.CharField(max_length=50) account = models.ForeignKey('mymoney.Account', on_delete=models.CASCADE,) date = models.DateField(default=timezone.now) amount = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.notes TransactionLog (mytransactions app, models.py) class TransactionLog(models.Model): label = models.ForeignKey(Label, on_delete=models.CASCADE, blank=True, null=True) amount = models.DecimalField(max_digits=10, decimal_places=2) date = models.DateField(default=timezone.now, null=False) notes = models.CharField(max_length=300, blank=True) account = models.ForeignKey('mymoney.Account', on_delete=models.CASCADE) beneficiary = models.ForeignKey('mybeneficiaries.Beneficiary', on_delete=models.CASCADE) is_cleared = models.BooleanField("Cleared") def __str__(self): return str(self.beneficiary) Balance class from mymoney app, and the check_if_needs_consolidation() method I want to call: class Balance(models.Model): date = models.DateField(auto_now_add=True) account = models.ForeignKey('mymoney.account', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=15,decimal_places=2) #def check_if_needs_consolidation(month): -
How to know if the user completed login or not and close the server in youtube api and python
I want to make a web app using django and I want to make sure that the user completed login into his youtube account or not because the user may click on the button to go to the page where he can log into his account using this code flow.run_local_server(port=8080, prompt='consent', authorization_prompt_message='', timeout_seconds=40 ) and he may don't complete login process when I added timeout secondes argument it works but if the user took more than 40 seconds it raises AttributeError : 'NoneType' object has no attribute 'replace' and if the user clicks on the button to go to the page where he can log into his youtube account and He backs to the previus page and clicked on the button again it raisesOSError at /channels/ : [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted So what basicly I want to do is two things first : I want to show a success message if the user successfully logged into his account and I can make the message itself but I need a help for "when I will add it" second : I want to solve the second problem OSError at /channels/ so what … -
Add argument to Django imageField to change location
questions: I have an image_upload_handler function for my imageField's in my model. This function takes two arguments as explained on the documentation. Can I add another argument to this? I would like to use this function for multiple fields but want to change the location for the images depending on the argument. So like this: def image_upload_handler(location, instance, filename): fpath = pathlib.Path(filename) new_fname = str(uuid.uuid1()) return f"{location}/{new_fname}{fpath.suffix}" is this possible? -
Having trouble with the authentication process of logging in Facebook from my Django project
I am new to Django and I wanted to build a Django application that could allow users to log in using Facebook, so I have followed every step listed in this tutorial https://www.digitalocean.com/community/tutorials/django-authentication-with-facebook-instagram-and-linkedin Despite following the same step, I still getting errors after providing my password and click on the continue button. Here are two errors that I've encountered: URL blocked This redirect failed because the redirect URI is not white-listed in the app's client OAuth settings. Make sure that the client and web OAuth logins are on and add all your app domains as valid OAuth redirect URIs. The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings. My configuration for the app in Facebook developers valid OAuth Redirect URIs: https://127.0.0.1:8000/ app domains: localhost site url: https://localhost:8000/ I tried to search for cues everywhere but found nothing in the end. Is there anyone faced this kind of issue before? How can I make it work? Urgently need help with this 🙏🙏🙏 -
Displaying images blobs on Django html templates using SaS token
I'm currently trying to get blob images to be displayed in the html of django templates using Sas but I don't see any online implementation examples. I have currently the SaS token but I don't know how to implement it to Django. I tried to manualy add the token to the end of the url: https://{account}.blob.core.windows.net/{container}/{path}.jpg/?sp=r&st=2023-03-11T17:53:36Z&se=2050-03-12T01:53:36Z&sv=2021-12-02&sr=c&sig={****} -
Is there a way to extend django's handling of bulk data that is returned from the DB?
I have implemented a custom field with a from_db_value() method and get_db_prep_value() method. These effectively act as a layer between the caller and the data in the database, and it works well. I used it to implement a lookup the data in a secondary store. The problem is that for bulk data (e.g. list(MyModel.objects.all())), my function from_db_value() will get called O(n) times, which means that if it does something costly (e.g. my use case of lookup in a secondary store) it's really inefficient. What is the best way to "capture" bulk calls and do the conversion in one go? -
Making pagination work with multiple tables in Django
I have a html page in which you can change the table displayed based on the value of a select box. The pagination does not seem to work as intended. When the page is initially loaded the pagination works fine however when changing the the table and trying to go to the next page it loads the second page of the default table. Here are the relevant parts in the template: <h1 id="tableHeader">Users</h1> <div id="template"> {% include user_table %} </div> <select class="form-select" name="view_select" id="view_select" onchange="loadTable()"> <option value="1" selected>Users</option> <option value="2">Categories</option> </select> The JavaScript function loadTable: function loadTable() { var select_value = document.getElementById("view_select").value; if (select_value == 1) { var url = "{% url 'user_table' %}"; } else if (select_value == 2) { var url = "{% url 'category_table' %}"; } else { return; } $.ajax({ url: url, type: "GET", success: function(response) { $("#template").html(response); } }); } The url.py file: path('user_table/', views.user_table, name='user_table'), path('category_table/', views.category_table, name='category_table'), The relevant views: def admin_dashboard(request): if (request.user.is_staff == False) and (request.user.is_superuser == False): return redirect('landing_page') else: if request.method == 'POST': # IF CREATE USER BUTTON CLICKED if 'create_user' in request.POST: form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() return redirect('admin_dashboard') # IF CREATE CATEGORY BUTTON CLICKED … -
Django Channels does not connect to redis on heroku
I am using django chanels for sending real time notification, on the local development server it works fine with redis url redis://127.0.0.1:6379 but when I go to production on Heroku it couldn't connect meanwhile celery works fine on the same redis url on Heroku. this is the channel layer I am using and the REDIS_URL is set properly in the environment variables both locally and on production. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [env('REDIS_URL', default='redis://localhost:6379')], }, }, } The Error I get is the following: 2023-03-12T13:15:29.051013+00:00 app[web.1]: ERROR 2023-03-12 13:15:29,047 server 2 140084942075712 Exception inside application: Error 1 connecting to ec2-50-17-163-82.compute-1.amazonaws.com:7550. 1. 2023-03-12T13:15:29.051015+00:00 app[web.1]: Traceback (most recent call last): 2023-03-12T13:15:29.051016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/redis/asyncio/connection.py", line 603, in connect 2023-03-12T13:15:29.051016+00:00 app[web.1]: await self.retry.call_with_retry( 2023-03-12T13:15:29.051016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/redis/asyncio/retry.py", line 59, in call_with_retry 2023-03-12T13:15:29.051017+00:00 app[web.1]: return await do() 2023-03-12T13:15:29.051017+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/redis/asyncio/connection.py", line 640, in _connect 2023-03-12T13:15:29.051017+00:00 app[web.1]: reader, writer = await asyncio.open_connection( 2023-03-12T13:15:29.051018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/streams.py", line 52, in open_connection 2023-03-12T13:15:29.051019+00:00 app[web.1]: transport, _ = await loop.create_connection( 2023-03-12T13:15:29.051019+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 1090, in create_connection 2023-03-12T13:15:29.051019+00:00 app[web.1]: transport, protocol = await self._create_connection_transport( 2023-03-12T13:15:29.051019+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 1120, in _create_connection_transport 2023-03-12T13:15:29.051020+00:00 app[web.1]: await waiter 2023-03-12T13:15:29.051020+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/sslproto.py", line … -
Cutting stock problem methods and techniques
I have taken an interest in creating a web app using React based on cutting stock problem. I have some questions about the topic: Should i pair React with Django or is there better alternative? I'm gonna implement two algorithms each for 1 Dimensional and 2 Dimensional (So 4 in total). What algorithms should i implement? Is there any recommended resources online that will aid me in my work? Result: A simple cutting stock problem app -
Django not displaying images through pagination container bootstrap class
Django images are only showing icons not full image when a user tries to post a new image onto the platform. i created a products function that was supposed to post onto the main home page of my ecommerce django application product images with prices, only that the prices and all the other information is shown, but for the images, the links to the specific images are working, but the display of the real images is not working. Views.py def products(request): if request.method == 'POST': pagination_content = "" page_number = request.POST['data[page]'] if request.POST['data[page]'] else 1 page = int(page_number) name = request.POST['data[name]'] sort = '-' if request.POST['data[sort]'] == 'DESC' else '' search = request.POST['data[search]'] max = int(request.POST['data[max]']) cur_page = page page -= 1 per_page = max # Set the number of results to display start = page * per_page # If search keyword is not empty, we include a query for searching # the "content" or "name" fields in the database for any matched strings. if search: all_posts = Product.objects.filter(Q(content__contains = search) | Q(name__contains = search)).exclude(status = 0).order_by(sort + name)[start:per_page] count = Product.objects.filter(Q(content__contains = search) | Q(name__contains = search)).exclude(status = 0).count() else: all_posts = Product.objects.exclude(status = 0).order_by(sort + name)[start:cur_page * max] … -
Problems with installing Django project on hosting.(Error: Web application could not be started)
I used hosting Beget. Relying on this instruction of my hosting i tried to locally install this versions of Python==3.7.2 Django==3.2.13. I successfully installed Python and Django. I also configured .htaccess and passenger_wsgi.py files, following this instruction. passenger_wsgi.py: # -*- coding: utf-8 -*- import os, sys sys.path.insert(0, '/home/n/nurtugur/nurtugur.beget.tech/coolsite') sys.path.insert(1, '/home/n/nurtugur/nurtugur.beget.tech/djangoenv/lib/python3.7/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = 'coolsite.settings' from django.core.wsgi import get_wsgi_application .htaccess: PassengerEnabled On PassengerPython /home/n/nurtugur/nurtugur.beget.tech/djangoenv/bin/python3.7 Error that i got I haven't any ideas of why it doesn't work. I guess only ones that can help me are people who have experience in using Beget hosting. -
Having a error while running a django project from github in vscode editor, Error goes as follows that was displayed on localhost:
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/result/ Django Version: 2.2.13 Python Version: 3.9.0 Traceback: File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/predictor/views.py" in model_form_upload 35. meta = getmetadata(uploadfile) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/predictor/Metadata.py" in getmetadata 6. y, sr = librosa.load(filename) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/lazy_loader/init.py" in getattr 77. attr = getattr(submod, name) File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/lazy_loader/init.py" in getattr 76. submod = importlib.import_module(submod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py" in import_module 127. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>" in _gcd_import 1030. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load 1007. <source code not available> File "<frozen importlib._bootstrap>" in _find_and_load_unlocked 986. <source code not available> File "<frozen importlib._bootstrap>" in _load_unlocked 680. <source code not available> File "<frozen importlib._bootstrap_external>" in exec_module 790. <source code not available> File "<frozen importlib._bootstrap>" in _call_with_frames_removed 228. <source code not available> File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/librosa/core/audio.py" in <module> 17. from numba import jit, stencil, guvectorize File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/numba/init.py" in <module> 42. from numba.np.ufunc import (vectorize, guvectorize, threading_layer, File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/numba/np/ufunc/init.py" in <module> 3. from numba.np.ufunc.decorators import Vectorize, GUVectorize, vectorize, guvectorize File "/Users/reddylohitha/Desktop/Music-Genre-Classification-Django-master/env/lib/python3.9/site-packages/numba/np/ufunc/decorators.py" in <module> 3. from numba.np.ufunc import _internal Exception Type: SystemError at /result/ Exception Value: initialization of _internal failed without raising … -
Javascript for dynamically revealing Django formset forms
I'm trying to add/remove forms from formsets dynamically on button press. I am looking at an older example for JS to perform this action but I have multiple formsets but when I delete all of the forms for one of the formsets, obviously the addForm command no longer works as there are no forms to clone. That being said, I think a functional method would be to start with a hidden form and then copy the hidden form and display that form on demand. I just don't know how exactly to do that. Ideally, I'd like to not show any forms until the button press but not certain about how to do it. My current setup is shown below. HTML: <div class="selection"> <div class="forms"> <!-- {% for dict in formset.errors %} {% for error in dict.values %} {{ error }} {% endfor %} {% endfor %} --> <form id="general-formset" method="POST"> {% csrf_token %} {{ generalFormset.management_form }} {% for form in generalFormset %} <div class="formset"> {{ form.as_table }} <button id="remove-form" type="button" onclick="removeForm(this)" display="None">Remove Constraint</button> </div> {% endfor %} <button id="add-form" type="button" onclick="addForm(this)">Add Constraint</button> </form> <form id="specific-formset" method="POST"> {% csrf_token %} {{ specificFormset.management_form }} {% for form in specificFormset %} <div class="formset"> … -
Why is the drf login page showing me an error of wrong credentials even though i'm using the right credentials?
I'm working on a DRF project and was working on the Custom User Model. I can launch the server without errors and see all the API endpoints. However, after registering a new user, when I try to log in with the user's credentials, I get the error of giving the wrong email or password. I'm using dj-rest-auth for registering new users. Upon going into the admin, I see the notification of a new user being created, but for some reason, my code isn't letting them log in. Here's my models.py file:- import uuid from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager # Create your models here. GENDER_CHOICES = [ ('M','Male'), ('F','Female'), ('R','Rather not say'), ] class UserManager(BaseUserManager): def create_user(self,First_name:str,Last_name:str,Email:str,password:str,username:str,is_staff = False,is_superuser = False) -> 'User': if not Email: raise ValueError('User must have an Email') if not First_name: raise ValueError('User must have a First Name') if not Last_name: raise ValueError('User must have a Last Name') user = self.model(Email = self.normalize_email(Email)) user.First_name = First_name user.Last_name = Last_name user.set_password(password) user.username = username user.is_active = True user.is_staff = is_staff user.is_superuser = is_superuser user.save() return user def create_superuser(self,First_name:str,Last_name:str,Email:str,password:str,username:str)-> 'User': user = self.create_user( First_name = First_name, Last_name = Last_name, Email=Email, username=username, password=password, … -
Does django have lazy queries in foreign reverse lookup?
I have this code: def get_percentage_completions(task: Task, date_start: date, date_end: date): result = {} execution_percents = task.execution_percents.all() if execution_percents.exists(): year, week, _ = date_start.isocalendar() task_execution_percent = execution_percents.filter(year__lte=year, week__lte=week) \ .order_by('year', 'week').last() execution_percent = task_execution_percent.percent if task_execution_percent else 0 while date_end >= date_start: year, week, _ = date_start.isocalendar() if execution_percents.filter(year=year, week=week).exists(): task_execution_percent = execution_percents.filter(year=year, week=week).first() execution_percent = task_execution_percent.percent key = f"{year}_{week}" result[key] = round(execution_percent) date_start += timedelta(days=7) return result I get related objects from my model "Task". I thoght I hit to db once on second line when I define execution_persents variable, but actually my debug toolbar decrease amount of queries when I comment all lines after execution_persents variable. It means I hit to db inside while loop. Can I hit to db only once on the second line?