Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
row num in Django REST Framework
Is there any way to assign increasing integers to queryset objects ? qs = self.get_queryser() I know that I can use enumerate function like this: for i, obj in enumerate(qs): print(i, obj) but this is not what I need , I want to have something like rownum pseudocolumn for each object of qs, so when I pass obj to any other function, rownum will be passed along with it. for obj in qs: some_func(obj) /* here obj should include rownum */ Thank you in advance -
Calling a django view inside of a playwright scraper function
a. I have a scraper function shown below where I need a captcha input in order to move ahead with the scraping. b. I need the flow to happen as follows: I click a button inside a Django view to start the scraping on a web page. The scraper starts running and reaches the page on the MCA website with the captcha. Playwright captures a screenshot of the captcha as an image and sends the same to a Django view to be rendered as an image on a page while Playwright waits for the input from the user in the Django view. A Django view loads the captcha on a page with a form seeking user input for the captcha. Once the user enters the captcha in the form inside of a Django view and submits it, the user input gets submitted to Playwright which then enters the captcha on the page and continues scraping the MCA website. The data collected by Playwright is returned as a dictionary and saved in a Django model. My question is how do I implement 3. and 4. above. The scraping code is below: """Get profile data from mca.gov.in for a given CIN or … -
Only displaying certain options in django form dropdown
Gday, I am creating a site to manage data for software with django. Users on the site are linked to divisions (regions) in a divisions model through a many to many field. The actual data is all linked to profiles, which are owned by divisions. Division users can edit profiles owned by the division, but not others. My issue is with forms to create profiles. Attached is an image of the form. The division field shows all divisions registered on the site, but I only want it to show ones that the logged in user is a member of. For example, this user is only a member of 'VATPAC' so it should only show that as an option to select. Attached is all the relevant code. Forms.py class ProfileForm(ModelForm): class Meta: model = models.Profile fields = ('division', 'name') widgets = { 'division': forms.Select(attrs={'class':'form-control'}), 'name': forms.TextInput(attrs={'class':'form-control'}) } views.py def AddProfile(request): submitted = False if request.method == "POST": form = forms.ProfileForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('profile?submitted=true') else: form = forms.ProfileForm if 'submitted' in request.GET: submitted = True return render(request,'profiles/create/create_profile.html', {'form': form, 'submitted': submitted}) models.py class Profile(models.Model): division = models.ForeignKey(Division, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name models.py (foreignkey for division) class … -
How to run Django with other non-Django page in same port of localhost in apache?
I am trying to run Django through apache2 (mod_wsgi) on xampp-portable-windows. FILE: xampp/apache2/conf/httpd.confd LoadFile "/Portable_PY/Python_Web/python310.dll" LoadModule wsgi_module "/Portable_PY/Python_Web/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "/Portable_PY/Python_Web" WSGIPythonPath "/Portable_PY/Python_Web/Lib/site-packages" WSGIScriptAlias / "/hung_collections/tempoTest/wsgi.py" FILE: xampp/apache2/conf/extra/httpd-vhosts.conf <VirtualHost *:80> DocumentRoot "/xampp/htdocs" ServerName localhost </VirtualHost> # non Django page <VirtualHost *:80> ServerName testhis.localhost DocumentRoot "/Testinsite" <Directory "/Testinsite"> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> </VirtualHost> # Django app <VirtualHost *:80> ServerName heck.localhost <Directory "/hung_collections/tempoTest"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> After adding WSGIScriptAlias in httpd.conf file it runs the django site on heck.localhost, But running just localhost or localhot.test gives 403 forbidden error 403 forbidden error -
How do I dynamically change the value of text in html whenever a python variable is changed using ajax?
I'm using ajax, python, Django, HTML, and javascript for my project. I'd like to know if there is a in my HTML file like, <p class='text_box', id='tbox'> {{ text_variable_from_python }} </p> <input class='input_box', id='ibox', type='text'> Then I'd input some text into the input box, make a simple ajax request with the "text" variable and get an output from the server, which I would update on the views.py as, def main(request): if request.method == 'POST': new_text = request.POST['text'] context = {'text_variable_from_python': new_text} else: context = {'text_variable_from_python': 'You can change me!'} print(context) return render(request, 'Main.html', context=context) My question is, how do I send the data dynamically from the server to appear on client's webpage using ajax and python in between the two? Using my method, I can only see "You can change me!" on the webpage or nothing at all. No matter how many differing prompts I give, further changes do not show on the webpage. -
How can I fill my django form in two different template?
This is my models.py: class Person(models.Model): Person_ID = models.AutoField(blank=False, primary_key=True) p_SSN = models.CharField(blank=False, null=False, max_length=10) p_fName = models.CharField(null=False, blank=False, max_length=15) p_lName = models.CharField(null=False, blank=False, max_length=25) p_phoneNum = models.CharField(null=False, blank=False, max_length=11) p_birthDate = models.DateField(null=False, blank=False) p_Email = models.EmailField(null=False, blank=False, unique=True) p_Password = models.CharField(null=False, blank=False, max_length=20) At step 1 I want to fill my form except p_Email and p_Password. In step 2 (means next template) I want to initial p_Email and p_Password. this is my django form: class PersonForm(forms.ModelForm): p_fName = forms.CharField(max_length=15) p_lName = forms.CharField(max_length=25) p_SSN = forms.CharField(max_length=10) p_phoneNum = forms.CharField(max_length=11) p_birthDate = forms.DateField() p_Email = forms.EmailField(max_length=255) p_Password = forms.CharField(max_length=255) class Meta: model = Person fields = ['p_fName', 'p_lName', 'p_SSN', 'p_phoneNum', 'p_birthDate', 'p_Email', 'p_Password'] This is my views.py: def new_student(request): newStudentForm = PersonForm(request.POST or None) if newStudentForm.is_valid(): newStudentForm.save() return render(request, 'signUp_student.html', {'form': newStudentForm}) And my template for step 1 is : <form action="{% url 'new_student' %}" method="post"> {% csrf_token %} <label for="firstName">First Name</label><br> {{ form.p_fName }}<br> <label for="lastName">Last Name</label><br> {{ form.p_lName }}<br> <label for="firstName">SSN Code</label><br> {{ form.p_SSN }}<br> <label for="birthdate">Birthdate</label><br> {{ form.p_birthDate }}<br> <label for="phoneNumber">Phone Number</label><br> {{ form.p_phoneNum }}<br><br> <button type="submit">Sign up</button> </form> How can I initial my fields of class in different template? Thanks for giving your time to solve my … -
Slug page is not opening
My slug is coming into the url but the page linked with the page is not opening can anyone please help me with this. I have attached the code please see it and tell me the issue. btw it is a blog page. Models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(default=timezone.now()) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse("post_details", kwargs={"slug": self.slug}) 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> <style> body { font-family: "Roboto", sans-serif; font-size: 18px; } .head_text { color: white; } </style> </head> <body> {% extends "base.html" %} {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class=" col-md-8 col-md-10 mx-auto"> <div class="site-heading"> <h3 class=" site-heading my-4 mt-3 text-white"> Welcome to my awesome Blog </h3> </p> </div> </div> </div> </div> </header> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p> <p … -
Django: ModuleNotFoundError: No module named 'name_project' after doing refactor
I have initialized a Django project with the help of Pycharm with "name_project" and for several reasons, I decided to refactor the name of the project and directory to "name". I am using Pycharm which to my understanding, if I refactor, automatically every related name with the old name will automatically change to a new name throughout the project. However, when I tried to run python manage.py runserver 8000 I received this error File "C:\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'name_project' I tried to go to that latest file that is listed there... I didn't find any name_project stated there. Where could I go wrong? This is my Django directory looks like project ├── project │ ├── aesgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── views.py │ ├── wsgi.py └── templates │ ├── landing_page.html └── venv └── manage.py └── README.md -
Uncaught TypeError: Waypoint.Infinite is not a constructor at infinite_scroll.js:1:16
I am trying to use Jquery waypoints and infinite scroll on a Django app, but I keep getting this error for some reason. Can anyone tell me why? I already tried the answers from Waypoint.Infinite is not a constructor but they don't help me. Any suggestions? infinite_scroll.js var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { }, onAfterPageLoad: function () { } }); -
django-admin dose not create project
I'm running django 2.0.7 on a verual envirment python3 and when i run **django-admin startproject trydjango1 . ** the following error occers can you please help me to solve this problem Traceback (most recent call last): File "C:\Users\TG\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in run_module_as_main return run_code(code, main_globals, None, File "C:\Users\TG\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code exec(code, run_globals) File "D:\django-projects\Test1\Scripts\django-admin.exe_main.py", line 7, in File "D:\django-projects\Test1\lib\site-packages\django\core\management_init.py", line 371, in execute_from_command_line utility.execute() File "D:\django-projects\Test1\lib\site-packages\django\core\management_init.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\django-projects\Test1\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "D:\django-projects\Test1\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "D:\django-projects\Test1\lib\site-packages\django\core\management\commands\startproject.py", line 20, in handle super().handle('project', project_name, target, **options) File "D:\django-projects\Test1\lib\site-packages\django\core\management\templates.py", line 117, in handle django.setup() File "D:\django-projects\Test1\lib\site-packages\django_init_.py", line 16, in setup from django.urls import set_script_prefix File "D:\django-projects\Test1\lib\site-packages\django\urls_init_.py", line 1, in from .base import ( File "D:\django-projects\Test1\lib\site-packages\django\urls\base.py", line 8, in from .exceptions import NoReverseMatch, Resolver404 File "D:\django-projects\Test1\lib\site-packages\django\urls\exceptions.py", line 1, in from django.http import Http404 File "D:\django-projects\Test1\lib\site-packages\django\http_init_.py", line 5, in from django.http.response import ( File "D:\django-projects\Test1\lib\site-packages\django\http\response.py", line 13, in from django.core.serializers.json import DjangoJSONEncoder File "D:\django-projects\Test1\lib\site-packages\django\core\serializers_init_.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "D:\django-projects\Test1\lib\site-packages\django\core\serializers\base.py", line 6, in from django.db import models File "D:\django-projects\Test1\lib\site-packages\django\db\models_init_.py", line 3, in from django.db.models.aggregates import * # NOQA File "D:\django-projects\Test1\lib\site-packages\django\db\models\aggregates.py", line 5, in from django.db.models.expressions … -
Dynamic Serialization for related fields
I have the following models: class Country(models.Model): """ Country model """ # With name and isoCode (charfield) ... class State(models.Model): """ State model """ # With name and isoCode (charfield) country = models.ForeignKey(Country, on_delete=models.CASCADE) ... class City(models.Model): """ City model """ name = models.CharField(max_length=32) state = models.ForeignKey(State, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) ... And UserLocation referenced by: class Location(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="location") country = models.ForeignKey(Country, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) city = models.ForeignKey(City, on_delete=models.CASCADE) How do I build a serializer that creates UserLocation, as well as return the info in JSON? I have tried class LocationSerializer(serializers.ModelSerializer): country = serializers.SlugRelatedField(slug_field="isoCode", queryset=Country.objects.all()) state = serializers.SlugRelatedField(slug_field="isoCode", queryset=State.objects.filter(country__isoCode=country)) city = serializers.SlugRelatedField(slug_field="name", queryset=City.objects.all()) class Meta: model = Location fields = ["user", "country", "state", "city"] But it does not work, it gives the error {"state":["Object with isoCode=BC does not exist."],... How does one create a dynamic linked serializer? Or how does one work around this? -
Django: unsupported operand type(s) for +: 'int' and 'method' when creating function in Django
i am writing a function in my model to get the cart total, but i keep getting this error and i don't seem to know exactly what is going wrong - unsupported operand type(s) for +: 'int' and 'method'. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) transaction_id = models.CharField(max_length=1000, null=True, blank=True) completed = models.BooleanField(default=False) active = models.BooleanField(default=True) date_ordered = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.customer.user.username} - {self.transaction_id}" @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = int(sum([item.quantity for item in orderitems])) return total -
How to combine values from 2 queryset
I do have two queryset both having common field 'month' i want to combine both query set using field 'month' six_months_ago = date.today() + relativedelta(months=-6) ###### Geting number of New Patient registration by month (for last six month) patient_per_month = patientprofile.objects.filter(pat_Registration_Date__gte=six_months_ago)\ .annotate( month=Trunc('pat_Registration_Date', 'month') ) \ .order_by('month') \ .values('month') \ .annotate(patient=Count('month')) print(patient_per_month) ###### Geting number of visit by month (for last six month) visits_per_month = visits.objects.filter(visit_date__gte=six_months_ago)\ .annotate( month=Trunc('visit_date', 'month') ) \ .order_by('month') \ .values('month') \ .annotate(visits=Count('month')) print(visits_per_month) Both printing ad below: <QuerySet [{'month': datetime.date(2022, 2, 1), 'patient': 1}, {'month': datetime.date(2022, 3, 1), 'patient': 1}, {'month': datetime.date(2022, 4, 1), 'patient': 1}, {'month': datetime.date(2022, 5, 1), 'patient': 2}, {'month': datetime.date(2022, 6, 1), 'patient': 2}, {'month': datetime.date(2022, 7, 1), 'patient': 18}]> <QuerySet [{'month': datetime.date(2022, 5, 1), 'visits': 6}, {'month': datetime.date(2022, 6, 1), 'visits': 7}, {'month': datetime.date(2022, 7, 1), 'visits': 12}]> I want combine both of these query set as one by 'month' field something like below. <QuerySet [{'month': datetime.date(2022, 2, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 3, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 4, 1), 'patient': 1, 'visits': 0}, {'month': datetime.date(2022, 5, 1), 'patient': 2, 'visits': 6}, {'month': datetime.date(2022, 6, 1), 'patient': 2, 'visits': 7}, {'month': datetime.date(2022, 7, 1), 'patient': 18'visits': … -
Django Queryset Design: Filtering out soft-deleted users?
I have a soft-delete user model in Django, where we set is_active to False. But one problem I'm running into is needing to filter out is_active users on every type of content: Item.objects.filter(user__is_active=False, ...) Comment.objects.filter(user__is_active=False, ...) User.objects.filter(is_active=False, ...) And so-on. Is there some type of Django / Pythonic design pattern I can use here to avoid needing to manually filter out all users every time I query something made by a user, or a current list of users? -
How to remove "Currently" tag and link in django filefield
Basically, on the website it says currently: and then its the name of the file that was uploaded and im wondering how to remove the "currently" and the name of the file that was uploaded. ps: sorry if i didn't explain well im not the best at it pfp_url = models.FileField() bg_pfp = models.FileField() Heres a more indepth image -
ModuleNotFoundError: No module named 'django_apscheduler' when I migrate my file with heroku
I want to update my heroku site with this command heroku run python manage.py migrate, but the error appeared: » Warning: heroku update available from 7.53.0 to 7.60.2. Running python manage.py migrate on ⬢ mighty-harbor-18334... up, run.5980 (Free) Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/app/.heroku/python/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.10/site-packages/django/apps/config.py", line 223, in create import_module(entry) File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_apscheduler' I installed django_apscheduler with pip install django_apscheduler for sure. My python version is 3.10.2, and in my settings.py, the app module is in INSTALLED_APPS such: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' 'django_apscheduler', ] I am not sure why the ModuleNotFoundError would occured, any help will be appreciated. -
Django annotate query to return datetime values in localtime like `Extract` can
settings.py: TIME_ZONE = 'UTC' USE_TZ = True I understand that Django returns values in model queries in UTC. If I want to show the values of time-aware datetime objects to users in there localtime I can do so in templates etc via timezone.activate or timezone.override. I have the need to return all datetime values in a specific timezone before it is rendered in any template. With timezone.activate or timezone.override, I notice `DateTimeField extracts do something close to what I want: import zoneinfo from datetime import datetime from django.utils import timezone class Experiment(models.Model): created_at = models.DateTimeField() created_at = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc) Experiment.objects.create(created_at = created_at) tz = zoneinfo.ZoneInfo('Australia/Melbourne') with timezone.override(tz): qs = Trade.objects.annotate(hour=ExtractHour('created_at')).values('created_at', 'hour') print(qs.query) print(qs) Output SELECT "experiment"."created_at", EXTRACT('hour' FROM "app_trade"."created_at" AT TIME ZONE 'Australia/Melbourne') AS "hour" FROM "experiment" <QuerySet [{'created_at': datetime.datetime(2015, 6, 15, 23, 30, 1, tzinfo=<UTC>), 'hour': 9}]> Notice the hour 'Australia/Melbourne' and created_at is UTC. What I want is I want all my timestamps to comeback in specified zone. Is there a Django-native or elegant way to do this? Hopefully integrated with any timezone.override. Something like: tz = zoneinfo.ZoneInfo('Australia/Melbourne') with timezone.override(tz): qs = Trade.objects.annotate(local_created_at=LocalTimeZone('created_at')).values('created_at') Related How can I cast a DateField() + TimeField() to … -
Sum aggregation over a JsonField using Django Orm
I have a model in my django project with the following structure: class Portfolio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) entered_usdt = models.DecimalField(max_digits=22, decimal_places=2, default=0) detail = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I would like to have a Sum aggregate function over non-zero value keys of detail field of records this model in database. This field may be empty or have different keys for earch record in database for example I capture a section of database to better explain what I mean: For this purpose, I wrote the below code snippet with pure Python, which first extracts their keys for records whose details are not empty, and then calculates the sum of all those keys in all those records. import json from bestbuy.models import Portfolio from django.db.models import Q def calculate_sum_of_all_basket_coins(): non_zero_portfolios_details = list(Portfolio.objects.filter(~Q(detail={})).values('detail')) detail_list = list() result = {} for detail in non_zero_portfolios_details: detail_list.append(json.loads(portfolio)) for d in detail_list: for k in d.keys(): if k in result: result[k] += d.get(k, 0.0) else: result[k] = d.get(k, 0.0) return result I know this method is not good at all because as the database records increase, this function takes more and more time to perform this calculation. I also read the below … -
How I do save stars in Movie model?
Wha I want to achive. I want to save stars in Movie model when def average_stars() is used. I want to put a number in stars and save it when the movie function is called like the code below. What should I do? class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars -
AuthCanceled at /oauth/complete/github/ (Authentication process canceled)
I'm working with a Django app and when I try to login with Github, this error occurs: AuthCanceled at /oauth/complete/github/ Authentication process canceled Request Method: GET Request URL: https://my-site.com/oauth/complete/github/?code=xxxxxxxxxxxxxx&state=xxxxxxxxxxxxxx Django Version: 3.0.5 Exception Type: AuthCanceled Exception Value: Authentication process canceled Exception Location: /usr/local/lib/python3.7/site-packages/social_core/utils.py in wrapper, line 254 Python Executable: /usr/local/bin/python Python Version: 3.7.2 Python Path: ['/code', '/usr/local/bin', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages'] I have set (correctly, I think) SOCIAL_AUTH_GITHUB_KEY and SOCIAL_AUTH_GITHUB_SECRET on my settings.py (adding https://my-site.com/oauth/ as Authorization callback URL on https://github.com/settings/applications/XXXXX). Any idea of where is the problem? -
Strings from default locale missing from Django JavaScript catalog
Problem The problem I am having is that the JavaScript catalog doesn't include fallback strings in certain scenarios. In other words: when string "A" is not translated in es_MX but it is translated in es, the JavaScript catalog contains the default or untranslated "A" string. I set up an app that demonstrates this problem: https://github.com/cmermingas/i18n_test Setup LOCALE_PATHS set to PROJECT_ROOT/locale. Translations for all apps stored under LOCALE_PATHS. JavaScriptCatalog configured without packages: path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog') es_MX and es translations that demonstrate the problem: The string "es - Not translated" is translated in the es locale. The string "es_MX - Not translated" is translated in the es_MX locale. Workaround This works if I pass packages to JavaScriptCatalog: path( 'jsi18n/', JavaScriptCatalog.as_view(packages=["testapp"]), name='javascript-catalog' ) But this is not required, is it? I tried this answer, which suggests adding domain="django", but it didn't work for me. What am I doing wrong or is this an issue? -
Why am I seeing "No module named '_tkinter" when I deploy django to heroku?
django works well on my local machine. But, when I deploy it to heroku, I see "ModuleNotFoundError" "No module named '_tkinter'". Though, I never imported "_tkinter" or "tkinter" in my code. Your help will be appreciated. Thank you. ModuleNotFoundError at / No module named '_tkinter' Request Method: GET Request URL: https://howididit.herokuapp.com/ Django Version: 4.0.6 Exception Type: ModuleNotFoundError Exception Value: No module named '_tkinter' Exception Location: /app/.heroku/python/lib/python3.10/tkinter/init.py, line 37, in Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.5 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] -
Django with social auth: Direct assignment to the forward side of a many-to-many set is prohibited
When trying to authenticate (create) a user in Django, I get the following error: Direct assignment to the forward side of a many-to-many set is prohibited. Use gave_mangoes.set() instead. Code: models.py ... from waters.models import Water class User(AbstractUser): id = models.AutoField(primary_key=True) posts = models.ManyToManyField(Water) # MANY TO MANY FIELD CAUSING ERROR ... oauth.py from social_core.backends.oauth import BaseOAuth2 class <name>Oauth2(BaseOAuth2): name = "<name>" AUTHORIZATION_URL = "<url>" ACCESS_TOKEN_URL = "<url>" ACCESS_TOKEN_METHOD = "POST" EXTRA_DATA = [("refresh_token", "refresh_token", True), ("expires_in", "expires")] def get_scope(self): return ["read"] def get_user_details(self, response): profile = self.get_json("<url>", params={"access_token": response["access_token"]}) return { "id": profile["id"], "username": profile["username"], ... } def get_user_id(self, details, response): return details["id"] I read this answer that deals with the same error: You need to save the cart before you can add items to the many-to-many field. However, since I'm using Python Social Auth, it creates the user in the backend, so I'm not able to save it and modify the field later. How can I fix this error? -
why is CSS align-items not centering my text
.top-part { position: relative; display: flex; background: rgba(51, 102, 255,0.7); width: 100%; height: 8cm; background-position: center; background-size: cover; } .not-content { display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; font-family:'Consolas','Courier New','Trebuchet MS'; color: white; line-height: .5cm; flex-wrap: wrap; } <section class="top-part"> <div class="not-content"> <h1><strong>BIG TEXT</strong></h1> <h4>TEXT</h4> </div> </section> i don't know what error I've made, the "align-items: center;" is not working as it should be, it's not centering my text horizontally -
Send Email: user.email_user vs send_mail
_Hi, gentlemans and ladies.) I want to send you email (some spam), but I couldn't. Can you help me? If I use 'email_user' it sends the email. current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') But when I want to use send_mail instead of email_user, it's not working. I want to understand what I do wrong. send_mail(subject, message, email_from, recipient_list, fail_silently=False) My settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = get_secret('EMAIL_HOST_USER') EMAIL_HOST = get_secret('EMAIL_HOST') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = get_secret('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = get_secret('EMAIL_HOST_PASSWORD') # Custom setting. To email RECIPIENT_ADDRESS = ['None']