Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django selecting a record if its Many-to-Many relation contains data
I have these 2 tables class Job(models.Model): name = models.CharField() collaborators = models.ManyToManyField(User, through="Collaborator") created_by = models.ForeignKey(User) class Collaborator(models.Model): job = models.ForeignKey(Job) user = models.ForeignKey(User, related_name="jobs") role = models.CharField() For a user, I want to select all those Jobs where either created_by=user or the user is in collaborators. The following query does not produce correct results Job.objects.filter(Q(created_by=user) | Q(collaborators=user)) Upon looking at the raw query generated by above code I have found out that this is because the query produced by django ORM creates a LEFT OUTER JOIN between Job and Collaborator, so if there are multiple Collaborators for the same Job then it returns multiple rows of the same job. What I have come up with is the following query Job.objects.filter(Q(created_by=user) | Q(pk__in=user.jobs.all().values("job_id"))) My question is, is there a better query than the above that I can use? P.S. I am using django 4.0 -
How to Merge Two Model Serialisers in Django Rest Framework
I want to merge the results of two models. I have two models as below. First is Product and the other is ProductChannelListing class Product(models.Model): name = models.CharField() category = models.ForeignKey() # has many other fields which I want in the response class ProductChannelListing(models.Model): product = models.ForeignKey() channel = models.ForeignKey() is_visible = models.BooleanField() price = models.IntegerField() I want the result in the following way. { "name": "ABC", "category": {}, "is_visible": true, "price": 200, ** } I want make the query efficient query such that it should not make so many queries. -
How to refer to a related object after deleting an object?
As in the title: How to refer to the related object after deleting the object? Simple example: ModelA(models.Model): ... ModelB(models.Model): model_a = models.ForeignKey("ModelA", on_delete=models.CASCADE) class TestView(APIView): def delete(self, request, pk): object_b = get_object_or_404(ModelB, pk=pk) object_a = object_b.model_a object_b.delete() It is now impossible to use object_a, this error pops up: 'NoneType' object has no attribute 'id' This approach does not work either: class TestView(APIView): def delete(self, request, pk): object_b = get_object_or_404(ModelB, pk=pk) object_a = ModelA.objects.get(id=object_b.object_a.id) object_b.delete() Related queryset can be used later with list(queryset), what about one object? -
How do I send a list of items from my UI to my Django Rest Framework API?
my project uses multithreading to work on several tasks simultaneously. I'd like my UI (I'm using Vue.js) to send a list/array of items to my API to work on each individual item task. ex. [{ "1": "item1", "2": "item2", "3": "item3", ...}] (API searches the items to find what commands to use, that's why I used multithreading so I can work on several tasks at once instead of sending each individual item which takes too long) How do I send a list or array of objects to the API? -
dj-rest-auth overriding reset password default email template not working
I wanna override the default email that gets sent to the user when he forgets his password here is the implementation: #urls.py path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path("password-reset/confirm/<uidb64>/<token>/",TemplateView.as_view( template_name="main/password_reset_confirm.html"),name='password_reset_confirm'), #serializers.py class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'html_email_template_name': 'custom_email_template.html', } def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(self.reset_form.errors) elif not User.objects.filter(email=value).exists(): raise serializers.ValidationError("A user with this email already exists!") return value # settings.py REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'main.serializers.UserSerializer', 'PASSWORD_RESET_SERIALIZER': 'main.serializers.CustomPasswordResetSerializer' } 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', ], }, }, ] I tried the solutions from many stackoverflow questions and github issues none of them was working Other than overriding the get_email_options method i tried overriding the save method like so: def save(self): request = self.context.get('request') opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'html_email_template_name': 'custom_email_template.html', 'request': request, } self.reset_form.save(**opts) and it did not work , i tried putting it under -templates -registration password_reset_email.html and it still did not work, while tried the above solutions i have it under templates custom_email_template.html -
Django - How to update a parent model using a child model?
I am sorry that I am not good at English. I have a two models something like this: Models.py class Parent(models.Model): id = models.BigAutoField(primary_key=True) quantity = models.DecimalField(max_digits=3, decimal_places=0, null=True) class Child(models.Model): parent = models.ForeignKey('Parent', related_name="parent_child", on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=3, decimal_places=0, null=True) If the parent quantity is different from the sum of the child quantities, Updates the parent quantity to the sum of the child quantities. I tried to get an object whose parent quantity is different from the sum of the child quantities: parent = Parents.objects.annotate(sum_quantities=Sum('parent_child__quantity')).exclude(quantity=F('sum_quantities')) It works! But I'm having trouble updating this. Is there a good way? Thanks a lot for your help! -
Django-allauth Cannot login
I created a login form with Django-allauth. But I can't login properly. I think my email address and password are correct. Is there a problem with the LOGIN_REDIRECT_URL? How can I log in? settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'app', 'accounts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] 、、、、、、、、、、、、、、、、、 # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' SITE_ID = 1 LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_REDIRECT_URL = '/' ACCOUNT_EMAIL_VERIFICATION = 'none' AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_AUTHENTICATION_EMAIL = 'email' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIl_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False mysite/urls.py from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('accouts/', include('accounts.urls')), path('accouts/', include('allauth.urls')), ] -
Django Dynamically fetch table name at runtime
I used django's inspectdb function to import an existing database as django models. The output is below The tables are dynamically created by an external program, partitioned by month or week (depending on the data model, these ones are month). What I want, is to have the single django model, but be able to change the table it uses for them at runtime, so that I can set which table it pulls from. Am I able to do something like set a callback instead of a string to get the table name? def get_history_partition_name(timestamp): return 'formatted_table_name_from_timestamp' class SqltData1202211(models.Model): tagid = models.IntegerField(primary_key=True) intvalue = models.BigIntegerField(blank=True, null=True) floatvalue = models.FloatField(blank=True, null=True) stringvalue = models.CharField(max_length=255, blank=True, null=True) datevalue = models.DateTimeField(blank=True, null=True) dataintegrity = models.IntegerField(blank=True, null=True) t_stamp = models.BigIntegerField() class Meta: managed = False #db_table = 'sqlt_data_1_2022_11' db_table = get_history_partition_name # Example of a callback instead of a string unique_together = (('tagid', 't_stamp'),) class SqltData1202302(models.Model): tagid = models.IntegerField(primary_key=True) intvalue = models.BigIntegerField(blank=True, null=True) floatvalue = models.FloatField(blank=True, null=True) stringvalue = models.CharField(max_length=255, blank=True, null=True) datevalue = models.DateTimeField(blank=True, null=True) dataintegrity = models.IntegerField(blank=True, null=True) t_stamp = models.BigIntegerField() class Meta: managed = False db_table = 'sqlt_data_1_2023_02' unique_together = (('tagid', 't_stamp'),) -
Display language icons in Django template
I want to display language icons instead of names in Django template. My code looks like this: {% load static i18n %} {% get_current_language as CURRENT_LANGUAGE %} {% get_available_languages as AVAILABLE_LANGUAGES %} {% get_language_info_list for AVAILABLE_LANGUAGES as languages %} <div id="language"> {% for language in languages %} <ul> <li> <a href="/{{ language.code }}/" {% if language.code == LANGUAGE_CODE %} class="active"{% endif %}> {{ language.name|slice:":3" }} </a> </li> </ul> {% endfor %} </div> Is there any possible ways to achieve that goal or I have to try different ways? -
Django form with m2m relationship not saving
I have a form where I want request.user to populate as little as possible and rely on the views to populate other fields automatically. As a result, some of these fields are not rendered on the form. The code in my view seems to work fine for the FK relationship, but some reason the m2m is failing. It's probably the first time I am trying to save a form with m2m and I am probably missing something. At the moment the error I get with the current code is 'VoucherForm' object has no attribute 'user'. This is because the user field is not present in form.py, as I want to handle it directly with the view. If I remove voucherform.user.add(userprofile)from the views the form will save, but will not add the user. model class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) class Voucher(models.Model): user = models.ManyToManyField(User, blank=True) venue = models.ForeignKey(Venue, blank=True, null=True, related_name="vouchervenues", on_delete=models.CASCADE) title = models.TextField('voucher title', blank=True) terms = models.TextField('terms & conditions', blank=True) form class VoucherForm(ModelForm): class Meta: model = Voucher fields = ('title','terms') labels ={ 'title': '', 'terms': '', } widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter title'}), 'terms': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter terms'}), } views def add_voucher(request, userprofile_id): url = … -
No module named '_mysql_connector' using Django and mysql-connector-python 8.0.32
I have a Django 4.1 website that was running fine in a Docker container with MariaDB 10.5. I updated only the mysql-connector-python module from 8.0.29 to 8.0.32 but now when I start up the web container that runs Django's dev server I get: myproject_web | Traceback (most recent call last): myproject_web | File "/root/.local/share/virtualenvs/code-_Py8Si6I/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 64, in <module> myproject_web | import _mysql_connector myproject_web | ModuleNotFoundError: No module named '_mysql_connector' myproject_web | myproject_web | The above exception was the direct cause of the following exception: myproject_web | myproject_web | Traceback (most recent call last): myproject_web | File "/root/.local/share/virtualenvs/code-_Py8Si6I/lib/python3.8/site-packages/mysql/connector/django/base.py", line 60, in <module> myproject_web | from mysql.connector.connection_cext import CMySQLConnection myproject_web | File "/root/.local/share/virtualenvs/code-_Py8Si6I/lib/python3.8/site-packages/mysql/connector/connection_cext.py", line 81, in <module> myproject_web | raise ImportError( myproject_web | ImportError: MySQL Connector/Python C Extension not available (No module named '_mysql_connector') myproject_web | myproject_web | The above exception was the direct cause of the following exception: ... I'm not sure where the fault lies, having a sketchy understanding of database servers and their connectors etc. If I downgrade mysql-connector-python to 8.0.29 then it works again (I can't use 8.0.30 or 8.0.31 because of a utf8 issue that I'm hoping is fixed in 8.0.32). Here is its changelog. My docker-compose.yml … -
Django can't recognize 0,1,2 precisely in url
my_app/views.py from django.http import HttpResponse,HttpResponseRedirect articles = { 'index' : "Hello this is a view inside my_app", 'simple' : 'simple views', 'sports' : 'Sports Page', 'finance' : 'Finance Page', 'politics' : "Politics Page" } def news_view(request, topic) : try : return HttpResponse(articles[topic]) except: raise Http404("404 GENERIC ERROR") def num_page_view(request,num): topics_list = list(articles.keys()) topic = topics_list[num] return HttpResponseRedirect(topic) my_app/urls.py from django.urls import path from . import views urlpatterns = [ path('<int:num>',views.num_page_view), path('<str:topic>/',views.news_view), ] when i type /my_app/0, django automatically change 0 0/, so i think Django can't recognize that this page's parameter is pure int. It continues until I type 0,1,2 But when i type more than 2 (ex. /my_app/3), it works as i intended (1. enter /my_app/3 2. redirect to /my_app/finance/) I don't know why Django do recognize the int parameter more than 2 but not 0,1,2. Expected enter /my_app/0 redirect to /my_app/index/ But... enter my_app/0 url is automatically changed to my_app/0/ can't redirect to the page so i got an error -
Adding Checkbox For Each Row to Select Rows Without Adding Any Actions in Django Admin Model Page
Problem image I want to add checkboxes for each row like action checkboxes to post selected rows to a view with my custom buttons. If I do it like this with adding a pointless action, it behaves like I am doing an action and it redirects to the same page with an error "no action selected". Before I press the button and post changelist-form After I press the button I want to select specific rows especially all rows without adding an action to my ModelAdmin or without changing my Model. How can I achieve that? -
Best and most convenient web app hosting for django, AWS or Azure [closed]
I have been working on python development and using the django framework for a while now. I have a few projects that i'd like to launch online, and some web app i'd like to host and have accessible by other users. I just want to know, which would be the easiest, convenient, and most affordable way to achieving this using a cloud-based service? AWS or Azure? Please provide some guidance on which platform would be the most preferred. Thank you. -
Python 3.8, 3.9 or 3.10 with Django 4.1. Target WSGI script '...wsgi.py' cannot be loaded as Python module
I have log error?: [Wed Feb 01 11:55:43.648533 2023] [mpm_prefork:notice] [pid 8463] AH00163: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 OpenSSL/1.1.1 configured -- resuming normal operations [Wed Feb 01 11:55:43.648562 2023] [core:notice] [pid 8463] AH00094: Command line: '/usr/sbin/apache2' [Wed Feb 01 11:55:49.491748 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] mod_wsgi (pid=8464): Target WSGI script '/var/www/calangolavadoestudio/calangolavadoestudio/wsgi.py' cannot be loaded as Python module. [Wed Feb 01 11:55:49.491815 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] mod_wsgi (pid=8464): Exception occurred processing WSGI script '/var/www/calangolavadoestudio/calangolavadoestudio/wsgi.py'. [Wed Feb 01 11:55:49.492211 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] Traceback (most recent call last): [Wed Feb 01 11:55:49.492241 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] File "/var/www/calangolavadoestudio/calangolavadoestudio/wsgi.py", line 29, in <module> [Wed Feb 01 11:55:49.492247 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] from django.core.wsgi import get_wsgi_application [Wed Feb 01 11:55:49.492254 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] File "/home/envs/calango/lib/python3.8/site-packages/django/__init__.py", line 1, in <module> [Wed Feb 01 11:55:49.492259 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] from django.utils.version import get_version [Wed Feb 01 11:55:49.492265 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] File "/home/envs/calango/lib/python3.8/site-packages/django/utils/version.py", line 7, in <module> [Wed Feb 01 11:55:49.492270 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] from django.utils.regex_helper import _lazy_re_compile [Wed Feb 01 11:55:49.492276 2023] [wsgi:error] [pid 8464] [remote 131.72.97.18:9123] File "/home/envs/calango/lib/python3.8/site-packages/django/utils/regex_helper.py", line 10, in <module> [Wed Feb 01 11:55:49.492281 … -
Date Parsing problem while Integrating to Oracle PMS
I'm recieving date in PMS message something like this |GA090616|GD090617| which means Guest Arrival is at 09-06-16 and Guest Deprature is at 09-06-17 I wanted to parse it as date using python. I've also visited stack oveflow[1, 2 ...] for this but as solution I've found from datetime import datetime self.DATE_FROMAT='%d/%m/%y' arrival_date=datetime.strptime('90616', self.DATE_FROMAT).date() print(arrival_date) and it's not possible to parse it like this due to it's not in clear format. not able find out 09 is month or date as far I got from docs and pdfs it seems month. is there any better solution for this kind of date parsing? or suggestion for my expectation. { guest_arrival: 09-06-16, guest_deprature: 09-06-17 } -
How do I get a variable value from javascript function to python function in django
I am trying to scan QR code using html,javascript as shown below by nurse_home.html. I am able to scan and see the content of the QR code on the website but I can't POST and write it into my database shown on views_nurse.py. Any help is greatly appreciated! <nurse_home.html> {% load static %} {% block mainbody %} <title>Django Online Barcode Reader</title> <meta charset="utf-8"> {% csrf_token %} <script src={% static "js/html5-qrcode.min.js" %}></script> <style> .result{ background-color: green; color:#fff; padding:20px; } .row{ display:flex; } </style> {% csrf_token %} <div class="row"> <div class="col"> <div style="width:500px;" id="reader"></div> </div> <div class="col" style="padding:30px;"> <h4>Scanned Result</h4> <!--<div id="result" name="result">Result Here</div>--> <output type="POST" id="result" name="result" placeholder="qrCodeMessage"> {% csrf_token %} </div> </div> <script type="text/javascript"> function onScanSuccess(qrCodeMessage) { document.getElementById('result').innerHTML = '<span class="result">'+qrCodeMessage+'</span>'; } function onScanError(errorMessage) { //handle scan error } var html5QrcodeScanner = new Html5QrcodeScanner( "reader", { fps: 10, qrbox: 250 }); html5QrcodeScanner.render(onScanSuccess, onScanError); </script> {% endblock %} <views.py> def nurse_home(request): return render(request, 'nurse_home.html') <views_nurse.py> @api_view(['GET',"POST"]) # Nurse scans QR def nurse_qrscan(request): ### Test! nurse: QR if request.method == 'POST': result = request.POST.get("result") # Saving the result to database, nurse_QR qr_output = nurse_QR(output=result) qr_output.save() return Action.success("Successful") <urls.py> from hospital import view_nurse from . import views urlpatterns = [ # Main Page … -
How to change colors of ChoiceFields options within the drop down menu when mouse is over
The form uses crispy forms which implements bootstrap. I tried using '!important' and specifics the widget of choicefield to have an attribute of a class which I can reference in my stylesheet: <form id="gene_form" action ="http://127.0.0.1:8000/checkqueries/", method="get", novalidate> {{ gene_form|crispy }} my forms.py: select_cancer = forms.ChoiceField(label = 'Cancer', choices = ExtractCancer(), required=False, widget=forms.Select(attrs={'class':'boostrap-select'})) my css .boostrap-select { background-color: black; color: white; } select option { background-color: blue; color: white; } .boostrap select changes the color of the box but not of the options dropdown menu. How can I change this to be able to allow the user to hover over an option in the drop down and then my own css colors will take over? I have tried referencing the class in the css and this works for the box but not for the options. I have also tried changing the css for any select option html found in the page but this hasn't worked either. I am using Django framework if that makes a difference -
How to do bulk delete using S3Boto3Storage? without using standard boto3 client
Hi i am using S3Boto3Storage and it works fine when i loop the objects and delete them one by one as below, @receiver(pre_delete, sender=TicketModel) def pre_delete_another_model(sender, instance, **kwargs): print("inside signals................") documents = MyDocuments.objects.filter(ticket=instance) for document in documents: document.document.delete(save=False) documents.delete() But in above example it is deleting one by one file by calling the s3 api's and it is taking some time, and here the actual model ie TicketModel is being called for bulk delete and in that case all its relevant files has to be removed from s3 and there are many files hence taking lot of time to delete and http request gets timed out if the files are more than 100. So is there any way to do bulk delete using S3Boto3Storage? so that i can call that in one go. I know there bulk delete is supported in normal boto3 s3 client but is there any possibility to use S3Boto3Storage to use bulk delete? -
My Django endpoints are not allowing Frotnend to access the data
So I'm totally lost. Hobby coder. I am making a web-app where I have got Django dealing with my backend, and react on the frontend. The Django server runs on localhost:8000 and the forntend on localhost:3000. On login, the user is forwarded to the homepage which immediatley requests data from the django rest api to poulate some data on the homepage. SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_DOMAIN = '.localhost' SESSION_COOKIE_PATH = "/" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', 'uauth', 'corsheaders', ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'backend' / 'templates', BASE_DIR / 'uauth' / '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 = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/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', }, ] # Internationalization # … -
How to import lodash in a typescript library package?
I'd like to centralize my generic most-used (typescript) functions in a Util package which I can reuse across my projects. Turned out more difficult than expected. This package is not going to be published, so I'm really only interested in ESM. I was able to do this as a plain js-package, but now that I'm converting it to TS, I'm running into problems. My question is, how to import from an external package? I use various Lodash functions. But Rollup complains that they don't exist, and/or have to be exported as well. I've included the first function that I was putting into this lib, I'm very new to TS, so don't mind that too much. ;-) [!] RollupError: "now" is not exported by "../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/lodash.js", imported by "out-tsc/src/createUid.js". https://rollupjs.org/troubleshooting/#error-name-is-not-exported-by-module out-tsc/src/createUid.js (1:9) 1: import { now, random, padStart } from "lodash"; ^ This my latests setup, going through many many variations: Config package.json { "name": "@vexna/util", "version": "1.0.0", "description": "Generic utilities, uses lodash", "private": true, "type": "module", "main": "dist/index.js", "types": "dist/index.d.ts", "sideEffects": false, "scripts": { "build": "rimraf dist && tsc && rollup -c rollup.config.js", "test": "node test/spec", "pretest": "npm run build" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.20.12", … -
530, b'5.7.0 Authentication Required Error when using gmail to send emails through django
Im having problems with sending emails through gmail in Django. I have set up a app password and yet I cant seem to send emails through Django. My settings.py look like this EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend EMAIL_HOST = 'smtp.gmail.com' EMAIL_FROM_USER = 'ianis.donica@gmail.com' EMAIL_HOST_PASSWORD = 'my app password' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False To my best of knowledge it isn't a gmail specific issue, as I had experienced the same problems across yahoo mail and Sendgrid, the function that's responsible for sending the email looks like this def send_activation_email(user, request): current_site = get_current_site(request) email_subject = "Activation Email" context = {"user": user, "domain": current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) } email_body = render_to_string('email/activate.html',context) email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.send() and the full error message is this SMTPSenderRefused at /register/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError g9-20020a170906394900b00872a726783dsm9975622eje.217 - gsmtp', 'ianis.donica@gmail.com') What I tried was changing to yahoo and SendGrid mail but the same issues occurred there, just with different names. I also tried changing some details but that shouldn't be the problem? Yet I cant seem to send an email anywhere. If anyone can help me I would really appreciate it I also have IMAP enabled -
Can Django's URL tag show the URL of the RedirectView
Let's say that in my urls.py I have a url like this: path("support/", RedirectView.as_view(url="http://www.example.com"), name="support"), And in one of my templates I use the url tag: {% url "support" %} This of course renders /support/ as expected. But what if I want it to render http://www.example.com instead? Is that at all possible? Skip the redirect basically. -
any I'm trying to update a booleanfield from another model. i have 2 model studentcourse and Examgrade 'RelatedManager' object has no attribute 'show'
I have 2 models which are StudentCourses and ExamGrade, below are the models and attribute important which i would like to update on StudentCourses when ExamGrade is created models.py class StudentCourses(models.Model): id = models.AutoField(primary_key=True) student = models.ForeignKey(Students, related_name='studentcourses') studentcourse = models.ForeignKey(Courses, related_name='studentcourses', null=True) show = models.BooleanField(default=False) class ExamGrade(models.Model): id = models.AutoField(primary_key=True) lecturer = models.ForeignKey(Lecturers, null=True, related_name='examgrades') student = models.ForeignKey(Students, related_name='examgrades') from the model above the student are related to both StudentCourse and ExamGrade i would like to update the show attribute to True on StudentCourses and in my views i have this code below Views.py examgrades = ExamGrade(lecturer=lecturer, student=student) examgrades.student.studentcourses.show = True examgrades.save() and this was my error 'RelatedManager' object has no attribute 'show' -
Is there a way to make date fields timezone unaware when querying a Django model to save in Excel file?
I'm querying my model like this: info = Prorrogation.objects.using('test_database').exclude( contractDate__gte=date.today() ).filter( contractDate__gte=data ).order_by('companyName').values() Then I build a DataFrame using pandas and save a report in excel format, but I'm getting the error Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel., is there a way for me to make the date fields timezone unaware when I query the model?