Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have different settings in local settings.py and settings.py in a docker container
I finally sorted this issue by using the answer in the link below. I'm posting this here in the hope others might find this and click on the link below. I was stuck on this for a long time and couldn't get an answer anywhere. This link should be way more popular but I don't have the credits to give it an upvote. How to make different database settings for local development and using a docker I tried re-configuring my wsl-config hosts, multiple re-configurations of my docker-compose.yml. I tried 'host.docker.internal', extra-hosts, links -
type object 'my model' has no attribute 'CHOICES' after running 'migrate'
so here in my migration file i have this function : def populate_categories(apps, schema_editor): CategoryModel = apps.get_model('app_l3', 'CategoryModel') for name, desc in CategoryModel.CATEGORY_CHOICES: CategoryModel.objects.create(category_name=name, description=desc) this is for auto populating my database, and the model is this CATEGORY_CHOICES = ( ('hardware', 'Hardware'), ('software', 'Software'), ('network', 'Network'), ('printer', 'Printer'), ('phone', 'Phone'), ('laptop', 'Laptop'), ) category_name = models.CharField(max_length = 150,unique=True,primary_key=True,choices=CATEGORY_CHOICES) description = models.TextField() category_creation_date = models.DateTimeField(auto_now_add=True,null=True,blank=True) so after i tried to run py manage.py migrate i got this error : for name, desc in CategoryModel.CATEGORY_CHOICES: AttributeError: type object 'CategoryModel' has no attribute 'CATEGORY_CHOICES' so how i could fix it .. and is there other ways to auto populate with predefined choices -
VSCode on Linux freezes when opening existing folder, but works fine after Git cloning the same folder
On Linux when I try to open a folder in vscode the program crashes. If I git clone this folder after opening vscode, everything works fine (I can run the code and everything). But otherwise I get an error if the folder has already been cloned and I try to open it "Visual Studio Code" Not responding On Windows everything works without problems. The code is python-django code -
Django User not inheriting Group permissions
I have a TestCase that i'm testing permissions on. I don't understand how this test is failing where it's failing: # Make sure group has permission group_permissions = self.my_group.permissions.filter(codename="view_mymodel") self.assertEqual(len(group_permissions), 1) print("Group Permissions:") for permission in group_permissions: print(permission) # Make sure user is in group user_groups = self.user.groups.filter(name="My User Group") self.assertEqual(len(user_groups), 1) user_permissions = self.user.get_all_permissions() print("User Permissions:") for permission in user_permissions: print(permission) # Make sure user has permission self.assertTrue(self.user.has_perm("myapp.view_mymodel")) This is failing at the last assertion. I can see the permission is set for the group but when i call get_all_permissions(), nothing shows up. That makes no sense because get_all_permissions() is suppose to return all permissions on both the User and the group. -
In django crispy form, forms.ImageField value always is None
I have a form with an image field but its value is always None. I found this. it says that I should put enctype="multipart/form-data" as an attribute of the form tag in my HTML template but I am using crispy so I do not have access to the form tag directly. As here says there is no need to put this attribute for crispy forms and it sets whenever it needed. So what is the problem with my image field? -
Django and htmx messages with refresh dataTables after submit form
I am a beginner in the django programming language who please need some assistance. I have a data which after validation of my form displays a success message: "Operation completed successfully" from the return httpReponse but does not refresh the page. However, by adding this script in the form <form hx-post="{{ request.path }}" class="modal-content" hx-on="htmx:afterRequest:location.reload()"> tag, the dataTable is refreshed but success message is not displayed views.py def index(request): all_person = Personne.objects.all() context = {'all_person': all_person} return render(request, 'index.html', context) def add_personne(request): if request.method == "POST": form = PersonneForm(request.POST) if form.is_valid(): form.save() return HttpResponse(status=204, headers={'HX-Trigger': json.dumps({ "personList": None, "showMessage": "Opération effectuée avec succès", }) }) else: form = PersonneForm() return render(request, 'form_personne.html', {'form':form}) <---------------------------- Début index.html -------------------------------------------> index.html {% extends "base.html" %} {% block title %}Tableau-Dynamique{% endblock title %} {% block content %} <div class="col md-12"> <button type="button" class="btn btn-primary" hx-get="{% url 'add_personne' %}" hx-target="#dialog" style="width:300px;"> Add New </button> </div> <br> <h3 class="mt-3">Option de recherche</h3> <!--HTML table with student data--> <table id="tableID" class="display"> <thead> <tr> <th class="px-2 py-2 text-center">N°</th> <th class="px-2 py-2 text-center">Nom</th> <th class="px-2 py-2 text-center">Age</th> </tr> </thead> <tbody> {% for personne in all_person %} <tr> <td>{{ forloop.counter }}</td> <td>{{personne.nom}}</td> <td>{{personne.age}}</td> </tr> {% endfor %} </tbody> </table> {% endblock … -
ValueError at /accounts/signup/ Cannot query "echiye@gmail.com": Must be "User" instance
Am using django-allauth for aunthentication and below is my custom user models. The password are not safe to the database because it will report incorrect password but the user will be created along with other necceasiry informations on the database entered during registrations are correctly saved rightly. password created using the createsuperuser is stored correctly too. Kindly help me out with the ValueError at /accounts/signup/ Cannot query "echiye@gmail.com": Must be "User" instance. class MyUserManager(UserManager): """ Custom User Model manager. It overrides default User Model manager's create_user() and create_superuser, which requires username field. """ def _create_user(self, email, password, username, first_name, phone_number, country, last_name, is_staff, is_superuser, wallet_address=None, private_key=None, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, first_name=first_name, last_name=last_name, username=username, is_staff=is_staff, is_active=True, last_login=now, date_joined=now, phone_number=phone_number, country=country, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) ''' def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) return self._create_user(email, password, True, True, **kwargs) def create_superuser(self, email, password, **kwargs): user = self.model(email=email, is_staff=True, is_superuser=True, **kwargs) user.set_password(password) user.save(using=self._db) return user ''' def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) user = self._create_user(email, password, True, True, … -
Dark Mode doesn't sync properly?
I'm having an issue syncing the Django admin panel theme with the application's side of the theme...Whenever I switch to Light mode from Dark mode on the app side, it changes to Auto and it should rather switch to Dark mode and vice versa. The issue persists on the admin side as well for some reason. If I switch from Light mode to Dark mode whilst in the admin panel and refresh the application's side, it changes it to Light mode? It's quite odd. I tried troubleshooting it and what I could find was an error pointing at theme.js which is a file part of the admin panel. It seems the problems stems from this file... theme.js 'use strict'; { window.addEventListener('load', function(e) { function setTheme(mode) { if (mode !== "light" && mode !== "dark" && mode !== "auto") { console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`); mode = "auto"; } document.documentElement.dataset.theme = mode; localStorage.setItem("theme", mode); } function cycleTheme() { const currentTheme = localStorage.getItem("theme") || "auto"; const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; if (prefersDark) { // Auto (dark) -> Light -> Dark if (currentTheme === "auto") { setTheme("light"); } else if (currentTheme === "light") { setTheme("dark"); } else { setTheme("auto"); } … -
Django: how to pass javascript code from python to form field attributes?
I'm using django-bootstrap-daterangepicker plugin that allows to create the following Django form: from django import forms from bootstrap_daterangepicker import fields class DateRangeForm(forms.Form): date_range = fields.DateRangeField() Everything works as expected until I want to add some dynamic daterangepicker-specific options like predefined ranges, that should be evaluated on every page refresh: $('#demo').daterangepicker({ ranges: { 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], }, }) If I use: from datetime import datetime, timedelta from django import forms from bootstrap_daterangepicker import fields, widgets class DateRangeForm(forms.Form): date_range = fields.DateRangeField( widget = widgets.DateRangeWidget( picker_options = { 'ranges': { 'Last week': [ (datetime.now() - timedelta(days=7)).isoformat(), datetime.now().isoformat(), ], }, }, ), ) then dates are evaluated on server start and not re-evaluated at page refresh. Is there a way to tell Django to treat string as javascript code to pass it to rendered page as code, not as string? Or are there other ways to solve this problem? -
Filtering in Django admin for multiple conditions on the same record
This is linked to my other question here, which I thought I had resolved. Nevertheless, when applying a filter by school, I get any project where any person belongs to that school. I want, instead, to filter only projects with persons that are both "Principal investigator" (role) and belong to a specific school. Right now the code below outputs a project that has any person linked which belongs to the filtered school, regardless of its role. My models.py: class School(models.Model): name = models.CharField(max_length=200) class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) school = models.ForeignKey(School, null=True, blank=True, on_delete=models.CASCADE) class PersonRole(models.Model): ROLE_CHOICES = [ ("Principal investigator", "Principal investigator"), [...] ] project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) person_role = models.CharField(choices=ROLE_CHOICES, max_length=30) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) My admin.py: class PISchoolFilter(admin.SimpleListFilter): title = 'PI School' parameter_name = 'school' def lookups(self, request, model_admin): return ( ('Arts & Humanities Admin',('Arts & Humanities Admin')), [...] ) def queryset(self, request, queryset): if self.value() == 'Arts & Humanities Admin': return queryset.filter( person__personrole__person_role__contains="Principal investigator", person__personrole__person__school=5 #5 is 'Arts & Humanities Admin' pk school. ).distinct() [...] def choices(self, changelist): super().choices(changelist) return ( *self.lookup_choices, ) class ProjectAdmin(NumericFilterModelAdmin, ImportExportModelAdmin): list_filter = [PI_SchoolFilter] Why … -
Using nested objects with react-hook-form
I am trying to send data to my backend using react-hook-form and this is the FormData interface: interface FormData { title: string; // other things location: { country: string | null; city: string | null; address: string | null; }; } The problem is that when I submit the form and observe it in my backend (django) it's something like it: <QueryDict: {'title': ['CCC'], 'location': ['[object Object]']}> So that the backend will not set location for the object -
Default avatar doesn't show up in my django-project profile
I tried to load a default avatar image in my profile page but it doesn't show up. However, new avatar photos actually does. Explain me, what did i worng? HTML template of profile page: {% extends 'movieapp/base.html' %} {% load static %} {% block content %} <h1>Данные пользователя</h1> <form method='post' enctype="multipart/form-data"> {% csrf_token %} {% if user.photo %} <p><img src="{{ user.photo.url }}"> {% else %} <img src="{% static 'default_image' %}"> {% endif %} {% for f in form %} <p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }}</label>{{ f }}</p> <div class="form-error">{{ f.errors }}</div> {% endfor %} <p><button type="submit">Отправить</button></p> </form> <hr> <p><a href="{% url 'password_change'%}">Сменить пароль</a></p> {% endblock %} forms.py: class ProfileUserForm(forms.ModelForm): username = forms.CharField(disabled='Логин', widget=forms.TextInput(attrs={'class': 'form-input'})) email = forms.CharField(disabled='E-mail', widget=forms.TextInput(attrs={'class': 'form-input'})) this_year = datetime.date.today().year date_birth = forms.DateField(widget=forms.SelectDateWidget(years=tuple(range(this_year - 100, this_year - 5)))) class Meta: model=get_user_model() fields=['photo','username','email','date_of_birth','first_name','last_name',] labels={ 'first_name':'Имя', 'last_name':'Фамилия', } widgets={ 'fist_name':forms.TextInput(attrs={'class': 'form-input'}), 'last_name':forms.TextInput(attrs={'class': 'form-input'}) } models.py: from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): photo=models.ImageField(upload_to='users/%Y/%m/%d/',blank=True,null=True,verbose_name='Фото') date_of_birth=models.DateTimeField(blank=True,null=True,verbose_name='Дата рождения') views.py: class ProfileUser(UpdateView): model=get_user_model() form_class = ProfileUserForm template_name = 'user/profile.html' success_url = reverse_lazy("profile_changed.html") extra_context = {'title': 'Профиль пользователя', 'default_image':settings.DEFAULT_USER_IMAGE} settings.py: STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/users/' DEFAULT_USER_IMAGE = MEDIA_URL + 'profile/chad.jpg' … -
ModuleNotFoundError: No module named 'config' gunicorn
I'm trying to run a django project on docker project ├── manage.py ├── config │ ├── settings.py │ ├── wsgi.py │ └── ... ├──__init__.py Dockerfile docker-compose.yml entrypoint.sh Dockerfile ... WORKDIR /app ... COPY project project EXPOSE 8000 COPY entrypoint.sh ./entrypoint.sh RUN chmod a+x ./entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] docker-compose.yml version: '3.9' services: ... web: build: . container_name: web restart: unless-stopped ports: - '8000:8000' depends_on: - db ... entrypoint.sh #!/usr/bin/env bash set -e RUN_MANAGE_PY='poetry run python project/manage.py' echo 'Collect static files...' $RUN_MANAGE_PY collectstatic --no-input echo 'Running migrations...' $RUN_MANAGE_PY migrate --no-input echo 'Starting server...' exec poetry run gunicorn project.config.wsgi:application --bind 0.0.0.0:8000 wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = get_wsgi_application() when I run the command docker-compose up I get an error web | ModuleNotFoundError: No module named 'config web | [2024-04-12 20:07:47 +0600] [15] [INFO] Worker exiting (pid: 15) web | [2024-04-12 20:07:47 +0600] [1] [ERROR] Worker (pid:15) exited with code 3 web | [2024-04-12 20:07:47 +0600] [1] [ERROR] Shutting down: Master web | [2024-04-12 20:07:47 +0600] [1] [ERROR] Reason: Worker failed to boot. collectstatic and migrate are successful I tried changing the gunicorn command to ... gunicorn project/config.wsgi:application ... I also tried removing the project from the command and tried … -
I am unable to fetch data line email from mongodb database in django framework while creating password reset page
Keyword: None Sub SQL: None FAILED SQL: ('SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE ("auth_user"."email" iLIKE %(0)s AND "auth_user"."is_active")',) Params: (('mohanrajjj.learn@gmail.com',),) -
i am deploying my Django app on vercel but then after deployment is successful i get a 404: NOT_FOUND Code: NOT_FOUND when i open the link
I am deploying my Django app on Vercel but then after deployment is successful I get a 404: NOT_FOUND Code: NOT_FOUND when I open the link. I'm deploying to Vercel. I expected my app to run but is not. i don't know the cause of this error. can anyone help me. -
Django GRPC Framework Issues
I am trying to use GRPC frameowrk in Django (latest version). I am facing an error that says: TypeError: requires_system_checks must be a list or tuple. After commenting the below code in base.ppy, the error gets resolved. if ( not isinstance(self.requires_system_checks, (list, tuple)) and self.requires_system_checks != ALL_CHECKS ): raise TypeError("requires_system_checks must be a list or tuple.") But is there any other work around for this so that we are not needed to make changes in the environment. -
In django how can i do listing of the data which has been user forignkey key in this
In my Django project, I have implemented two models: one for the vendor and the other for the user. The user model serves as the main authentication model and has been configured with specific permissions. Additionally, the user model includes a foreign key referencing the vendor model, enabling users to log in with their own credentials in the Django admin interface. Furthermore, users possess the permission to create entries in the User model. However, a challenge arises when attempting to assign a foreign key in the users model's company field, as it currently retrieves all available vendors. Instead, the objective is to retrieve only the vendor associated with the user How i can i achive this? i have tried with admin configs using this @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserAdminChangeForm add_form = UserAdminCreationForm fieldsets = ( ( _("Personal info"), {"fields": ("username", "password", "name", "first_name", "last_name", "email", "role", "vendor")}, ), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) list_display = [ "uuid", "username", "name", "email", "get_vendor_name", "role", "is_superuser", "is_active", "created", ] search_fields = ["name", "uuid", "email"] def get_vendor_name(self, obj): return obj.vendor.name if obj.vendor else None get_vendor_name.short_description = "Vendor Name" def … -
Adjust Stripe Subscription Billing Interval
I aim to modify the billing interval of a subscription in Stripe to include a one-time complimentary extension of 3 months when a user subscribes to a product. The regular billing interval for the plan is 1 year, resulting in a 15-month billing period with the extension. However, after this extended period, it should revert back to the original 1-year billing interval. This isn't a trial period; it's a complimentary 3-month extension for which I want to charge the user immediately. Below is my current implementation for the checkout session view, and I manage all changes using Stripe webhook `class CreateCheckoutSessionView(View): def post(self, request, *args, **kwrgs): ... checkout_session = stripe.checkout.Session.create( success_url=protocol + domain + reverse('payment_success')+'?session_id={CHECKOUT_SESSION_ID}', cancel_url = protocol + domain + reverse('payment_failed'), payment_method_types=['card'], mode='subscription', customer=customer.id, line_items=[{ 'price': price_id, 'quantity': 1, 'metadata': { } }], allow_promotion_codes = True, subscription_data={ 'default_tax_rates': [STRIP_TAX_ID], }, ) return redirect(checkout_session.url, code=303) ` -
Nginx Timeouts getting status code 502 when using Gunicorn
AM currently having an issue here. My Django application is timing out i.e 502 when i place it behind a proxy like nginx. I have tried to increase the timeouts but still not thing has change any help will be highly appreciated. Am using gunicorn as my production server. Any help will be highly appreciated. """ For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.43.78', 'localhost'] CSRF_TRUSTED_ORIGINS = ['https://192.168.43.78:8094'] INSTALLED_APPS = [ 'tickets', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'notifications', 'widget_tweaks' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'tickets.middleware.SessionTimeoutMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tickets.middleware.UserDashboardMiddleware', ] ROOT_URLCONF = 'ticket_resolution.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ticket_resolution.wsgi.application' DATABASES = { 'default': … -
How to make an HTML form be permanent after filling out the field, but before submitting?
Context: I think that filling out a form in a paper with a pen brings the person to pay more attention to what it writes and I wonder if there is a way to bring that to a html form. Expected Behaviour: The person clicks on a checkbox and it stays like that unless the person reloads the page, it cannot be "unclicked", or a person writes a settence in a text field and, after it presses enter (or tab) the field can't be edited. Doesn't have to behave exactly like that, any suggestion close to it will be helpful. It can be in HTML, Js, Python (for Django) or whatever, just wondered if there is a "simple" way or it would be a separate project all throughout. Tried searching on google but didn't find anything close to that. -
Django Installable App. Abstract class with dependencies on it's implementation
In my installable Django application, I have a class called Timer which I intend for users to implement: class Timer(models.Model): class Meta: abstract = True @abstractmethod def finish(self): raise NotImplementedError Additionally, I have a class for recording results: class TimerResults(models.Model): timer1 = models.ForeignKey(settings.TIMER_MODEL) parameter1 = models.IntegerField() parameter2 = models.IntegerField() parameter3 = models.IntegerField() My plan is for users to create their own Timer, implement finish method, which should then create TimerResults. However, this approach isn't working as intended. When I implement Timer in other app, django try to autodiscover other models, and eventually found TimerResults which has a foreign key referencing settings.TIMER_MODEL. However, TIMER_MODEL is not yet created, resulting in the following error message: "The field installable_app.TimerResults.timer was declared with a lazy reference to 'app.timer', but app 'app' doesn't provide model 'timer'." I found a solution where I can make the TimerResults class abstract and force the user to implement it, which solves the problem. However, I'm wondering if there are other ways to solve it. -
Django Allauth Instagram Authentication: Invalid Redirect URI Error
I'm integrating Instagram as a third-party login option into my Django app using Django Allauth. I've set up an Instagram Basic Display API app and configured ngrok to provide my website with an HTTPS scheme. Additionally, I've set up the redirect URIs for authorization, deauthorization, and deletion in the Instagram app settings as shown in the images below: app configuration picture redirect uris i also created an Instagram test user and accept it from the instagram apps and websites page instagram test users In my Django project's settings.py, I've configured Allauth to use the Instagram provider with the following setup: INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.instagram', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': {'access_type': 'online'} }, 'instagram': { 'APPS': [ { 'client_id': '463389002.....', 'secret': 'd34b120.....', 'redirect_uri': 'https://6112-196-179-81-60.ngrok-free.app/account/oauth/instagram/login/callback/', }, ], 'SCOPE': [ 'user_profile', ], } } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000', 'https://6112-196-179-81-60.ngrok-free.app', ] ALLOWED_HOSTS = [ 'localhost', '127.0.0.1:8000', '6112-196-179-81-60.ngrok-free.app', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', 'https://6112-196-179-81-60.ngrok-free.app', ] My urlpatterns in urls.py are configured as follows: urlpatterns = [ path('account/oauth/', include('allauth.urls')), ] On my home.html page, I've included the Instagram authentication URL as follows: {% load socialaccount %} <div> <form id="instagram_form" … -
How to connect MySQL Workbench to an AWS EC2 instance
I managed to connect a Django project of mine to an Ubuntu AWS instance. It runs pretty well so far, but now I want to know if it's possible to connect my MySQL Workbench application to it. -
Renaming relational tables on existing schema in Django
Due to a migration from django 2.x to django 4.x, I had to rename my project to fix the intial name containing '-' and no '_'. The initial project name was DEMANDE-PROJET In a Model called DEMANDE ( DEMANDE-PROJET_DEMANDE ), I have a foreign key ( field created_by ) to a model called UserDemandeMapper created_by = models.ForeignKey('UserDemandeMapper', related_name="demande_createur", on_delete=models.SET_NULL, null=True, blank=True) Django is handling this table on its own and on my DB browser I can see it on the name DEMANDE-PROJET_USERDEMANDE2573 Now I renamed my project, django want to request DEMANDE_PROJET_* instead of DEMANDE-PROJET_* I couldn't request anything anymore. I added : class Meta: db_table = "DEMANDE-PROJET_DEMANDE" to link my django model to the tables that gets a fixed name. And now I can request Demande without any problem. The problem comes from my created_by foreign key. I have the value of the ID but not the Model Object of the foreign model. I tried to add UserDemandeMapper a meta class with a db_name but nothing worked. As I'm not a migration expert and this side of django is a bit nebulous, I would like help on it. Thanks by advance. Damien -
How to retrieve the form data in Python using "POST" method
Recently I made a login form using HTML and JS (the JavaScript validating the form), and I have made an action in the form tag in HTML for where I would like to send and store the form data, which is a Python page because it is a server-side language (when I learned that JavaScript is not the best for storing sensitive data because it is client-side). This means I am playing with a language (PY), that I am not very familiar with but have used in the past. So How do I retrieve the form data on my PY script page and maybe I could use Django to get it? Thanks