Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't we create a field in Model Serializer which is not being used in Object Creation?
Models.py class Palika(CreatedInfoModel): name = models.CharField( max_length=50, help_text="Unique | Max: 50 characters | Gaun/Nagar Palika", ) district = models.ForeignKey( District, on_delete=models.PROTECT, help_text="Link to District" ) is_default = models.BooleanField(default=False, help_text="By default=False") active = models.BooleanField(default=True, help_text="by default=True") class Ward(CreatedInfoModel): name = models.CharField( max_length=50, # unique=True, help_text="", ) palika = models.ForeignKey( Palika, on_delete=models.PROTECT, related_name="wards", help_text="link to Gaun/Nagar Palika" ) active = models.BooleanField(default=True, help_text="by default=True") def __str__(self): return f"{self.name}" serializers.py class PalikaCreateSerializer(BaseModelSerializer): wards_names = serializers.ListField(child=serializers.CharField()) class Meta: model = Palika # Write only fields # 1. Common Write Only fields common_write_only_fields = get_common_write_only_fields_create() # 2. Custom Write Only fields with respect to model custom_write_only_fields = [ "name", "district", "wards_names", "is_default", "active", ] fields = common_write_only_fields + custom_write_only_fields # Extra Kwargs extra_kwargs = get_common_extra_kwargs_create() extra_kwargs.update( { "name": {"write_only": True}, "district": {"write_only": True}, "wards_names": {"write_only": True}, "is_default": {"write_only": True}, "active": {"write_only": True}, } ) def create(self, validated_data): print(validated_data) ward_names = validated_data.pop("wards_names") print(validated_data) validated_data["name"] = validated_data["name"].title() palika = super().create(validated_data=validated_data) for ward_name in ward_names: Ward.objects.create( app_type=palika.app_type, device_type=palika.device_type, created_date_ad=palika.created_date_ad, created_by = palika.created_by, name=ward_name, palika=palika ) return palika def validate(self, attrs): super().validate(attrs) model_name = get_model_name_by_self_obj(self) # Unique (Case Insensitive) validation unique_keys_to_be_checked = [] unique_ci_char_create_validator = UniqueCICharCreateValidator( CORE_APP_IMPORT_STRING, model_name, unique_keys_to_be_checked, attrs ) unique_ci_char_create_validator( CORE_APP_IMPORT_STRING, model_name, unique_keys_to_be_checked, attrs ) # Default Check … -
Django/Gunicorn Logging Redis exceptions
Background I noticed that when Django is incorrectly configured to connect with Redis, say for example transport encryption is enabled but the auth token is incorrect, then the application fails silently without anything in the logs, other than NGINX reporting the following: 2023/02/13 05:17:44 [info] 35#35: *248 epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream, client: *.*.*.*, server: _, request: "GET /sup/pleasant/ HTTP/1.1", upstream: "http://127.0.0.1:8000/sup/pleasant/", host: "myhost.com" The application logs do not report anything until I refresh the page a few times (F5). At this point, the container locks up for some reason and stops responding to ALB health checks, and is terminated by the Fargate service. Interestingly, when I turn the Redis server off and have Django Redis settings set to "IGNORE_EXCEPTIONS": False, then connection errors are reported in the application logs. django_redis.exceptions.ConnectionInterrupted: Redis ConnectionError: Connection closed by server. NOTE: Just to make it clear, even with "IGNORE_EXCEPTIONS": False, nothing is reported when the Redis server is online but the Django/Redis configuration details are misconfigured. Redis is being used for channels and caching. I've tested with DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS but it hasn't had an impact. Question How do enable exception logging … -
How do I test if the current logged in user's id is in a list of id's
I have this question model: class Question(models.Model): title = models.CharField(max_length=100) body = models.TextField(max_length=10000) user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "question" verbose_name_plural = "questions" db_table = "questions" def __str__(self): return self.body and then I have this question feeling model which is just for someone to like a question: class QuestionFeeling(models.Model): like = "like" feelings = [ (like , "like"), ] feeling = models.CharField(max_length=15,choices=feelings, default=like) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='feelings') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="question_feelings") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ['question', 'user'] verbose_name = "Question feeling" verbose_name_plural = "Question feelings" db_table = "question_feeling" def __str__(self): return str(self.feeling) I am using Django rest framework and I would like to see if a user already likes a question. I don't want to do a serializer method field where the database needs to be queried twice. I would just like to see if the logged in user's id matches any of the feelings' user ids On the front end the array for feelings that appear for each question looks like this: feelings: Array [ {…} ] 0: Object { id: 1, feeling: "like", created_at: … -
Error while Installing Module Chatter Box
"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD "-IC:\Users\Wajahat Murtaza\AppData\Local\Programs\Python\Python311\include" "-IC:\Users\Wajahat Murtaza\AppData\Local\Programs\Python\Python311\include" "-IC:\Users\Wajahat Murtaza\AppData\Local\Programs\Python\Python311\Include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /EHsc /Tppreshed/maps.cpp /Fobuild\temp.win-amd64-cpython-311\Release\preshed/maps.obj /Ox /EHsc maps.cpp c1xx: fatal error C1083: Cannot open source file: 'preshed/maps.cpp': No such file or directory error: command 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe' failed with exit code 2 [end of output] I got this error Please Help Me I have been trying Different tutorial from google but nobody help me -
Manage caching from Django Admin
I am currently looking for a way to manage the Django cache from the administration (having the possibility to turn it off, turn it on, or leave it on with a timeout of 8 hours). I have tried to use for this the django cache framework, with 3 buttons in the administration to different functions that turn off, activate or modify the cache timeout with no results (the cache remains activated with no possibility to turn it off or modify its timeout). I tried to use a script that restarts the server once one of these options is chosen, but it doesn't work as it should (this must happen because I can't dynamically modify the settings.py file). Any different approach to this problem? Thanks in advance -
Is space matter in Jinja?
What David has written in CS50 2022 - Lecture 9 - Flask, layout.html is {% block body %}{% endblock %} What I typically do in Django, a similar Python web framework is {% block body %} {% endblock %} Is space matter in Jinja? Is it a matter of style? Because I know HTML is also space insensitive. -
Trouble with custom column ordering in Django app using django_tables2, using calculated ForeignKey relationships
I'm trying to make ordering possible for one of my columns in a Django project using django_tables2. I'm getting a FieldError, Cannot resolve keyword 'job_code' into field. Choices are: PO_num_is_fixed, PO_number, amount, currency, description, id, invoice_status, job, job_id, notes, vendor, vendor_id I'm trying to sum all of the Cost objects that pertain to each job so I can sort them. I don't totally understand how F() works, so I have the feeling that's where I'm going wrong. Would love some feedback on how I can get this to work/improve on what I have. tables.py: import django_tables2 as tables from .models import Job, Cost from django.utils.html import format_html from django.db.models import F class JobTable(tables.Table): class Meta: model = Job template_name = "django_tables2/bootstrap5.html" fields = ("client", "job_name", "job_code", "budget", "total_cost", "profit_rate", "job_type", "job_date") # Doesn't work, cannot resolve keyword 'job_code' into field. def order_total_cost(self, queryset, is_descending): queryset = queryset.annotate( total_cost = sum([cost.amount for cost in Cost.objects.filter(job__job_code = F("job_code"))]) ).order_by(("-" if is_descending else "") + "total_cost") return (queryset, True) models.py Cost class: class Cost(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name='cost_rel') description = models.CharField(max_length=30, blank=True) amount = models.IntegerField(default=0, blank=True) currency = models.CharField(max_length=10, default='JPY ¥', choices=( ('¥','JPY ¥'), ('US$','USD $'), ('CA$','CAD $'), ('AU$','AUD $'), ('€','EUR €'), … -
How do I solve the issue where my django primary key (id) is null?
I am expecting that the primary key (id) to be inserted automatically E.g. 1 However, when I run my server, it is reflected as null instead. I have tried deleting the migration and previous records in the database, but it still reflects a null value in new entries. null_id In my settings.py file, I have the following option on default DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' I have the following Camera model class Camera(models.Model): status = models.BooleanField(default=True) location = models.CharField(max_length=2) liveURL = models.URLField(max_length=200) I created the Camera Object and save it using the django shell (python manage.py shell) test = Camera(status=False,location='b1',liveURL='http://test.com') I am using Django version 4.1.5 -
Ask for more information depending on a the input of the user on a from - Django ModelForms
To elaborate a little bit more Ill explain exactly what I want to do. So I have a database of employees, the issue is that some employees are under the age of 18, and when they are under that age I should ask some extra information. You can take a look into my code that I ask for the Date of birth (variable name is fecha_de_nacimiento which is the spanish for date of birth) of the employee you are registering. So my Idea is to make my program to understand the age of the entry, then see if its over 18, if not, then ask for some other details. If this is not clear enough, feel free to ask questions. BTW I am new in python and django, so if you notice something that I can do better, even if its not related to my question, feel free to let me know, feedback is well taken. models.py: from django.db import models from django.urls import reverse from django.utils import timezone from datetime import date class EmployeesInfo(models.Model): employee_number = models.AutoField(primary_key=True) nombre_completo = models.CharField(max_length=50) fecha_de_nacimiento = models.DateField(default = timezone.now) def get_age(self): age = date.today() - self.fecha_de_nacimiento return int((age).days/365.25) def get_absolute_url(self): return reverse("lista_empleados", kwargs={"pk": … -
listing the time from an api increase in plus 1
I have an error in listing an api that only use get and pull the normal database but at the time of listing increases me the date plus 1 and that in the database I register correct the api is normal and the same time zone q could it be? I have an error in listing an api that only use get and pull the normal database but at the time of listing increases me the date plus 1 and that in the database I register correct the api is normal and the same time zone q could it be? -
Server Error After Setting DEBUG=False Django
I keep getting Sever error- 500 after setting DEBUG=True both on localhost and the hosted version and I don't know the cause of the error. Here are some my code in my settings.py file import os from pathlib import Path from decouple import config import django_heroku import dj_database_url BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = str(os.getenv('SECRET_KEY')) DEBUG = config("DEBUG", default=False, cast=bool) ALLOWED_HOSTS = ["127.0.0.1", "localhost", "cv-build.onrender.com"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "cloudinary_storage", "cloudinary", 'app', ] MEDIA_URL = "/cv-build/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] STATIC_ROOT = os.path.join(BASE_DIR, "app/static") STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" DEFAULT_FILE_STORAGE = "cloudinary_storage.storage.MediaCloudinaryStorage" CLOUDINARY_STORAGE = { "CLOUD_NAME": config("CLOUDINARY_CLOUD_NAME"), "API_KEY": config("CLOUDINARY_API_KEY"), "API_SECRET": config("CLOUDINARY_API_SECRET"), } DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I've tried to sort it out by checking the Allowed Host, static settings and all but it is the same result. Thanks. -
django template: how to access form.fields[key] with dynamic keys?
Iam trying to access my form.fields in django template by using a dynamic key with two integers in its name. My goal is do render a checkbox matrix. Thats my form.py from django import forms class Mounting_Calc_Form(forms.Form): def __init__(self, rows, columns, *args, **kwargs): super().__init__(*args, **kwargs) self.rows = range(rows) self.columns = range(columns) for i in range(rows): for j in range(columns): self.fields['checkbox_{}_{}'.format(i, j)] = forms.BooleanField(required=False, widget=forms.CheckboxInput, label=str(i)+","+str(j)) print(type(self.fields)) print(self.fields) thats my template {% extends "admin/base.html" %} {% block content %} <form method="post"> {{ form.as_p }} {% csrf_token %} <table> {% for i in form.rows %} <tr> {% for j in form.columns %} <td>{{ form.fields[checkbox_{{ i }}_[{ j }}].widget }}</td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Submit"> </form> {% endblock content %} Thats the error i get: Could not parse the remainder: '[checkbox_{{ i' from 'form.fields[checkbox_{{ i' What iam doing wrong? -
Django app on Cloud Run infinite redirects (301)
I am trying to deploy a Django app in a container to Cloud Run. I have it running well locally using Docker. However, when I deploy it to Cloud Run, I get infinite 301 redirects. The Cloud Run logs do not seem to show any meaningful info about why that happens. Below is my Dockerfile that I use for deployment: # Pull base image FROM python:3.9.0 # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY requirements.txt requirements.txt RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home django-user # Copy project COPY . /code USER django-user # Run server CMD exec gunicorn -b :$PORT my_app.wsgi:application I store all the sensitive info in Secrets Manager, and the connection to it seems to work fine (I know because I had an issue with it and now I fixed that). Could you suggest what I might have done wrong, or where can I look for hints as to why the redirects happen? Thank you! -
Forbidden (CSRF cookie not set.)
I am creating an app in Django, and I am getting this error: Forbidden (CSRF cookie not set.) I am using Elastic Beanstalk to host my website, and everything was fine until it started doing this. My settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'i1kf*^g1+dt*8n9bgcl80$d!970186x(x(9z2)7dfy1ynlxixn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['travelApp-kool4-env.eba-pfvej56m.us-west-2.elasticbeanstalk.com', "52.27.98.222", "35.166.8.118", "127.0.0.1",] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'crispy_forms', 'django.contrib.staticfiles', 'sights.apps.SightsConfig', 'itineraries.apps.ItinerariesConfig', ] 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', ] ROOT_URLCONF = 'travelApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'static')], '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', ], }, }, ] TEMPLATE_DIRS = ( '/home/django/myproject/templates', ) WSGI_APPLICATION = 'travelApp.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, … -
Why is my web service trying to redirect to a url that does not exist?
Basically, I have a web service that I am trying to build using Django. While working on the user LogIn, I ran into a confusing error. If the user is None (in my code, this means that the password or username does not match an existing one), then the user should be redirected to the LogIn page again, wich has a url path of /accounts/login, however, is instead sent to /accounts/login/login This is the code that controls the user LogIn def logIn(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if username is not None: auth.login(request, user) return redirect('/') else: return redirect('/accounts/register/') else: return render(request, 'logIn.html') This is the urls file inside the app from django.urls import path from . import views urlpatterns = [ path('', views.Empty), path('register/', views.register), path('login/', views.logIn) ] and this is the main urls file in the project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('ControlApp.urls')), path('accounts/', include('Accounts.urls')) ] Here's the full code in case it helps I tried changing removing completely the redirect instruction from the logIn function, however, evenm then the user was getting redirected to /accounts/login/login I assume there … -
Django template with forloop. Exception Type: IndexErrorm, Exception Value: pop from empty list
I have a web page with essays. Each essay (on its own sub-page) can have multiple videos from another model (linked with many-to-many relations). When I had - in the past - one video in a subpage with a particular essay (with a different column related to the video, in the same model: 'one-to-many model', now hashed in my models.py) then I used to be able to invoke the video in my essay page with: <p>{% video essay_videos.video.video_item_url %}</p> But now when I try to invoke a list of videos, with this code: <ul> {% for vid in essay_videos %} <li>{{ vid.video_item_url }}</li> {% endfor %} </ul> I'm getting a list of URLs - that's ok, but, when I try to use the embed-video tag (like before): <ul> {% for vid in essay_videos %} <li>{% video %}{{ vid.video_item_url }}{% endvideo %}</li> {% endfor %} </ul> or <ul> {% for vid in essay_videos %} {% video %} <li>{{ vid.video_item_url }}</li> {% endvideo %} {% endfor %} </ul> or <ul> {% video %} {% for vid in essay_videos %} <li>{{ vid.video_item_url }}</li> {% endfor %} {% endvideo %} </ul> ...In all cases, I've got Exception Type: IndexErrorm, Exception Value: pop from empty … -
django-money object not limiting decimal fields
I'm using django-money for all currency fields in an app I'm building. According to the documentation the default CURRENCY_DECIMAL_PLACES is 2, and I am explicitly calling it in my settings.py file as well. However, when I am checking a remaining balance on an order it is returning a Money object, but showing all the decimal places instead of just 2. In [2]: order.remaining_balance Out[2]: Money('0.002500000000', 'USD') Is there a reason it isn't restricting it to only the 2 decimal places that I am wanting? In the templates it is only showing two decimal places, but in my views.py file or the shell it renders the full decimal places. I've set the CURRENCY_DECIMAL_PLACES to 2, but I'm getting back more than 2 decimal places. -
Django admin open modal and create inlineobects
I would like to add a button in my admin change_view (of orders) to open a modal or and other page with a form. After submitting the form i want to create some inline objects (articles). Whats the best way to achieve this? I tried using admin_extra_buttons but i didnt figured out how to open a template and go back after submitting the data to create the inline objects. -
Error downloading file using Vue.js and Blob in frontend
I am using Vue.js in my frontend and facing an issue while downloading a CSV file from my API endpoint (Django backend) using the following endpoint and code. The error in the console says "Error while downloading file: Unknown Error". Can someone please help me resolve this issue? I'm using downloadData method to handle the download and DataRepository.ts to retrieve the data from the API. The endpoint GET /api/mydata/data_export/ returns a Content-Type header of text/csv and a Content-Disposition header of attachment; filename="data_export.csv" when the request is successful. @action(detail=False, methods=["get"]) def data_export(self, request, pk=None): feedbacks = self.get_queryset().filter(type=DataType.FEEDBACKPROPOSAL) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="data_export.csv"' response["Access-Control-Allow-Origin"] = "*" writer = csv.writer(response) writer.writerow(["Question", "Answers", "Status", "Comment", "Email", "Phonenumber", "Proposed by"]) for feedback in feedbacks: writer.writerow( [ feedback.content, ";".join(feedback._question_answers), feedback.status, feedback.comment, feedback.email, feedback.phone_number, # feedback.proposed_by if not feedback.is_anonymous else "", ] ) return response Here's my code for the downloadData method: const downloadData = async () => { try { const repository = RepositoryFactory.get(DataRepository) const response = await repository.DataExport() if (response.status === 200) { const content = await response.text() const blob = new Blob([content], { type: 'text/csv' }) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.setAttribute('download', 'data_export.csv') document.body.appendChild(link) link.click() } … -
Django Websocket is not sending instant within group
I have a websocket that should send messages very x seconds. I am connecting to the socket from two clients. THe socket should send the message to both when one of them sends a start message but only the one which doesnt started is getting the message every x seconds. The one which send is getting all messages after all the time passed This is the loop. The normal send is getting send instant to one that initialized the send (i used this for now as a half fix). My problem is that the send to the group is not send every x second as it should. Only the other connected client are getting it every seconds. The starting person is getting them all at once after the time passed async def init_starting(self): if not self.lobby.status == "waiting": print("Already Started") return False else: print("Starting Countdown") #self.lobby.status = 'starting' #await self.save_lobby() await self.send_status_message_with_status(status='starting', data={'has_started': self.lobby.has_started, 'host': self.host.username, 'players': self.players, 'lobby_code': self.lobby_code, 'countdown': 3}) countdown = 3 while countdown >= 0: countdown_data = { 'countdown': countdown } await self.send(json.dumps({"type": "msg", "message": countdown})) await self.send_status_message_with_status(status='starting', data=countdown_data) print(countdown) countdown -= 1 await asyncio.sleep(1) await self.send_status_message_with_status(status='started', data={ 'message': "Test" }) return True async def send_status_message_with_status(self, … -
Django Allauth Email Verification ( not effective after signup ) .. works after first login
I'm using allauth in my Django project and it's configured as below to use email for authentication. allauth configuration* ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_PASSWORD_MIN_LENGTH = 8 ACCOUNT_EMAIL_VERIFICATION = 'mandatory' SOCIALACCOUNT_EMAIL_REQUIRED = True Problem is : after signup, i'm directed to Home page without confirming email. if it tried to logout and login again, it directs me to (accounts/confirm-email/) and is now required to confirm my email. Note user is overridden *(settings.py)* AUTH_USER_MODEL = 'home.User'` *(models.py)* `class User(AbstractUser): photo = models.ImageField(upload_to='user/', blank=True, null=True) address = models.CharField(max_length=50, null=True, blank=True) date_of_birth = models.DateField(blank=True, null=True) phone = models.CharField(max_length=20) email = models.EmailField(unique=True) i think after signup the user shouldn't be able to login before confirming his email. -
DJStripe create subscription for user after logging in
When a user signs up for the service, a stripe subscription should be automatically created when the user logs in. To achieve this, I added the following code snippet to my middleware. stripe_customer, _ = Customer.get_or_create(subscriber=user) user.update_stripe_customer(update_name=True) subscription = stripe.Subscription.create( customer=stripe_customer.id, items=[{"price": "price_id"}], metadata={ "user_id": user.id, "product_type": "type1", }, trial_period_days=trial_period_days, cancel_at_period_end=True, currency="eur", ) # Option 1 Subscription._get_or_retrieve(subscription.id) # Option 2 Subscription.sync_from_stripe_data(subscription) Both options work locally, also another option using djstripe. In the moment, I deploy my app to the staging enviroment, the subscription is being created but not saved into the database. As the staging enviroment uses transactions, I also tried to call the signup action after the transaction has been finished but the problems continues. What happens, stripe is being called, a customer and a subscription created but not saved into the database. -
Django static files not found in production 1.2
My code is working fine in the testing environment (DEBUG=TRUE) but when I switch to DEBUG=FALSE, static files are not being loaded. To run the application I follow: python3 manage.py collectstatic --no-input --clear python3 manage.py runserver settings.py: from pathlib import Path, 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.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-z$w^9$+no7vh2hbu#d6j7b3rx!+m=ombxy9=h%u&cr_=0v)ojv' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['.vercel.app', '.alisolanki.com', '.now.sh'] # Application definition INSTALLED_APPS = [ 'home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'sentiment_analysis.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'sentiment_analysis.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } # } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', … -
Django Form fields changing after page refresh
The first time I open this ModelAdmin's /add page, all the fields of the ServiceProvider model are displayed, although I specified with self.fields the fields that should be displayed. When pressing F5 to reload the page, the unsolicited fields do not appear. I suspected cache, but disabling the caches did not cause changes. The problem with loading all fields is that it also does some heavy querying related to those fields. class ServiceProviderAdmin(admin.ModelAdmin): ... def get_form(self, request, obj=None, **kwargs): self.fields = ( "name_registration", "name_social", "nome_usual", ("gender","document"), "department", "department_aditionals", "picture", "active", ) if request.user.has_perm("rh.can_edit_secondary_mail"): self.fields = self.fields + ("email_secondary",) self.form = ServiceProviderFormFactory(request.user) return super().get_form(request, obj=obj, **kwargs) def ServiceProviderFormFactory(user): class ServiceProviderForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ... class Meta: model = ServiceProvider exclude = ("",) -
How do I rectify this collectstatic error?
I am trying to run python manage.py collectstatic But I got the following error message: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\User\\Desktop\\PY4E\\djangoPorfolio\\static' Below are my settings.py STATIC_URL and STATIC_ROOT from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media') ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'mediafiles/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" Am I missing something?