Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter by ManyToManyField, one way
I have a model with a ManyToManyField: class Release(models.Model): #... bundled_releases = models.ManyToManyField("self", blank=True) def get_bundles(self): return Release.objects.filter(bundled_releases__in=[self.id]) I want get_bundles to only return releases that have self in their bundled_releases fields, but this way it also returns releases in self's bundled_releases field. How do I do this? -
Django: setting up project/app to use Jinja syntax in Markdown posts
I'm migrating my website from Eleventy to Django. I had Eleventy set up with some custom Nunjucks filters/shortcodes or whatever they're called so I could use Nunjucks for including responsive web images as well as custom HTML media player code for video files, instead of having to write out HTML in the Markdown file every time. I'm trying to replicate that simplification in Django via Jinja (as it's basically the same thing, by Nunjucks' own admission), but I'm having a time wrapping my head around the learning curve for the different things I need to tackle in order to do this. From what I think I understand so far, I have a few obstacles: Figuring out how to get my Django project/app to process Jinja syntax in Markdown files and convert it to HTML. I found what looks like a good context explainer here (https://stackoverflow.com/a/32254521/21423257), but it's more of a general heads-up and doesn't explain what you need to actually do to your project/app to make this work. I'm using the Markdown plugin, I assume that will be adequate but if not, I'm open to using one of the other Markdown plugins if they're better suited for this task. Posting … -
Use Oauth2+Django to get authorization toaccess user's Gmail
I was using this tutorial: https://www.geeksforgeeks.org/python-django-google-authentication-and-fetching-mails-from-scratch/. However, the oauth2client library is deprecated and hasn't been touched in almost 9 years. I have looked for various tutorials, but they seem to be written by AI; they make no sense, and do things like tell you to include credentials in a piece of code that does not use credentials. So my question is, how can I implement oauth2 into my Django application so that user's can go to the Django website and give permission to read their emails? -
Gmail Oauth2 - restrict scope to only apply to emails from a certain domain [closed]
I have a Django site that uses Google Oauth2 to allow users to grant access to read and reply to their emails. GOOGLE_OAUTH2_CREDENTIALS = { 'client_id': '********************', 'client_secret': '*******', 'scope': [ 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send' ], 'redirect_uri': 'https://www.********.com/*****/', } However, for privacy and security purposes I want to set restrict the scope to only being able to read and reply to emails from a specific domain. Is it possible to modify the scope to only allow the permissions within for emails to/from a certain domain? -
Docker port forwarding not working Django app
I have a Django app that works fine locally when I run it without a container. However, when I containerize the app, create an image, and run the container, the app is not accessible at the forwarded port: http://localhost:8081 When I exec into the container and run the curl command: curl localhost:8005 I am able to see the response inside the container. Here is my Dockerfile, which I am using to build the image and run the container with some environment variables, which are present when I exec into the container: FROM python:3.11 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . /app EXPOSE 8005 #ENTRYPOINT ["bash", "entrypoint.bash"] CMD ["python", "manage.py", "runserver", "0.0.0.0:8005"] To build the image and run the container, I use the following commands: docker build -t app_backend:v1 . docker run -dit --rm -p 8081:8005 --name app_backend app_backend:v1 For testing, I tried running a sample command and was able to access Nginx on port 8009, but I cannot access the Django app at the specified port: docker run -d -p 8009:80 nginx:alpine -
How can I reduce the number of queries in a queryset?
I have the following serializers: class LiteratureProductSerializer(serializers.ModelSerializer): author = AuthorSerializer() binding = BindingSerializer() language = LanguageSerializer() genres = GenreSerializer(many=True) class Meta: model = LiteratureProduct fields = ('year_of_manufacture', 'pages', 'isbn', 'author', 'binding', 'language', 'genres') class AccessoryProductSerializer(serializers.ModelSerializer): manufacturer = ManufacturerSerializer() seria = SeriaSerializer() material = MaterialSerializer() class Meta: model = AccessoryProduct fields = ('manufacturer', 'seria', 'material', 'size') class FoodProductSerializer(serializers.ModelSerializer): manufacturer = ManufacturerSerializer() class Meta: model = FoodProduct fields = ('manufacturer') class ClotherProductSerializer(serializers.ModelSerializer): material = MaterialSerializer() colors = ColorSerializer(many=True) sizes = SizeSerializer(many=True) class Meta: model = ClotherProduct fields = ('material', 'colors', 'sizes', 'year_of_manufacture') class ProductSerializer(serializers.ModelSerializer): category = CategorySerializer() source = SourceSerializer() literature_product = LiteratureProductSerializer() accessory_product = AccessoryProductSerializer() food_product = FoodProductSerializer() clother_product = ClotherProductSerializer() class Meta: model = Product fields = ('id', 'name', 'slug', 'description', 'image', 'price', 'discount', 'amount', 'is_active', 'weight', 'rating', 'created_date', 'category', 'source', 'literature_product', 'accessory_product', 'food_product', 'clother_product') Now I want to display information about a single object, which can belong to one of these four categories. I created the following API view. Since I have many ForeignKey and ManyToMany relationships, I used select_related and prefetch_related for optimization. Here's the code of my view: class ProductsAPIView(RetrieveAPIView): serializer_class = ProductSerializer lookup_field = 'slug' lookup_url_kwarg = 'product_slug' def get_queryset(self): return Product.objects.select_related( 'category', 'source', 'literature_product', 'literature_product__author', … -
NoReverseMatch URL using Django
Currently getting a NoReverseMatch error and not sure why. Here's the error message and relevant code: Error: Error during template rendering In template C:....<Folder><Project>\userapp\templates\userapp\details.html, error at line 11 Reverse for 'favourite' with arguments '('',)' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/favourite\Z'] urls.py path('music/<int:album_id>/favourite/', views.favourite, name='favourite') views.py def favourite(request, album_id): albums = get_object_or_404(Album, pk=album_id) try: selected_song = albums.song_set.get(pk=request.POST['song']) except (KeyError, Song.DoesNotExist): return render(request, 'userapp/details.html', { 'albums': albums, 'error_message': "You did not select a valid song", }) else: selected_song.is_favourite = True selected_song.save() return render(request, 'userapp/details.html', {'albums': albums}) details.html {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} line 11 - {% csrf_token %} {% for song in albums.song_set.all %} {{ song.song_title }} {% if song.is_favourite %} <img {% endif %} {% endfor %} -
Django ignoring DEBUG value when I use os.environ?
In my Django settings I have the following: on env.py I have the below code: os.environ.setdefault( "DEBUG", "True" ) On settings.py I have the below code: DEBUG = os.environ.get('DEBUG') == 'True' However some of the systes are not visbile after deploying but they are perfect on my local server. Please assist thank you. I tried changing the DEBUG value to false but nothing changes. -
Does calling a method from template query the database each time?
Say you have the following method in a model: def get_images(self): return ReleaseImage.objects.filter(release=self.id) And you call it from a template like so: {% if release.get_images %}{{ MEDIA_URL }}{{ release.get_images.first }}{% endif %} Does the database get queried twice, or is there some behind-the-scenes optimization that prevents this? It might be highly inefficient if not. -
Issue with Django Login Form: Form is Invalid Despite Correct Credentials
I've been facing an issue with my Django login form. Despite providing the correct credentials, the form consistently returns as invalid. Here’s a detailed description of my setup and the problem I’m encountering. Description I'm using Django's AuthenticationForm to handle user login. My goal is to authenticate users and redirect them to a specific page upon successful login. However, the form validation fails even though the credentials are accurate and the user exists in the database. form.py from django import forms from .models import UserRegister from django.contrib.auth.forms import UserCreationForm , AuthenticationForm from django.core.exceptions import ValidationError class UserRegisterForm(UserCreationForm): username = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Username', 'class': 'input-group'})) email = forms.EmailField(max_length=70, required=True, widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'input-group'})) password1 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'input-group', 'id': 'password'})) password2 = forms.CharField(max_length=128, required=True, widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password', 'class': 'input-group', 'id': 'password'})) class Meta: model = UserRegister fields = ['username', 'email', 'password1', 'password2'] error_messages = { "password_mismatch": "Conform Password Does not match with Password" } def clean_email(self): email = self.cleaned_data.get('email') if UserRegister.objects.filter(email=email).exists(): raise ValidationError('This email address is already in use.') return email def clean_username(self): username = self.cleaned_data.get('username') if UserRegister.objects.filter(username=username).exists(): raise ValidationError('This username is already in use.') return username def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 … -
How to make Pre-commit ignore when an element is not accessible?
I have this config in my app.rb : from django.apps import AppConfig class WebsiteConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "website" def ready(self): import website.signals The "website.signals" is not accessible (Pylance) because I am using docker. When the pre-commit is running, it will change my code to: from django.apps import AppConfig class WebsiteConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "website" def ready(self): pass How do I bypass this in general in my pyproject.toml? I don't want to by pass only the file app.py but for any project I am working on, I want him to not pass if something looks like it is not accessible -
with regard to form.save(commit=False), what am I missing?
As explained in many posts like the following: Why do we use "form.save(commit=False)" in Django-views? "The main use case is if you have a ModelForm that doesn't contain all the required fields of a model. You need to save this form in the database, but because you didn't give it all the required fields, you will get an error.." which is all good and dandy but why not just complete all the instance fields and then call the regular save? In the bellow example: # Creates a Dog class with all fields as mandatory: class Dog(models.Model): name = models.CharField(max_length=50) race = models.CharField(max_length=50) age = models.PositiveIntegerField() # Creates a ModelForm with only name and age: class DogForm(forms.ModelForm): class Meta: model = Dog fields = ['name', 'age'] # In your view use this form: def dog_view(request): ... form = DogForm(request.POST or None) # If the form is valid we need to add a race, otherwise we will get an error: if form.is_valid(): dog = form.save(commit=False) # Define the race here: dog.race = 'Labrador retriever' # And then do the regular save to push the change in the database: dog.save() ... why not just say: form = DogForm(request.POST or None) # Define the … -
Intermittent Pooler Error in django app server
facing intermittent Pooler Error: server conn crashed? in my http server. Tried searching and fixing long running transaction in my system but didn't help. Also this happens very randomly at any point in time without any co-relation with traffic. Sharing error logs: 2025-01-31 11:41:07.067 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34186 closing because: client close request (age=0) 2025-01-31 11:41:07.051 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34186 login attempt: db=test user=server_application_api tls=no 2025-01-31 11:41:06.988 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34096 closing because: client close request (age=0) 2025-01-31 11:41:06.968 1 LOG C-0x55d7847ae820: logs/server_application_api@127.0.0.1:34048 closing because: client close request (age=0) 2025-01-31 11:41:06.952 1 LOG C-0x55d7847ac110: logs/server_application_api@127.0.0.1:34096 login attempt: db=test user=server_application_api tls=no 2025-01-31 11:41:06.948 1 WARNING C-0x55d7847ac110: logs/server_application_api@127.0.0.1:40674 Pooler Error: server conn crashed? CloudWatch metrics -
Django import-export import foreign keys that do not exist
Being in a rush I'm having a hard time understanding the import concept. Where is the final board creation missing? i.e. Board(person=p, organization=p) Model class Person(BaseModel): organizations = models.ManyToManyField("Organization", blank=True, through="Board") class Organization(BaseModel): people = models.ManyToManyField("Person", blank=True, through="Board") class Board(BaseModel): person = models.ForeignKey(Person, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) Test from django.test import TestCase import tablib from import_export import resources class BoardResource(resources.ModelResource): def before_import_row(self, row, **kwargs): org_name_1 = row["organization"] o=Organization.objects.get_or_create(name_1=org_name_1, defaults={"name_1": org_name_1}) person_firstname = row["person"] p=Person.objects.get_or_create(firstname=person_firstname, defaults={"firstname": person_firstname}) class Meta: model = Board dataset = tablib.Dataset(['','john','acme'], headers=['id','person','organization']) class TestCase(TestCase): def test_basic_import(self): board_resource = BoardResource() result = board_resource.import_data(dataset, dry_run=False) print(result.totals) assert not result.has_errors() The documentation points to this thread though I'm unable to apply anything to my case -
Selenium: not working fine with the docker
I want to run the selenium chrome driver my django project with the docker configuration so i followed this: [https://hub.docker.com/r/selenium/standalone-chrome/][1] and I have created the celery task functionality is like this: def setup_driver(): try: chrome_options = Options() chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_argument("--start-maximized") chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36") driver = Remote( command_executor="http://selenium_grid:4444/wd/hub", # Use service name! options=chrome_options ) print("Successfully connected to Selenium Grid:", driver) return driver except Exception as e: print(f"Failed to connect to Selenium Grid: {e}") return None def view_fun(request): try: driver = setup_driver() time.sleep(2) logger.info(f"{driver} setup successful") except Exception as e: print(f"An error occurred: {e}") finally: driver.quit() So the error is like this: celery_worker-1 | [2025-01-31 11:50:17,605: WARNING/ForkPoolWorker-4] Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NameResolutionError("<urllib3.connection.HTTPConnection object at 0x7f08d1d0d7f0>: Failed to resolve 'selenium_grid' ([Errno -2] Name or service not known)")': /wd/hub/session celery_worker-1 | [2025-01-31 11:50:29,547: WARNING/ForkPoolWorker-4] Loading login page... celery_worker-1 | [2025-01-31 11:50:29,547: WARNING/ForkPoolWorker-4] Login failed: 'NoneType' object has no attribute 'get' celery_worker-1 | [2025-01-31 11:50:29,548: ERROR/ForkPoolWorker-4] scrape.tasks.run_weekly_scraping_zip[ebf4199d-61d4-4a3c-85ab-c64e228f3e2b]: Error in weekly scrape: 'NoneType' object has no attribute 'quit' celery_worker-1 | File "/app/scrape/utils.py", line 256, in scrape_ziprecruiter_jobs celery_worker-1 | driver.quit() celery_worker-1 | AttributeError: 'NoneType' object has no attribute 'quit' Also … -
Django customize validation error message
I have a following serializer definitions that validate request payload: # diagnosis serializer class ICD10Serializer(serializers.Serializer): icd_10 = serializers.IntegerField(required=True, allow_null=False) class DetailsSerializer(serializers.Serializer): diagnosis_details = ICD10Serializer(many=True) class ChartUpdateSerializer(serializers.Serializer): diagnosis = DetailsSerializer(many=True) Its usage: payload = ChartUpdateSerializer(data=request.data) if not payload.is_valid(): raise serializers.ValidationError(payload.errors) This throws validation error message in the following format: { "diagnosis": [ { "diagnosisDetails": [ {}, <- valid {}, <- valid {}, <- valid {}, <- valid { "icd10": [ "This field may not be null." ] } ] } ] } Here {} is also shown for valid ones. Can we simply raise validation error for invalid ones? Or better even if we can know which field and the message so custom message can be generated. -
Information on using Twilio with Whatsapp
I am making an app with Django and react about a clinic. My clients want to send automatically the appointment through WhatsApp to their patients. I have been reviewing the Twilio documentation, as I understand, I need that the phone number I use to send the WhatsApp must be WhatsApp Business. Can anyone help me on how to perform this function? I have never used Twilio, and I am very lost, I also don't understand how I am going to be able to test that it works correctly before launching it. Thanks in advance for the help. -
Firebase API is not sending notification in background
I'm creating web app using Django, and trying to send push notification via firebase API. It's working when user is on page that registers firebase-messaging-sw.js, but in background no notification is coming, even though no error was raised. def send_fcm_notification(device_token, title, body, data=None, click_action=None): headers = { "Authorization": f"Bearer {get_access_token()}", "Content-Type": "application/json", } data = { "message": { "token": device_token, # Use "topic": "your-topic" to send to a topic "notification": { "title": title, "body": body, }, "data": data or {}, "android": { "priority": "high" }, "apns": { "payload": { "aps": { "alert": { "title": title, "body": body } } } } } } response = requests.post(FCM_ENDPOINT, headers=headers, data=json.dumps(data)) return response.json() SW importScripts("https://www.gstatic.com/firebasejs/11.2.0/firebase-app-compat.js"); importScripts("https://www.gstatic.com/firebasejs/11.2.0/firebase-messaging-compat.js"); // Firebase Configuration (Same as in your main script) const firebaseConfig = { //myconfig data }; // Initialize Firebase firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); self.addEventListener('notificationclick', (event) => { event.notification.close(); // CLosing the notification when clicked const urlToOpen = event?.notification?.data?.url || 'https://www.test.com/'; // Open the URL in the default browser. event.waitUntil( clients.matchAll({ type: 'window', }) .then((windowClients) => { // Check if there is already a window/tab open with the target URL for (const client of windowClients) { if (client.url === urlToOpen && 'focus' in client) { return client.focus(); … -
I am attempting to use Django Ninja for the first time and running into a strange error
I cant quite understand error I am receiving. I am simply trying to setup a model schema for my model. I am an old Django hand but ninja is new for me. What am I doing wrong here? Would love some help and feedback. My model is this class Program(models.Model): mentor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) description = models.TextField() start_date = models.DateField() end_date = models.DateField() attendees = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="attendees") participants = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="participants") created_on = models.DateTimeField(auto_now_add = True) updated_on = models.DateTimeField(auto_now = True) My api.py has the following definition class MentorOutSchema(Schema): class Config: model = Program model_fields = [ "mentor", "description", "start_date", "end_date", "attendees", "participants", ] My endpoint is this @router.get('/programs') async def mentor_programs(request, response=list[MentorOutSchema]): return Program.objects.filter(mentor=request.user) When I start the server, I get the following error @router.get('/programs') ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/router.py", line 268, in decorator self.add_api_operation( File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/router.py", line 319, in add_api_operation path_view.add_operation( File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/operation.py", line 426, in add_operation operation = OperationClass( ^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/operation.py", line 331, in __init__ super().__init__(*args, **kwargs) File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/operation.py", line 82, in __init__ self.signature = ViewSignature(self.path, self.view_func) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/signature/details.py", line 87, in __init__ self.models: TModels = self._create_models() ^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/ninja/signature/details.py", line 171, in _create_models model_cls = type(cls_name, (base_cls,), attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/vivekv/.cache/pypoetry/virtualenvs/pifnow-Zp6OiFzb-py3.12/lib/python3.12/site-packages/pydantic/_internal/_model_construction.py", line 219, in __new__ set_model_fields(cls, … -
Django Redirect followed by database lookup
I have an authenticated user that is signed into a webpage Page1.html on this page I want to create redirect the user to another page that matches a particular property that the user has in their user role. I managed to get the part working that redirects the user to that webpage, but I know I am going to be faced with having many users so it will take a while for searching each user that is why I want the second redirect to occur on the second html page. My thoughts are that I use the manipulation of the post to the redirect of the first page Page1.html, and have Page1.html have a please wait till redirected to the final page that they will be using. I was reading this question but it did not really answer my question: Django - show loading message during long processing -
Can't install R in Heroku deployment
I'm trying to install the R buildpack for rpy2 for my website built with Django and React, but I keep getting an error on deployment and I have no clue what's going on. I've checked my buildpacks a billion times to make sure it is in the order of Apt, Python, and R, and I have Aptfiles, init.R, and runtime.txt in my root directory. This is the error message. Help very much appreciated! Collecting rpy2~=3.5.16 (from -r requirements.txt (line 15)) remote: Downloading rpy2-3.5.17.tar.gz (220 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'error' remote: error: subprocess-exited-with-error remote: remote: × Getting requirements to build wheel did not run successfully. remote: │ exit code: 1 remote: ╰─> [34 lines of output] remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> remote: main() remote: File "/app/.heroku/python/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main remote: json_out['return_val'] = hook(**hook_input['kwargs']) remote: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ remote: File "/app/.heroku/python/lib/python3.12/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel remote: return hook(config_settings) remote: ^^^^^^^^^^^^^^^^^^^^^ remote: File "/tmp/pip-build-env-jhoy88xq/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 334, in get_requires_for_build_wheel remote: return self._get_build_requires(config_settings, requirements=[]) remote: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ remote: File "/tmp/pip-build-env-jhoy88xq/overlay/lib/python3.12/site-packages/setuptools/build_meta.py", line 304, in … -
Writing Django Func() Expression with multiple parameters and specify the order
I'm using Func() Expressions to use this answer and compute the difference between two dates in business days: class BusinessDaysBetween(Func): """Implementation of a Postgres function to compute the working holidays between two fields.""" template = """ (SELECT COUNT(*) FROM generate_series(%(expressions)s, interval '1 day') s(day) WHERE EXTRACT(DOW FROM s.day) NOT IN (0, 6)) """ arity = 2 output_field = IntegerField() However, I am having problems with the formatting of Date and DateTime. So I want to call the functions mentioned in this answer. My edited code looked like this: class BusinessDaysBetween(Func): """Implementation of a Postgres function to compute the working holidays between two fields.""" template = """ ( SELECT COUNT(*) FROM generate_series( TO_CHAR(CAST(%(expressions)s AS DATE), 'YYYY-MM-DD'), TO_CHAR(CAST(%(expressions)s[1] AS DATE), 'YYYY-MM-DD'), interval '1 day' ) s(day) WHERE EXTRACT(DOW FROM s.day) NOT IN (0, 6) ) """ arity = 2 output_field = IntegerField() The problem is that I am putting both parameters in the first place, I don't know how to specify the order of the parameters in which they will appear. I already tried: With {0} and {1} and it says there is a syntax error. %(expressions)s and %(expressions)s[1] and nothing. With %s, it's raising the "not enough arguments for format string" … -
wrong password when social authentication in allauth
I have been struggling with this for days, I'm a beginner and I don't know how to implement social authentication (authentication by providers) neither in allauth nor in headless-allauth libraries, I have implemented a sign in with providers in reguler allauth, my settings.py SOCIALACCOUNT_PROVIDERS= { 'google': { 'SCOPE': [ 'profile', 'email' ], 'AUTH_PARAMS': {'access_type': 'online'}, 'APP': { 'client_id': '247133284916-r5pu7h3bnee0vbrbem7nhph5ffhkk5ob.apps.googleusercontent.com', 'secret': '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', 'key': '' } }, 'github' : { 'SCOPE': [ 'user' ], 'APP': { 'client_id': 'Ov23liT9Y3rQjzd25rZN', 'secret': '02f816d85ec879da6ddec85d2d169a019fa1084b', 'key': '' } }, 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'} } html <a class="social-login Google-login" href="{% provider_login_url 'google' %}"> <span class="G-logo"></span> <span>Log in with Google</span> </a> when I try to sign up with a provider (google for instance) I am signed in and everything is ok, but when I try to reauthenticated in headless-allauth library by entering the password (I am using both) or I try to sign out then sign in by entering the email and password, I always keep getting (the password you specified is not correct.) when I am sure of my google account … -
Why am I unable to query the date from my database in django?
My database does have an item in the collection I want to query, and it returns the price correctly. from django.db import models # Create your models here. class Dollar_price(models.Model): price = models.FloatField() date = models.DateTimeField() def __str__(self): print(self.date) return str("success") The problem is that when I try printing self.date it says it's None. I don't know why this happens, nor how can I solve this. -
Do not monitor changes for field in django-simple-history
I am trying to monitor and display historical changes of my model. Problem is that every time user logins it saves it to historical model. I have tried to exclude this field like shown bellow, but it just saves new instance without field last_login. Model: class CustomUser(AbstractBaseUser, PermissionsMixin): ... history = HistoricalRecords(excluded_fields=['last_login']) View: def user_history(request, pk): user = get_object_or_404(CustomUser, pk=pk) history_records = user.history.all().order_by("-history_date") table = UserHistoryTable(history_records) return render(request, "history.html", { "name": user.username, "instance": user, "table": table, }) Table: class UserHistoryTable(tables.Table): history_date = tables.DateTimeColumn(verbose_name="Date", format="d.m.Y H:i") history_user = tables.Column(verbose_name="Modified By") history_type = tables.Column(verbose_name="Change Type", accessor="get_history_type_display") changes = tables.Column(empty_values=(), verbose_name="Changes") class Meta: model = CustomUser.history.model attrs = {"class": "table table-striped table-hover table-bordered shadow-sm"} template_name = "django_tables2/bootstrap4.html" fields = ("history_date", "history_user", "history_type") def render_changes(self, record): if record.prev_record: changes = [] for field in record.instance._meta.fields: field_name = field.name old_value = getattr(record.prev_record, field_name, None) new_value = getattr(record, field_name, None) if field_name == "password" and old_value != new_value: changes.append(f"<strong>{field.verbose_name}:</strong> {'*' * 7} → {'*' * 7}") elif old_value != new_value: changes.append(f"<strong>{field.verbose_name}:</strong> {old_value} → {new_value}") if changes: return format_html("<br>".join(changes)) else: return "No changes" return "No previous record" I need to display table with changes without empty entries My current solution was to filter table in view, but …