Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot execute shell command on Microsoft IIS
After hosting the Django application on IIS, this fragment of code doesn't work, when I try to execute the command manualy on cmd it works fine but it's doesn't work when the application hosted on IIS execute that command with the code bellow. I've tried to grant all permissions to DefaultAppPool but nothing changes. def convert_to_pdf(input_file, output_file): wordfile = input_file command = ["soffice", "--convert-to", "pdf", wordfile, "--outdir", os.path.dirname(output_file)] subprocess.call(command, shell=True) It works good when the application is outside of IIS environnement. Code -
Why is my Django page not being found, even though I have created a model instance for the page?
Details: I have a Django application where I'm trying to create a dynamic view that displays a detail page for a model instance based on a URL parameter. I have set up the following: Model Code: class Card(models.Model): background_image_id = models.CharField(max_length=100) border_id = models.CharField(max_length=100) image = models.ImageField(upload_to='cards/') number = models.IntegerField() name = models.CharField(max_length=30) subtitle = models.CharField(max_length=100) title = models.CharField(max_length=200) card_paragraph1 = models.TextField() card_paragraph2 = models.TextField() card_paragraph3 = models.TextField() card_paragraph4 = models.TextField() card_button_class = models.CharField(max_length=100) card_detail_url = models.CharField(max_length=100, blank=True, null=True) card_modal_class = models.CharField(max_length=100) card_temple_url = models.CharField(max_length=100, blank=True, null=True) quote = models.CharField(max_length=255) background_modal_image_id = models.CharField(max_length=100) modal_title = models.CharField(max_length=100) View Code: from django.shortcuts import render from .models import Card def card(request, name): try: # Attempt to retrieve the card with the given name card = Card.objects.get(name=name) except Card.DoesNotExist: # If no card is found, render the placeholder template return render(request, 'cards2/temples_placeholder.html') else: # If the card is found, render the card detail template return render(request, 'cards2/card.html', {'card': card}) URL Code: from django.urls import path from . import views urlpatterns = [ path('card/<str:name>/', views.card, name='card_detail'), ] Issue: When I try to access a URL like http://127.0.0.1:8000/card/arepage/, I get a 404 error, indicating that the page cannot be found. ("arepage" being the name of my … -
Django/nginx/gunicorn giving this in deployment: GET https://.../ net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)
In development my app runs fine, when deployed to my server running django with nginx/gunicorn I get this error on some (not all) pages when I goto them: GET https://mywebpage.yes.com/longhtmlpage/ net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK) I am not even sure where to start with this one, I only see the error by bringing up the browser's dev console. I know its happening though as the web site 'dies' when I hit a page that produces this error, by dies I mean like the menus don't work and I have to reload not the page causing the error but something like the index. Never seen this before and not sure where to start hunting it down, I am curious if its some timeout happening? These pages are pretty large of lots of text(copied straight HTML over from an old site and put it into a static django page) -
Django/Docker multiple containers error - could not translate host name "db" to address: Temporary failure in name resolution
I am working on creating directory and subdirectories: main project directory that contains backend and frontend code/containers. I am working on the connection of main directory and the backend first. Here's my backend docker-compose.yml: `services: db: image: postgres volumes: # - ./docker/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d - ./data:/var/lib/postgresql/data/ # volumes: # - ./data:/app/backend/data environment: POSTGRES_DB=postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres backend: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app/backend env_file: - docker/environment/db.env ports: - "8000:8000" restart: on-failure depends_on: - db links: - db:db Here's my backend Dockerfile: >! `FROM python:3 >! ENV PYTHONDONTWRITEBYTECODE=1 >! ENV PYTHONUNBUFFERED=1 >! WORKDIR /app/backend/ >! COPY requirements.txt /app/backend/ >! RUN pip install -r requirements.txt >! COPY . /app/backend/ >! EXPOSE 8000 >! CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]` >! >! >! Also, here's the database settings in settings.py: >! `DATABASES = { >! 'default': { >! 'ENGINE': 'django.db.backends.postgresql', >! 'NAME': os.environ.get('POSTGRES_NAME'), >! 'USER': os.environ.get('POSTGRES_USER'), >! 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), >! 'HOST': 'db', >! 'PORT': 5432, >! } >! }` My backend container works fine if I cd into backend and do a docker compose up. I am trying to set up a docker-compose.yml from the main folder so that I can do a docker compose up from main directory and it would spin … -
Django API - CORS Error with Login (Avoiding Django REST Framework & corsheaders)
I'm new to Django and building a web API without Django REST Framework. My Setup: Angular for frontend (compiled for production) Django backend with user login/register functionality as a First step Used collectstatic command to include Angular's compiled assets Done the setup in urls.py points to Angular's index.html for the main URL -----------------------urls.py------------------- from django.contrib import admin from django.urls import include, path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/auth', include('user_auth.urls')), path('', TemplateView.as_view(template_name='index.html')), path('<path:path>', TemplateView.as_view(template_name='index.html')), ] -----------------------settings.py------------------- STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / 'frontend/dist/frontend/browser'] STATIC_ROOT = BASE_DIR / 'static' CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", # Angular dev server "http://127.0.0.1:4200", "http://localhost:8000", # Django server "http://127.0.0.1:8000", ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'http://127.0.0.1:8000' ) CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = [ 'content-type', 'X-CSRFToken', 'authorization', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Headers' ] Issue: I'm encountering a CORS error when making a login request to http://127.0.0.1:8000/api/auth/login. Attempts: I tried using the corsheaders package to resolve the issue with CORS and CORS issue has been resolved but then faced a CSRF token issue when make a post request to the http://127.0.0.1:8000/api/auth/login.. I understand by using the csrf_exempt decorator i can resolve the issue, Question: Is my approach of building a custom API without external packages feasible and correct? Thank … -
how to create an object for a Django model with many to many field?
class Date(models.Model): date = models.DateField() def __str__(self): return str(self.date) class Time(models.Model): time = models.TimeField() def __str__(self): return str(self.time) class Showtimes(models.Model): theater = models.ForeignKey(Theater,on_delete=models.CASCADE,related_name="theater") movie = models.ForeignKey(Movie,on_delete=models.CASCADE,related_name="movie") show_date = models.ManyToManyField(Date) show_time = models.ManyToManyField(Time) how can i create a objects with multiple date and time by passing aruguments in objects.create function call Showtimes.objects.create(theater=th,movie=m,show_date = Date.objects.all(),show_time = Time.objects.all()).save() i want to create a object for ShowTimes by function call objects.create by passing all date and time field -
Is there a way to use bcc with django mailgun mime
I am using Mailgun mime with my django project to send out newsletters but i'm not sure if their is a way to use blind carbon copy so that every recipient can't view every other recipients email addresses i have looked from through the documentation for mailgun and the mailgun mime module but it doesn't seem to be very clear if you can or not -
Not redirecting to correct template
So I am practicing django cbvs and I am using update veiw to update model data and I created a button which is suppose to redirect to the form to update but it is showing me the same template page with jst url updated and id infront of it. I have django 1.11.25 installed currently heres my app url and views and the details page: urls: from django.conf.urls import url from Cbvs_app import views app_name = 'Cbvs_app' urlpatterns = [ url(r'^$',views.School_List.as_view(),name='list'), url(r'(?P<pk>\d+)/$',views.School_Detail.as_view(),name='details'), # it simply grabs the primary key provided in href and displays corresponding detail view to the primary key url(r'^create/$',views.School_Create.as_view(),name='create'), # print("Registering SchoolUpdateView URL"), url(r'^update/(?P<pk>\d+)/$',views.SchoolUpdateView.as_view(),name='update'), ] Views: class School_Create(CreateView): # my create view is working fine fields = ('name','principal','location') model = models.School template_name = "Cbvs_app/school_form.html" class SchoolUpdateView(UpdateView): fields = ("name","principal") model = models.School template_name = "Cbvs_app/school_form.html" forms: {% extends "Cbvs_app/Cbvs_app_basic.html" %} {% block body_block %} <div class="jumbotron"> <h1>Welcome to detail of all schools</h1> <h2>School details: </h2> <p>Name: {{school_detail.name }}</p> <p>Principal: {{school_detail.principal }}</p> <p>Location: {{school_detail.location }}</p> <p>Students:</p> {% for student in school_detail.students.all %} <p>{{student.name}} who is {{student.age}} years old.</p> {% endfor %} <p>Id: {{school_detail.pk}}</p> <p><a class='btn btn-warning' href="{% url 'Cbvs_app:update' pk=school_detail.pk %}">Update</a></p> </div> {% endblock %} I tried to … -
Is it reasonable to use Vue + Django / React + Django?
I've decided to create a portfolio project using vue and django. But i've asked myself a question if i should do this. Im not going to use SPA, vue is required only for unifining and more comfortable working with ui (forms, buttons etc.) I wondered if such a choice will bring worse user experience and make my project more difficult for nothing. Have anyone worked with such cases? I have been working with those frameworks one-by-one, but have never tried to combine those. -
CSS/JS Issue: Grey Space Appears Between Navbar and Content on Page Load, Then Disappears on Interaction
I'm working on a Django-based website and encountering an issue with a grey space appearing between my fixed navbar and the content on the home page. The grey space appears only on the initial page load, and once I interact with the page (like scrolling), the grey space disappears, and the layout corrects itself. Here's what happens: On initial load: A grey space appears between the navbar and the content. After any small interaction: The grey space disappears, and the page layout behaves as expected. What I've Tried: I’ve traced the issue to this JavaScript that adjusts the margin of the content based on the height of the navbar: document.addEventListener("DOMContentLoaded", function () { var navbar = document.getElementById("navbar"); var content = document.querySelector(".content"); function adjustContentMargin() { var navbarHeight = navbar.offsetHeight; content.style.marginTop = navbarHeight + "px"; } // Adjust margin on page load window.onload = function() { adjustContentMargin(); }; // Re-adjust on window resize window.addEventListener('resize', function () { adjustContentMargin(); }); }); Problem: When the JS is active, the page initially loads with the grey space between the navbar and the content. The margin-top gets applied, but it looks like it happens after the grey space appears. If I remove the JS, the page … -
Storing time and date in postgre database based on local time in django project
I have a virtual server in Europe where a series of csv files are uploaded I am trying to use a script to read the information from csv and store it in the database(postgresql) My problem is when I read the date from the csv file, the date is based on Iran's time zone and I want it to be saved in the same way, but the time is saved based on utc this is a sample of date records in csv files 2024-09-12 08:00:00,.... and this is my command from read data from csv: AnemometerData = apps.get_model("DataLoger", "AnemometerData") class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("from_date", type=str) def handle(self, *args, **options): self.read_csv(options["from_date"]) def validate_date(self, date): try: _date = datetime.strptime(date, "%Y-%m-%d").replace(minute=0, second=0, microsecond=0) return _date except Exception as e: raise CommandError(e) def read_csv(self, from_date): from_date = self.validate_date(from_date) base_path = settings.BASE_DIR path = os.path.join(base_path, "DataLoger", "FTP") iran_tz = pytz.timezone('Asia/Tehran') current_time = datetime.now(iran_tz).replace(minute=0, second=0, microsecond=0, tzinfo=None) while from_date <= current_time: for id in ["G241156", "G241157"]: try: time_str = from_date.strftime("%Y%m%d_%H%M") file_path = os.path.join(path, f'{id}_{time_str}.csv.gz') df = pd.read_csv(file_path, compression='gzip', header=0, sep=',', quotechar='"') remove_columns = ['Anemometer 100m;wind_speed;Count', 'Anemometer 96m;wind_speed;Count', 'Anemometer 60m;wind_speed;Count', 'Anemometer 45m;wind_speed;Count', 'Wind Vane 94m;wind_direction;Count', 'Wind Vane 45m;wind_direction;Count', 'Hygro/Thermo 95m;humidity;Count', 'Hygro/Thermo 10m;humidity;Count', 'Hygro/Thermo 95m;temperature;Count', 'Hygro/Thermo 10m;temperature;Count', … -
Is it possible to switch to a through model in one release?
Assume I have those Django models: class Book(models.Model): title = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book) I already have a production system with several objects and several Author <-> Book connections. Now I want to switch to: class Book(models.Model): title = models.CharField(max_length=100) class BookAuthor(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) author = models.ForeignKey("Author", on_delete=models.CASCADE) impact = models.IntegerField(default=1) class Meta: unique_together = ("book", "author") class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book, through=BookAuthor) If I do this Migration: from django.db import migrations def migrate_author_books(apps, schema_editor): Author = apps.get_model('yourappname', 'Author') BookAuthor = apps.get_model('yourappname', 'BookAuthor') for author in Author.objects.all(): for book in author.books.all(): # Create a BookAuthor entry with default impact=1 BookAuthor.objects.create(author=author, book=book, impact=1) class Migration(migrations.Migration): dependencies = [ ('yourappname', 'previous_migration_file'), ] operations = [ migrations.RunPython(migrate_author_books), ] then the loop for book in author.books.all() will access the new (and empty) BookAuthor table instead of iterating over the existing default table Django created. How can I make the data migration? The only way I see is to have two releases: Just add the new BookAuthor model and fill it with data, but keep the existing one. So introducing a new field and keeping the old one. Also change every single place where author.books … -
Cannot get User Information within B2C Access Token
def get_access_token(authorization_code): token_url = "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxxxcxxxxe/oauth2/v2.0/token" redirect_uri = "https://localhost/api/oauth2/callback" client_id = "xxxxxx-xxx-xxxx-xxx-xxxxxx" client_secret = "xxxx~xxxxx~xxxx_xxxxxxxxx" scope = "https://graph.microsoft.com/.default" headers = {'Content-Type' : 'application/x-www-form-urlencoded'} token_data = { 'grant_type': 'client_credentials', 'code': authorization_code, 'redirect_uri': redirect_uri, 'client_id': client_id, 'client_secret': client_secret, 'scope': scope, } response = requests.post(token_url, headers = headers, data=token_data) token_json = response.json() if 'access_token' in token_json: return token_json['access_token'] else: raise Exception(f"Error fetching access token: {token_json.get('error_description', 'Unknown error')}") I can't find any user information within the bearer that Microsoft provides. The token end point seems to be correct and I get all the user info within Microsoft Graph Explorer but can't on my django app. -
Color problem in disqus in Django and Tailwind
I tried to use disqus in my django project: <div> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */ var disqus_config = function () { this.page.url = "{{ request.path }}"; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = "{{ news.id }}"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function () { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://site-name.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> But I got this error: Uncaught Error: parseColor received unparseable color: oklch(0.7464770.0216264.436) I'm using tailwind in project and I guessed that problem might be because of it. So I completely removed tailwind styles and it worked. But my whole project works with tailwind, I can't remove or replace it. I tried using the prose class from the @tailwindcss/typography plugin, but that didn't work either. -
Django date format puzzle in multi language app - SHORT_DATE_FORMAT not used with English
We use Django 4.2.11 and I have a bit of a date format puzzle regarding localization in different languages in our project. We are using jquery datepicker and configure it with the current active language. The behaviour of date fields is consistent in languages such as German, Italian and French. Dates are displayed according to the SHORT_DATE_FORMAT of Django, and the returned dates of datepicker show the same formatting. Only with English it's different. The SHORT_DATE_FORMAT is defined as being m/d/Y - but the date get's displayed in the form of YYYY-MM-DD. This leads to the weird behaviour that the user gets displayed a date like for instance 2024-09-08 and when chosing a date from the datepicker the same field shows a value of 09/08/2024. But still the form can be saved without errors and the date is handled correctly. The date field is defined as declarationDate = models.DateField() in the model. We are using django-crispy-forms 2.1 with bootstrap 5. Any ideas what goes wrong here? Where can I look? (I've looked for some time now ...) -
Django autoreload raises: TypeError: unhashable type: 'types.SimpleNamespace'
When I upgrade importlib_meta from version 8.4.0 to 8.5.0 (released just yesterday, Sep 11 2024), I get the following error when I start running the development server with python manage.py runserver: File "/app/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 75, in execute super().execute(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 459, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 112, in handle self.run(**options) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 119, in run autoreload.run_with_reloader(self.inner_run, **options) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 671, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 660, in start_django reloader.run(django_main_thread) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 344, in run self.run_loop() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 350, in run_loop next(ticker) File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 390, in tick for filepath, mtime in self.snapshot_files(): File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 411, in snapshot_files for file in self.watched_files(): File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 304, in watched_files yield from iter_all_python_module_files() File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 120, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) TypeError: unhashable type: 'types.SimpleNamespace' I actually could narrow the problem down to the following commit https://github.com/python/importlib_metadata/commit/56b61b3dd90df2dba2da445a8386029b54fdebf3. When I install importlib_meta just one commit before the problematic commit via pip install git+https://github.com/python/importlib_metadata@d968f6270d55f27a10491344a22e9e0fd77b5583 the error disappears. When I install … -
Django Admin: How to Set a Default Filter Without Conflicting with User-Selected Filters?
I'm working with the Django Admin panel and need to set a default filter for a model's changelist view. When the user opens the changelist page for the first time, I want it to automatically filter by a specific value (e.g., status="A"). However, when a user selects a different filter (e.g., status="B"), the default filter (status="A") should not be applied. What I Have Tried: I've overridden the changelist_view method in my ModelAdmin class to check if any status filter is present in the request. If not, I add the default filter (status=A). Here’s what my code looks like: from django.contrib import admin from django.shortcuts import redirect from django.urls import reverse from .models import Person # Replace with your actual model class PersonAdmin(admin.ModelAdmin): list_display = ('name', 'status') # Adjust fields to match your model list_filter = ('status',) # Adjust filters to match your model def get_queryset(self, request): # Get the original queryset without any default filtering qs = super().get_queryset(request) return qs def changelist_view(self, request, extra_context=None): # Check if any filters related to 'status' are already applied by looking at request.GET if 'status' not in request.GET and 'status__exact' not in request.GET: # Redirect to the same changelist URL with the default filter … -
AADSTS50011: The redirect URI 'http://127.0.0.1:8000/oauth2/callback' specified in the request does not match the redirect URIs
Message: AADSTS50011: The redirect URI 'http://127.0.0.1:8000/oauth2/callback' specified in the request does not match the redirect URIs configured for the application '456b3ef5-cdbe-4d58-aa7b-69f95fffac29'. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Navigate to https://aka.ms/redirectUriMismatchError to learn more about how to fix this. I don't understand why I get this error, although I set everything up strictly according to the documentation. User's image enter image description here My current django setting.py file Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_auth_adfs', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', # third party 'django_auth_adfs.middleware.LoginRequiredMiddleware', ] AUTHENTICATION_BACKENDS = ( 'django_auth_adfs.backend.AdfsAuthCodeBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ) # Microsoft Azure AD configuration AZURE_CLIENT_ID = os.environ.get('AZURE_CLIENT_ID') AZURE_TENANT_ID = os.environ.get('AZURE_TENANT_ID') AZURE_CLIENT_SECRET = os.environ.get('AZURE_CLIENT_SECRET') AZURE_REDIRECT_URI = os.environ.get('AZURE_REDIRECT_URI') AZURE_AUTHORITY = os.environ.get('AZURE_AUTHORITY') AZURE_SCOPES = os.environ.get('AZURE_SCOPES').split() AUTH_ADFS = { 'AUDIENCE': [f'api://{AZURE_CLIENT_ID}', AZURE_CLIENT_ID], 'CLIENT_ID': AZURE_CLIENT_ID, 'CLIENT_SECRET': AZURE_CLIENT_SECRET, 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': 'roles', 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': AZURE_TENANT_ID, 'RELYING_PARTY_ID': AZURE_CLIENT_ID, 'LOGIN_EXEMPT_URLS': [ '^api', ], } LOGIN_URL = "django_auth_adfs:login" LOGIN_REDIRECT_URL = "dashboard" LOGOUT_REDIRECT_URL = '/' Could you please tell me what could be the reason for this error? I have been trying to figure it out … -
Config pytest-django and pre-commit in Django project
I have a Django project with the following construction: . ├── db.sqlite3 ├── manage.py ├── switch │ ├── __init__.py │ ├── settings.py ├── store │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── tests | | ├── __init__.py | | ├── tests.py │ ├── apps.py │ ├── migrations │ ├── urls.py │ └── views.py ├── .pre-commit-config.yaml └── pytest.ini My author is test.ini: [pytest] DJANGO_SETTINGS_MODULE = store.settings python_files = tests.py tests_*.py *_tests.py The pre-commit file.yaml: exclude: "^docs/|/migrations/" default_stages: [commit] repos: - repo: local hooks: - id: pytest-check name: pytest-check entry: pytest language: system pass_filenames: false always_run: true When running tests locally pytest, everything works without errors. When running pre-commit locally pre-commit run --color=always --all-files, everything works without errors. When I try to commit, I get an error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If add a forced installation of an environment variable in the test file with the path to the settings file and call django.config(), then the problem is solved. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings") django.setup() But I think this is the wrong way and there is another more optimal solution. Please … -
Using Django to visualise scraped data
Hi I'm new to django and thought it would be interesting to use it to visualise a data I scraped from certain websites, sth like this video) (https://www.youtube.com/watch?v=TcnWEQMT3_A&list=PL-2EBeDYMIbTt63EH9ubqbvQqJkBP3vzy&index=1) However I'm finding it difficult to choose a right way of how to load a data. Right now, I have a python program that scrapes stats of players from big 5 leagues, from fbref.com (football related website) and store them to a csv file. I think I have two options now? Creating a Model in django and read a csv file to store each row as a separate model. So basically, I'm storing a data at Django db, similar to Not creating a separate Django model and using pandas dataframe. (Not storing my data to Django DB). I feel like first approach is less efficient because I'm thinking of adding further data analysis later on, so I would end up using pandas dataframe mainly anyways. However I'm lowkey worried about if anything would go terribly wrong if I don't use the Django database. Which approach is better and are there better ways to do this?? Thank you! I initially tried second approach but I got worried of data managements, -
django.contrib.staticfiles.templatetags and sharedpy-0.0.106
I am trying to move a deployment from one server to another to meet some organisational requirements. The components on the source server include: Django 2.2.7 Python 3.7 Components on target (these versions are not fixed but must be current) Django 4.2.13 Python 3.10.14 When running manage.py makemigrations I receive the following error: File "/home/dtracker/dtracker/prime/models.py", line 2, in from sharedpy.django.utils import cache_get_or_set File "/home/dtracker/env/lib/python3.10/site-packages/sharedpy-0.0.106-py3.10.egg/sharedpy/django/utils.py", line 10, in ModuleNotFoundError: No module named 'django.contrib.staticfiles.templatetags' Reference to django.contrib.staticfiles.templatetags in settings.py has replaced with django.templatetags.static. As per the last line of error, django.contrib.staticfiles.templatetags cannot be found as it is not available in Django 3+. My question is, does sharedpy-0.0.106 require django.contrib.staticfiles.templatetags and if so, how can I remove the need to use sharedpy? Tried to remove sharedpy however when running command received error stating it was required. -
Not able to get email when user submits the form
I have created contact form with react and connected it with mysql database hosted using RDS. i used django for building the database. before some days i was able to get email when i am submitting the form and the data was also been stored in the database but now when i am submitting the form i am not getting an email notification of submission but i can see the data in my database. i also tried to send test email from the console and it worked. when i changed the API from urls.py and then i submitted the form, i got the mail but when i did the submission again i did not get any mail. this is my setting.py code DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('DB_NAME', default='myportfolio'), 'USER': config('DB_USER', default='root'), 'PASSWORD': config('DB_PASSWORD', default=''), 'HOST': config('DB_HOST', default=''), 'PORT': config('DB_PORT', default='3306'), } } # Email backend configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') views.py from django.core.mail import send_mail from django.conf import settings from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from .models import Form from .serializers import FormSerializer import json @csrf_exempt … -
Encountering a 302 redirect issue when submitting a form in React/Django app as API call is being made without proper authentication
In my Django/React app I want a user to be signed in to be able to successfuly submit a request to an API. I successfully login with google and I believe I am passing all of the correct data to the backend api for it to be called. I have configured CORS, ensured my CSRF tokens match, am using @login_required on my Django view, use "credentials: 'include'" in the api call, and have exhausted both ChatGPT and my own internet searching to solve the problem. From my Conversation.jsx file I want to call /api/ask_new_york from app/views.py. Even when logged in I get a 302 response. Here is all of what I think is the relevant code and the output: settings.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', ] # CORS settings CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True # CSRF settings CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://localhost' ] # Disable CSRF cookies only if needed CSRF_COOKIE_SECURE = False LOGIN_REDIRECT_URL = '/' LOGIN_URL = '/login/' LOGOUT_REDIRECT_URL = '/' app/views.py: @csrf_exempt def get_csrf_token(request): csrf_token = get_token(request) return JsonResponse({'csrf_token': csrf_token}) @login_required def ask_new_york(request): if request.method == 'POST': try: data = json.loads(request.body.decode('utf-8')) input_value = data.get('input_value' users/views.py: This handles the … -
i am using cookiecutter-django with docker and it keeps reloading in the local env
I am starting to use cookiecutter-django 2024.07.26 with docker and after a few updates it keeps reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/contrib/sites/models.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/contrib/sites/shortcuts.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/account/views.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/generic/edit.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/account/mixins.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/generic/base.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/decorators/cache.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/django/views/decorators/debug.py', reloading aqua_loui_local_django | * Detected change in '/usr/local/lib/python3.12/site-packages/allauth/decorators.py', reloading aqua_loui_local_django | * Restarting with watchdog (inotify) aqua_loui_local_django | Performing system checks... aqua_loui_local_django | aqua_loui_local_django | System check identified no issues (0 silenced). aqua_loui_local_django | aqua_loui_local_django | Django version 5.0.7, using settings 'config.settings.local' aqua_loui_local_django | Development server is running at http://0.0.0.0:8000/ aqua_loui_local_django | Using the Werkzeug debugger (https://werkzeug.palletsprojects.com/) aqua_loui_local_django | Quit the server with CONTROL-C. aqua_loui_local_django | * Debugger is active! -
On the fly video conversion in django during upload
I an making a backend in django rest where user will be uploading videos in multiple formats such as mp4, avi, etc. I want to convert these videos to a single h264 format while storing them but rather than first taking the full video and then converting it i want to convert it while it is being uploaded how can i do that. The video file is comming through multipart/form-data I have been stucck and not able to find a plausible approach but i know that i have to use FFMpeg in some manner.