Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check and alternate Docker Compose file: Debug flag not being set?
I'm trying to prep a Django application for production. I created an alternate docker-compose YML file where I specify DEBUG=0. However when I run the django check for deployment, it says that DEBUG is set to True. Any thoughts on where I'm going wrong? I thought it was an issue with my use of Docker. But is it perhaps an issue with how I'm using Django? Here are my steps: Created my project with docker-compose.yml (see below) Created docker-compose-prod.yml for production (see below) Ran the following $ docker-compose down $ docker-compose -f docker-compose-prod.yml up -d --build $ docker-compose exec web python manage.py check --deploy Output of the check: ?: (security.W018) You should not have DEBUG set to True in deployment. Some of investigatory steps so far: A. Check the environment variables. $ docker-compose exec web python >>> import os >>> os.environ.get('DEBUG') '0' B. Try rebuilding docker image in different ways, e.g. with --no-cache flag C. Set the DEBUG flag in settings.py in a conditional code block (rather than using os.environ.get). This seemed to work. But I don't understand why? Code detail below. Code excerpts Excerpt from docker-compose.yml services: web: ... environment: - ENVIRONMENT=development - SECRET_KEY=randomlongseriesofchars - DEBUG=1 Excerpt from docker-compose-prod.yml … -
CSS class changed but the style is taking time to get applied
I added a new class in the custom CSS file in a Django app and changed the HTML accordingly. The problem is that the class is getting applied to let's say a button but the page is not showing the changes. For example: Please check the below snippet <button type="button" class="btn btn-primary btn-lg">Text</button> I added a new class .btn-custom in custom.css and changed the HTML file as well. Now after the refresh, the above tag changed to <button type="button" class="btn btn-custom btn-lg">Text</button> But the style is not applied to the page. I check the custom CSS file by opening the source and the changes I made are there. After 2 to 3 hrs the changes getting reflected. I tried hard refresh as well cache clearing and every other option related to cache -
Display formatted excel output on HTML while running external python script
So i have this huge python script which combines multiple excel files and generates another 20 excel files with formatted pivot tables etc. Since i am going to handover this script to people with no python knowledge, i have created a django project which will enable the users to run this script with a click of a button on their web browser. As of now the output gets saved in multiple excel files. So what i actually want to do is display the output below the execute button on the same webpage as soon as the script is completed its execution. As of now the script displays output as follows: b' MRC ACT ... Variance_y %real_var\r\n0 INDONESIA 5263639608.007611 ... 9899814.618474 100.199738\r\n1 MALAYSIA 3577129.588221 ... 1251126.219085 108.868625\r\n2 PHILIPPINES 27816561.032899 ... -153405.655029 97.436131\r\n3 SINGAPORE 3653201.384013 ... 611488.423571 100.843299\r\n4 THAILAND 74495246.352116 ... 13710289.449428 101.175474\r\n5 VIETNAM 31212513.847313 ... -54368.594170 100.000000\r\n\r\n[6 rows x 9 columns]\r\n' This is the snippet of code i am using: views.py: def external(request): #inp=request.POST.get("param") out=run([sys.executable, 'C:\\Users\\rsm\\Downloads\\ABC\\abc.py'], shell=False, stdout=PIPE) print(out) return render(request,'home.html', {'data1':out.stdout}) home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Python Button Script</title> </head> <body> <br> <form action="/external/" method="post"> {% csrf_token%} {{data_external}}<br><br> {{data1}} <br><br> <input type="submit" value="Execute Script"> </form> </body> </html> … -
Django ORM Query , how to convert the query set to tuple of tuples
I'm trying to do this from query (('1','A'), ('2','B'), ....) to use it as choice field in my form, how to convert my query result to do this ? where 1,2 is the row id and A,B is another columns value many thanks -
Add existing API into django rest framework
Besides the API I created by using the django rest framework, now I want to add the existing commerial API into the backend, how to do this? The commerial API include several part(API), for example, /prepare, /upload, /merge,/get_result, etc. They all use the "POST" indeed. Do I need to call the commerial API directly on the frontend? Or I need to integrate the commerial API in to one backend API? Any suggestions are appreciated.Thanks. For example: ``` class TestView(APIView): """ Add all the commerial API here in order /prepare(POST) /upload(POST) /merge(POST) /get_result(POST) return Result """ ``` -
change mintime on flatpicker based on currentdate
I am using flatpickr to show the calender time.I want to set the minimum time with the variable,and on change of the date if the date is selected anyother date except today's date the minimum time should be changed. The minumtime is 13:00. so on the first click the minimum time will be 13:00.But if the user selects any other date other than today the minimum time should be chanegd.Please help in proceeding with this. let minimumtime = "13:00" let start_date = $vehicle_request_form.find("#id_start_date").flatpickr( { altInput: true, altFormat: "F j, Y H:i", enableTime: true, time_24hr: true, weekNumbers: true, minDate: "today", minTime: minimumtime, maxDate: new Date().fp_incr(730), locale: { firstDayOfWeek: 1 }, onChange: function (selectedDates, dateStr, instance) { var date = new Date(Date.parse($("#id_start_date").val())); date.setMinutes(date.getMinutes() + 1); newDate = Date.parse(date.toString()); end_date.set("minDate", newDate); end_date.setDate(newDate, true); start_date.set("minTime","16:00"); } }); -
How to Import wagtailvideo in wagtail
In Shell:- 1st try :- from wagtailvideos.models import AbstractVideo 2nd try :- from wagtail import wagtailvideos_video Nothing Works, I want to use it Directly on my Templates thats why i am importing it. and I want to add custom fields in wagtailvideo. What steps should I take to add custom fields. in wagtailvideo -
Assign image to ImageField WITHOUT saving (django)
my code: class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images', blank=True, null=True) source_url = models.URLField(blank=True,null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True) slug = models.SlugField(blank=True,null=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)[:50] if self.source_url and not self.image: result = urllib.request.urlretrieve(self.source_url) self.image = os.path.basename(self.source_url), File(open(result[0], 'rb')) if self.source_url: if '//' in self.source_url: d = self.source_url.split('//')[1].split('/')[0] else: d = self.source_url.split('/')[0] try: domain = Domain.objects.get(domain_url=d) except Exception as e: print(e) domain_object = Domain.objects.create(domain_url=d) domain = domain_object self.domain = domain return super(AttackImage, self).save(*args, **kwargs) error: Traceback (most recent call last): File "crawl_ebaumsworld.py", line 92, in <module> crawl(first_url) File "crawl_ebaumsworld.py", line 66, in crawl creator=mike File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "/home/michael/projects/deepsteg/engine/models.py", line 62, in save return super(AttackImage, self).save(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql for sql, params … -
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3
I followed this document and I’m hitting this error. Could you let me know what I’m missing? I tried several things the whole day and nothing has worked? I’m wondering whether these documented steps are tested well!? $ sudo systemctl status gunicorn.socket Failed to dump process list, ignoring: No such file or directory ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Sun 2019-12-15 05:15:27 UTC; 17s ago Listen: /home/xx/myproject/myapp/myapp.sock (Stream) CGroup: /system.slice/gunicorn.socket Dec 15 05:15:27 ubuntu-s-01 systemd[1]: Listening on gunicorn socket. $ sudo systemctl status gunicorn.service ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2019-12-15 04:22:54 UTC; 53min ago Main PID: 15788 (code=exited, status=1/FAILURE) Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: self.stop() Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: File "/home/xx/myproject/xxenv/lib/python3.6/site-packages/gunicorn/arbi Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: time.sleep(0.1) Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: File "/home/xx/myproject/xxkenv/lib/python3.6/site-packages/gunicorn/arbi Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: self.reap_workers() Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: File "/home/xx/myproject/xxenv/lib/python3.6/site-packages/gunicorn/arbi Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Dec 15 04:22:54 ubuntu-s-01 gunicorn[15788]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Dec 15 04:22:54 ubuntu-s-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 15 04:22:54 ubuntu-s-01 systemd[1]: gunicorn.service: Failed with … -
Android failing to connect to django backend
I can upload a picture manually from the admin panel of Django backend, but failing to connect from Android end. I have seen multiple solutions and have also tried String DJANGO_SITE = "https://10.0.2.2:8000/image/" within Django API, but failed to connect everytime. To run my Django backend, I have typed python3 manage.py runserver 192.168.43.55:8080. Here, 192.168.43.55 is the IP adress of my router. Here is my code of the uploadphoto() method in the android part private void uploadFoto(Bitmap bmp) { File imageFile = savebitmap(bmp); // converts bitmap to file Log.e("The file to be send is",imageFile+""); Retrofit retrofit = new Retrofit.Builder() .baseUrl(DjangoApi.DJANGO_SITE) .addConverterFactory(GsonConverterFactory.create()) .build(); Log.e("Django post API", retrofit+""); DjangoApi postApi= retrofit.create(DjangoApi.class); Log.e("Django post API", postApi+""); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/data"), imageFile); MultipartBody.Part multiPartBody = MultipartBody.Part .createFormData("model_pic", imageFile.getName(), requestBody); Call<RequestBody> call = postApi.uploadFile(multiPartBody); Log.e("The call is ",call+""); call.enqueue(new Callback<RequestBody>() { @Override public void onResponse(Call<RequestBody> call, Response<RequestBody> response) { Log.e("response", response+""); Log.d("good", "good"); } @Override public void onFailure(Call<RequestBody> call, Throwable t) { Log.e("response", t+""); Log.d("fail", "fail"); } }); } } Here is my code for the Django API part: public interface DjangoApi { String DJANGO_SITE = "https://192.168.20.106:8000/image/"; @Multipart @POST("upload/") Call<RequestBody> uploadFile(@Part MultipartBody.Part file); } Can anyone kindly help me regarding this? -
django-rest-framework custom user model login failed
I am using django custom usermodel with restframework , after registering successfully I am unable to login for normal users.I am able to login via the initial superuser but if I create new superuser ,they are registered successfully but gives error while logging in as when trying with a normal user. Error Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. For few profiles I also observed following error in admin panel. invalid password format or unknown hashing algorithm models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **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, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_time_onboarded=now, **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, True, True, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) return user class AppOnboarding(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) product_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=True) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_time_onboarded = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD … -
"Reverse for 'about' with no arguments not found. 1 pattern(s) tried: ['$about$'] Request Method:"
blog_project\mysite\blog\templates\blog\base.html, error at line 26 Line number 26 is About In App's URL file: # url(r'^about', views.AboutView.as_view(), name='about'), path('about',views.AboutView.as_view(), name='about'), Tried both with and without $ sign. And in views.py file class AboutView(TemplateView): template_name = 'about.html' -
Axes Backend Request Parameter Required django
i'm using axes in my customised view in order to block my ecommers costumers after 3 fail logs. i'm getting an error "Axes Backend Request Parameter Required" each time i try to log with any user. The error disappear if delete 'axes.backends.AxesBackend' from AUTHENTICATION_BACKENDS. I'll apreciate any help or sugestion. Thanks Error: AxesBackendRequestParameterRequired at /account/signin/ AxesBackend requires a request as an argument to authenticate AUTHENTICATION_BACKENDS = [ # AxesBackend should be the first backend in the AUTHENTICATION_ 'axes.backends.AxesBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'stripe', 'crispy_forms', 'axes', ] 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', #clickjacking protection # 'axes.middleware.FailedLoginMiddleware', 'axes.middleware.AxesMiddleware', Thanks -
Django: TypeError: Calling `.seed()` on instances is deprecated. Use the class method `Faker.seed()` instead
i tried to make virtual data using django_seed. when python version was 3.7, there was no error. however, after updating python to 3.8 version there are error. what this error means? -
AttributeError: 'tuple' object has no attribute '_committed'
Full traceback: Traceback (most recent call last): File "crawl_ebaumsworld.py", line 92, in <module> crawl(first_url) File "crawl_ebaumsworld.py", line 66, in crawl creator=mike File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "/home/michael/projects/deepsteg/engine/models.py", line 62, in save return super(AttackImage, self).save(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert using=using, raw=raw) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1334, in execute_sql for sql, params in self.as_sql(): File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in as_sql for obj in self.query.objs File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1278, in <listcomp> for obj in self.query.objs File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1277, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1228, in pre_save_val return field.pre_save(obj, add=True) File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/fields/files.py", line 286, in pre_save if file and not file._committed: AttributeError: 'tuple' object has no attribute '_committed' models.py class AttackImage(models.Model): title = models.CharField(max_length=255) image = models.ImageField(upload_to='attack_images', blank=True, null=True) source_url = models.URLField(blank=True,null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, … -
Django Defender Connection error at /admin/login
the las couple of days i have been trying to find the solution to my issue, i'm trying to use Defender to block access after some fail loggin access. I installed it, set the backends ,installed app, middleware, and views. i read and tried to find the solution but i didnt find anything. Any sugestion? SETTINGS CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'stripe', 'crispy_forms', 'defender', ] 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', 'defender.middleware.FailedLoginMiddleware', ] AXES_LOCK_OUT_AT_FAILURE = True AXES_USE_USER_AGENT = False # AXES_COOLOFF_TIME = 1 AXES_LOGIN_FAILURE_LIMIT = 2 #defender customizing DEFENDER_LOGIN_FAILURE_LIMIT = 2 DEFENDER_DISABLE_IP_LOCKOUT = True DEFENDER_USE_USER_AGENT = True DEFENDER_COOLOFF_TIME = 1 Thansk you so much, i will apreciate any help -
New Project in Django. Can't access admin
I am a beginner and have been practicing creating django projects with vscode. I created a new project and set up a superuser. I then ran the server. The development server was http://127.0.0.1:8000 as usual and the django page come up. I went to admin and the login page came up. I logged in as superuser and got the following error: This site can’t be reached 127.0.0.1 refused to connect. When I went back to vscode, the server was shut down. I thought it might be a problem with a firewall, but I have completely uninstalled my anti-virus and changed the settings on windows defender to allow VScode access through the firewall, but nothing works. I exited the project, deleted it and set up a new project. The same thing happened and it did not matter what browser I used. I have set up a dozen projects before and never had this problem. -
Template tag into column name
I'm trying to add filter field from django-filter to replace column name in django-tables2. Is there any way to do that? I tried: tables.Column(verbose_name="{{ filter.form.as_p }}") but it just interprets it as a text. Is there a way to put that there with use of those libraries? I use django_filters.ChoiceFilter as filter type. -
I'm facing a problem with redirecting in class-based success_url
I'm working with Django 2.2 and I'm facing a problem with redirecting in class-based success URL. enter code here - view.py class LetterFormView(CreateView): template_name = 'post.html' model = Letter form_class = LetterForm def get_success_url(self): return reverse ('mainapp:user-profile') and the url.py enter code here- urls.py path('profile/<username>/', views.UserProfilePage.as_view(), name='user-profile'), Now I'm not sure how to pass the username argument in here. -
Passwords are not hashed in Django as well as some missing columns
I'm not sure why my passwords are not hashed when creating a new user using Django Rest Framework This is what I see in postgres. Not sure why my admin/staff/active columns aren't showing up either even after migrating models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password=None, first_name=None, last_name=None, is_active=True, is_staff=False, is_admin=False): if not email or not first_name or not last_name: raise ValueError('Email is required') if not password: raise ValueError('Password is required') if not first_name: raise ValueError('First name is required') if not last_name: raise ValueError('Last name is required') user_object = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, active=is_active, staff=is_staff, admin=is_admin, ) user_object.set_password(password) # change password user_object.save(self._db) return user_object def create_staff_user(self, email, first_name, last_name, password=None): staff_user_object = self.create_user(email, first_name, last_name, password, is_staff=True) return staff_user_object def create_superuser(self, email, first_name, last_name, password=None): super_user_object = self.create_user(email, first_name, last_name, password, is_staff=True, is_admin=True) return super_user_object class User(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_joined = models.DateTimeField(auto_now_add=True) # joined timestamp is_active = models.BooleanField(default=True) # Can login? is_staff = models.BooleanField(default=False) # staff user, non super user is_admin = models.BooleanField(default=False) # super user? objects = UserManager() USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] # email and passwords are required … -
How to require authentication to all views using social-auth-app-django? (All views are showing to non authenticated users)
I'm using social-auth-app-django version 3.1.0, and the login using Google OAuth2 is apparently running fine (I can succeed to login and get redirected back, also the user data from login is saved correctly (username, email)) But all my routes/views are accessible without authentication, even with the SocialAuthExceptionMiddleware (It was suposed to block this kind of unauthorized access I guess). I just need all my current views (routes) to require authentication and redirect user to my login page. This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_jinja', 'bootstrapform_jinja', 'django_celery_results', 'social_django', 'apps' ] MIDDLEWARE = [ 'social_django.middleware.SocialAuthExceptionMiddleware', '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', 'wharf.auth.LoginRequiredMiddleware' ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'wharf.auth.SettingsBackend', 'django.contrib.auth.backends.ModelBackend' ] # Social Login Django SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.environ.get('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY', '') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.environ.get('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET', '') SOCIAL_AUTH_GOOGLE_OAUTH2_USE_UNIQUE_USER_ID = True SOCIAL_AUTH_STRATEGY = 'social_django.strategy.DjangoStrategy' SOCIAL_AUTH_STORAGE = 'social_django.models.DjangoStorage' LOGIN_REDIRECT_URL = "/" LOGIN_URL = "/" SESSION_COOKIE_SAMESITE = None LOGIN_EXEMPT_URLS = ["webhook", "favicon.ico", "status"] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) ROOT_URLCONF = 'wharf.urls' TEMPLATES = [ { 'BACKEND': 'django_jinja.backend.Jinja2', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], "match_extension": None, "app_dirname": "templates", }, }, … -
Efficient way of running Django query over list of dates
I am working on an investment app in Django which requires calculating portfolio balances and values over time. The database is currently set up this way: class Ledger(models.Model): asset = models.ForeignKey('Asset', ....) amount = models.FloatField(...) ... class HistoricalPrices(models.Model): asset = models.ForeignKey('Asset', ....) price = models.FloatField(...) date = models.DateTimeField(...) Users enter transactions in the Ledger, and I update prices through APIs. To calculate the balance for a day (note multiple Ledger entries for the same asset can happen on the same day): def balance_date(date): return Ledger.objects.filter(date__date__lte=date).values('asset').annotate(total_amount=Sum('amount')) Trying to then get values for every day between the date of the first Ledger entry and today becomes more challenging. Currently I am doing it this way - assuming a start_date and end_date that are datetime.date() and tr_dates a list on unique dates on which transactions did occur (to avoid calculating balances on days where nothing happened) : import pandas as pd idx = pd.date_range(start_date, end_date) main_df = pd.DataFrame(index=tr_dates) main_df['date_send'] = main_df.index main_df['balances'] = main_df['date_send'].apply(lambda x: balance_date(x)) main_df = main_df.sort_index() main_df.index = pd.DatetimeIndex(main_df.index) main_df = main_df.reindex(idx, method='ffill') This works but my issue is performance. It takes at least 150-200ms to run this, and then I need to get the prices for each date (all … -
Django Add Recaptcha V3 To Allauth Login
I was able to follow this answer to be able to implement Google Recaptcha V3 to my allauth sign up page. Now I would like to do the same thing for the allauth login page. I tried using the same method as the sign up page but did not have success. Here is what I tried doing replicating the answer above: https://dpaste.org/UXcD How does one go about doing this? If possible, I would like to keep the the default allauth functionality the same and would not like to override it. I would like to figure out how to do this on all allauth pages not just the signup and login pages. If there is one universal way to do it for all the allauth pages, that would be great. Otherwise I will ask separate stackoverflow questions on each one. -
How do I make a childless node have an input box that will post a number so it can call a python function?
As the question states, I need a childless node to act as input (pretty input preferably) so I can call a Python function and return a value. I would like it all to happen in javascript so it's seemless. Does anyone know how I can do that? It may involve doing something to the following- h = t.append("g").classed("body-group", !0); return h.append("image").classed("body-box", !0).attr("xlink:href", "{% static 'body box bg.png' %}").attr("width", 1e-6).attr("height", 1e-6) Here is the JSFiddle. Hopefully it helps you understand what I mean by childless node. -
Nginx not serving multiple uploaded images over about 200kb | Will serve when uploaded one at a time
I am new to nginx, and deployment in general. I've succesfully deployed a Python/django site that has a page with various "listings", and each listing has its own page with 20-30 images. When all the images are uploaded through the admin area for each listing, at only 200kb or so each, the images are not served and show blank on the front-facing website -- but when i upload between 1-6 at a time, they are served. So adding a few at a time and reloaded is the only way to upload all the images, and its a pain. I imagine this gives Nginx a chance to cache the few images before the next 1-6 images are uploaded -- so the solution could lie here somewhere. Below are my settings. I've sifted through other stack overflow questions and adjusted a few settings according to answers to other related questions ive found. Ive tried increasing the "client_max_body_size" to 20M, and have now set it to 0, so it will be disregarded - neither seem to fix the problem. Would greatly appreciate y'alls help in troubleshooting this. Thanks! http { client_max_body_size 0; proxy_max_temp_file_size 0; proxy_buffering off; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout …