Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to send dynamic html email to thousands of recipient with django without any third party service?
I want to send email to thousands of users as quick as possible. I just want to confirm that the way I'm trying is good enough or not. Please share what you think and whats the best way to do that. Thanks is advance. I'll really appreciate for response. here is my code snippet. from django.core.mail import send_mail, EmailMessage from django.template import loader def email_sender(email_object): subject = email_object["subject"] html_body = email_object["html_body"] from_email = email_object["from_email"] recipient_list = email_object["to_email"] if isinstance(recipient_list, str): recipient_list=[recipient_list] print("recipient_list :",recipient_list) html_message = loader.render_to_string(html_body,{}) mail = EmailMessage( subject=subject, body=html_message, from_email=from_email, to=recipient_list ) mail.content_subtype = "html" # Main content is now text/html mail.send() -
django - static image not showing up in template
I'm just trying to display a basic image that is stored in my static folder but nothing is showing up. I have ran collectstatic but nothing. Path: /static/logos/IMG_1793.jpg (That is what is shown when printing tenant.image.url) Settings.html: <img src="{{ imagePath }}" alt="{{ tenant.name }}"> I have also tried: src="{% static imagePath %}" Views.py def settingsPage(request): tenant = get_tenant(request) imagePath = tenant.image.url context = {'tenant': tenant, 'imagePath': imagePath} return render(request, 'setting/settings.html', context) -
Why django collectstatic is not finding my css
I am struggling with django static files. I want to link "screen.css" stored in "all_statics/css" folder to "index.html". Here is my html file : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="https://fonts.googleapis.com/css2?family=Gwendolyn:wght@700&display=swap" rel="stylesheet"> <link href="{% static '/css/screen.css' %}" rel="stylesheet" > </head> <body> <h1>Test</h1> </body> </html> In my settings.py, I have set these variables : STATIC_URL = 'static/' STATICFILES_DIR = [ BASE_DIR / 'all_statics', ] STATIC_ROOT = BASE_DIR / 'static' Here is my project structure : Project structure When I run python manage.py collectstatic , the static files from admin app is copied to static folder, but not the files from 'all_statics' . When I run python manage.py runserver and browse to the index page, I see that the css can't be found (404) : [18/Jan/2022 11:30:26] "GET / HTTP/1.1" 200 308 [18/Jan/2022 11:30:27] "GET /static/css/screen.css HTTP/1.1" 404 1801 When I run python .\manage.py findstatic css/screen.css I get : No matching file found for 'css/screen.css'. I have created a sample project to show my problem. You can clone it from https://github.com/doolieSoft/django_project.git . Do you have an idea why my css can't be found ? Thanks for your help ! -
Unable to save to model with JSONField
I've been at this problem for so long that I'm not even sure where I am with it. I've written the following management command which generates some JSON and saves it using a Django model. Later I have a view which retrieves this JSON and displays it in a URL. The model is as follows: from os import name from django.db import models # Create your models here. class Payload(models.Model): name = models.CharField(max_length=255) json = models.JSONField() The management command has this: nodes = .... # Various logic to generate a dictionary links = .... # Various logic to generate a dictionary payload = json.dumps({'nodes': nodes, 'links': links}) print(payload) obj = Payload.objects.filter(name='sankey').first() if obj: obj.json = payload result = obj.save() if result: print('Successfully updated payload') else: print('Could not update payload: '+str(result)) else: obj = Payload(name='sankey', json=payload) result = obj.save() if result: print('Saved new payload') else: print('Could not create new payload: '+str(result)) self.stdout.write(self.style.SUCCESS('Generatesankeypayload command executed.')) When I run the command I get: {"nodes": [{"name": "Jacks Account"}, {"name": "Books"}, {"name": "Coffee & Snacks"}, {"name": "Grooming"}, {"name": "Hobbies"}, {"name": "Personal Gear"}, {"name": "Public Transport"}, {"name": "Jacks Monzo"}, {"name": "Toys"}, {"name": "Janes Account"}, {"name": "Clothing"}, {"name": "Joint Account"}, {"name": "Basic food"}, {"name": "Council tax"}, {"name": … -
Django filtering aggregate query after aggregation
I've got a transaction model: class transaction(models.Model): transactiondate = models.DateField() details = models.CharField(max_length=200, null=True) amount = models.DecimalField(decimal_places=2, max_digits=10) accountid = models.ForeignKey(account, on_delete=models.PROTECT) I'm trying to get a running total balance for each date so that I can plot the last 12 months balance on a line chart. My query is: transaction.objects.annotate( balance=Window(Sum('amount'), order_by=F('transactiondate').asc())).filter(transactiondate__gte='2021-01-01') The problem is that this isn't including data prior to 2021-01-01 in the calculation. I want the Sum to include all transactions regardless of date but I only want to see 12 months in my chart. I thought that tagging on the filter after the aggregate would calculate the correct balance first and then apply the filter to only give me 12 months, but that's not what's happening. If I remove the filter then I get the correct balance, but my line chart is unreadable with so much data. Is there a way to filter the data after aggregation? -
link table column with name of file in statcic Django
Hi all i am new bee in django coding. I want display a link for pdf when i have my seach result. The name(title) in table (db) of document is the same of my existing pdf document in static/media. i have try some fuction but not work. template : search_actes.py {% if actes.tilte == static('media/"*".pdf') %} <a href="{% get_static_prefix %}static/media/.pdf">tests</a> {% else %} <p>not working</p> -
importing module is not being resolved in env:venv environment
Im following a course about Django and making an API. Im usinf visual code I have set up an env:venv environment. When i try to import rest_framework i get the message: "Import "rest_framework" could not be resolved - Pylance Even though the import is working and i can use the functionalities. Im using the python interpreter available in the ENV environment Python 3.10.1 64-bit ('env':venv) when i set the interpreter to the local python path the import is resolved. So that fixes the problem. But i want to use the interpreter for the ENV environment because i think it should work this way. If i am in my ENV environment and i query 'pip list' the module to be resolved is installed: (env) C:\DjangoProjects\amonmcduul>pip list Package Version asgiref 3.4.1 distlib 0.3.4 Django 4.0.1 djangorestframework 3.13.1 djangorestframework-simplejwt 5.0.0 I have also pip installed the djangorestframework on my local computer, hense it works when i set the interpreter to my local python interpreter. I dont know why the import wont resolve.. it says it isnt resolved but it does work though. How can i resolve the import? Or get rid of the message 'it can't be resolved' -
running django with lightsail without the terminal
I was able to view my django site in lightsail but using the port 8000 and also having to run the commandline. Is there a way to make this run live without my interaction? -
Django query resolver for a specific field (graphql)
I want to make a query that only displays variant_view_configuration field. How can I solve the problem? If I write like that, it gives me an error class User(AbstractUser): variant_view_configuration = ArrayField(models.CharField(max_length=200), default=list, blank=True) class UserQueries(object): user_variant_view_preference = graphene.Field(UserNode, id=graphene.ID(required=True)) def resolve_user_variant_view_preference(self, info, id): instance = Node.get_node_from_global_id(info, id, only_type=UserNode) if not instance: raise ApplicationError.general.not_found(id) return User.objects.get(pk=instance.id).variant_view_configuration The GraphQL query: QUERY = """ query Test($id: ID!) { userVariantViewPreference(id: $id) { variantViewConfiguration } } """ def test_user_variant_preference(graphql_request_maker): user = User.objects.create( username='username12', email='btestare@example.com', variant_view_configuration=["colors[0].sizes[0].size", "details.country_of_origin"] ) data, err = graphql_request_maker.make( QUERY, { "id": to_global_id('UserNode', user.id) } ) So, as I say, I want a query that return only and only variant_view_configuration for a specific User id. I am new to django and graphql, please explain how I do this. Thank you! -
Django token authentication and csrf protection
I have a simple question to which I couldn't find a satisfying answer on the net. I have implemented a DRF API with token authentication and I wonder if I need to implement csrf verification anyway. I know that csrf verification is disabled when using DRF and moreover documentation says that if you're using session authentication than you need to implement csrf verification. So from those statements can we definitely conclude that there is no need to implement csrf verification when using token authentication? If so, for login views do we need to implement csrf verification even when using token authentication? Since login views permit unauthenticated access, I thought adding further security measures such as csrf verification might be a good practice. Thanks in advance. -
I am facing issue in QR Code generation in django python. When i insert more than 3 objects of a class, qrcode do not work
Following is my QR code def save(self,args,*kwargs): mylist = [self.name,self.passport,self.test_report_result] details = '-'.join([str(item) for item in mylist]) qrcode_img=qrcode.make(details) canvas=Image.new("RGB", (300,300),"white") draw=ImageDraw.Draw(canvas) canvas.paste(qrcode_img) buffer=BytesIO() canvas.save(buffer,"PNG") self.barcode.save(f'{self.name}',File(buffer),save=False) canvas.close() super().save(args,*kwargs) -
Django set_cookie working on localhost but not on ngrok?
I am using Django to return a cookie in a response via set_cookie: response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["refresh"], expires = settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'], path = settings.SIMPLE_JWT['AUTH_COOKIE_PATH'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'], ) where the values are: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), ... 'AUTH_COOKIE': 'refresh_token', 'AUTH_COOKIE_SECURE': False, 'AUTH_COOKIE_HTTP_ONLY' : True, 'AUTH_COOKIE_PATH': '/', 'AUTH_COOKIE_SAMESITE': 'Lax', } CORS is all set up correctly. I am also sending withCredentials: true, in my axios requests correctly. My problem is that when I test in development (i.e. Frontend hosted at http://127.0.0.1:3000/ and Backend hosted on http://127.0.0.1:8000/) the system works (i.e. the cookie gets set). However, when I use ngrok to tunnel my backend to a secure url, nothing works. I still get the set-cookie headers in my response, so I am receiving the cookies - it's just not setting them. Also, I am on Safari (since I know Chrome has an issue with setting cookies due to requiring values for samesite and secure). This is my response: here Any help would be greatly appreciated. Thank you! -
Adding a pause after each GET request
I have a table that loads empty (no rows) and then I run an Ajax call -inside a django for-loop- to populate the table with data from a python function that each time returns one row/item. The reason I am doing this is to allow for users to be able to interact with the table while the data are loading on the background (especially useful since the table displays lots or rows). I also have a jquery function that when I right-click on a row, it produces a context menu for that specific row, populated with options dynamically through an AJAX. The problem is that the context menu isnt always populated promptly. How it works is I right-click on a row and "grab" certain parameters of the object in said row. These parameters then are passed to the getTablePerms() function, which runs an AJAX POST request to a Python function that -based on those parameters- returns the permissions of the item in the row and modifies the html of the context menu div, essentially showing the context menu options. The problem is that while the rows are added to the table, right-clicking on a row should produce the context menu … -
Django linking allauth to google-api sign in
So I got the google button to link to http://localhost:8000/accounts/google/login/ and it displays the below Sign In Via Google You are about to sign in using a third party account from Google. Continue and if I click the continue button I get the following. How would I continue from here to authenticate a user using the google-api with allauth. I have the OAuth consent form with a OAuth 2.0 client id for a web app. Authorization Error Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. OAuth2.0 Client Authorized JavaScript origins For use with requests from a browser URIs * http://127.0.0.1:8000 http://localhost:8000 https://url.com Authorized redirect URIs For use with requests from a web server URIs * http://127.0.0.1:8000/accounts/google/login/callback http://localhost:8000/accounts/google/login/callback https://url.com/accounts/google/login/callback login.html: {% extends 'base.html' %} {% block title %}Login{% endblock %} {% block content %} <button><a href="{% url 'signup' %}">Sign up</a></button> <a id="google_login" href="/accounts/google/login" class="btn btn-success"> Sign in with Google </a> {% endblock %} -
Deploy Django project on apache2 over HTTPS
Currently, I have deployed django project on AWS Ec2 instance using Gunicorn and apache2 as server Also for executing Gunicorn, I have used supervisor Following is my current configuration: gunicorn.conf (location: /etc/supervisor/conf.d) [program:gunicorn] directory=/home/ubuntu/python-projects/web-app command=/home/ubuntu/python-projects/web-app/venv/bin/gunicorn --workers 3 --bind 0.0.0.0:5010project.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicron.out.log [group:guni] programs:gunicorn django.conf (location: /etc/apache2/sites-available) server { listen 5010; server_name <server_name_here>; location /{ include proxy_params; } location /static/ { autoindex on; alias /home/ubuntu/python-projects/web-app/project/static/; } } Everything is working properly over HTTP and can also serve static files Issue is, I want to run the project over HTTPS, tried many solutions but unsuccessful till now -
Update table values based on which button clicked
I have a DetailView that show all the transaction information from transaction id, name, created_date,...., and status. In this pages I have 3 button they are cancel, approve, and reject. what I want to do is when I clicked button cancel the status changed to "Cancelled", some goes for reject and approve that change the status to "Rejected" and "Success". how can I do this? I've tried to add form in the template with hidden input and method post, but after submit it show 405 error page. -
Can we connect locally created lambda to local dynamodb?
I am trying to establish a connection between the locally created lambda function and local dynamodb. I set up both lambda and dynamodb locally but don't know how to connect them? Actually, I am intended to create a Django project in local lambda and I want to use local dynamodb in it. If someone knows how to configure this, please guide me. -
Dockerized Django Application Deployed to AWS Elastic Beanstalk Flushes Database Everytime I Rebuild My Environment
I have deployed a django application using docker to AWS Elastic Beanstalk that is connected to an AWS RDS postgresql database. Everytime I update my code and rebuild my docker image, the database is always wiped clean. I am using github actions to deploy my application everytime I push my code. After searching for similar issues, most people suggest that there might be a flush command in one of the deployment scripts. That is not the case in my deployment scripts because I never explicitly flush the database. Github Actions Config name: Staging Docker Image CI on: push: branches: [ staging ] pull_request: branches: [ staging ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: lfs: 'true' - name: Build the Docker image run: docker build -t scrims -f Dockerfile . - name: Generate Deployment Package run: zip -r deploy.zip * - name: Get timestamp uses: gerred/actions/current-time@master id: current-time - name: Run string replace uses: frabert/replace-string-action@master id: format-time with: pattern: '[:\.]+' string: "${{ steps.current-time.outputs.time }}" replace-with: '-' flags: 'g' - name: Deploy to EB uses: einaregilsson/beanstalk-deploy@v14 with: aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }} aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} application_name: scrims environment_name: scrims-env-staging version_label: "scrims-staging-${{ steps.format-time.outputs.replaced }}" region: ap-southeast-1 deployment_package: deploy.zip Dockerfile # … -
django models relations getting count of given tasks
Trying to fetch a function from a table that is supposed to be there, but cannot get the value. Trying to get the amount of task that is completed. models.py class Task(models.Model): title = models.CharField(max_length=55, null=True, blank=True) slug = models.SlugField(max_length=500, unique=True, blank=True) task_completed = models.BooleanField(default=False) description = models.TextField(default="Task description") start_date = models.DateTimeField() due_date = models.DateTimeField() checklist = models.ManyToManyField(Checklist, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Task, self).save(*args, **kwargs) def get_url(self): return reverse('checklists', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task_completed(self): return self.task_completed.count() class Project(models.Model): project_manager = models.ForeignKey(Profile, on_delete=CASCADE) title = models.CharField(max_length=55, null=True, blank=True) developers = models.ManyToManyField(Profile, related_name='projects') slug = models.SlugField(max_length=500, unique=True, blank=True) description = models.TextField(default="Project description") date = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() due_date = models.DateTimeField() tasks = models.ManyToManyField(Task, blank=True) teams = models.ManyToManyField(Team, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) def get_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def num_task(self): return self.tasks.count() Then in the html is just loop through all projects {% for projects in projects.all %} <span class="text-small"> {{ projects.tasks.num_task_completed }} /{{ projects.num_task }}</span> I manage to get the amount of tasks, but not the amount completed. -
Automate deploying of synapse artifacts to devops repo
im trying to deploy some synapse artifacts to a synapse workspace with devops repo integration via a python runbook. By using the azure-synapse-artifacts library of the python azure sdk the artifacts are published directly to the live mode of the synapse workspace. Is there any way to deploy artifacts to a devops repo branch for synapse? Didnt find any devops repo apis or libaries, just for the direct integration of git. -
How to display one models data in another model django admin panel
I have two models: 1) SchoolProfile & 2) Content I want to show content data in schoolprofile, But data should be display as per user foreignkey. User foreignkey common for both the models. School Profile Model class SchoolProfile(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True) school_name = models.CharField(max_length=255) school_logo=models.FileField(upload_to='media/', blank=True) incharge_name = models.CharField(max_length=255, blank=True) email = models.EmailField(max_length=255, blank=True) phone_num = models.CharField(max_length=255, blank=True) num_of_alu = models.CharField(max_length=255, blank=True) num_of_student = models.CharField(max_length=255, blank=True) num_of_cal_student = models.CharField(max_length=255, blank=True) def __str__(self): return self.school_name Content Model class Content(models.Model): id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) content_type = models.CharField(max_length=255, blank=True, null=True) show=models.ForeignKey(Show,on_delete=models.CASCADE, blank=True, null=True) sponsor_link=models.CharField(max_length=255, blank=True, null=True) status=models.BooleanField(default=False, blank=True, null=True) added_on=models.DateTimeField(auto_now_add=True) content_file=models.FileField(upload_to='media/', blank=True, null=True) title = models.CharField(max_length=255) subtitle = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=500, blank=True, null=True) draft = models.BooleanField(default=False) publish_now = models.CharField(max_length=255, blank=True, null=True) schedule_release = models.DateField(null=True, blank=True) expiration = models.DateField(null=True, blank=True) tag = models.ManyToManyField(Tag, null=True, blank=True) topic = models.ManyToManyField(Topic, null=True, blank=True) category = models.ManyToManyField(Categorie, null=True, blank=True) def __str__(self): return self.title I have used Inline but it's show below error: <class 'colorcast_app.admin.SchoolProfileInline'>: (admin.E202) 'colorcast_app.SchoolProfile' has no ForeignKey to 'colorcast_app.SchoolProfile'. My admin.py class SchoolProfileInline(InlineActionsMixin, admin.TabularInline): model = SchoolProfile inline_actions = [] def has_add_permission(self, request, obj=None): return False class SchoolProfileAdmin(InlineActionsModelAdminMixin, admin.ModelAdmin): inlines = [SchoolProfileInline] list_display = ('school_name',) admin.site.register(SchoolProfile, SchoolProfileAdmin) -
Using python-lambda-local for django project
I am using python-lambda-local for testing aws-lambda function on local environment. Now I have django project like this /chatbot - /utilities settings.py entry.py and settings.py has entry point def hander For example, I can exec entry.py handler like this $python-lambda-local -f handler -t 5 entry.py event.json However of course it ignores the settings.py, and django environment. What is the bet practice to use django with aws lambda. -
JSON generated by json.dumps() is NOT valid according to RFC 4627
My Django management command generates some JSON. It creates a couple of Python dictionaries, puts them into another dictionary, and uses json.dumps() to convert to JSON. It then tries to save it to JSONField in database using a Django Model. The JSON is not saving due to it not being valid. I checked the JSON with many validators. They all said the JSON is invalid due to: Error: Parse error on line 1: { 'nodes': [{ 'name' --^ Expecting 'STRING', '}', got 'undefined' Eventually I found a validator that said the JSON is Javascript valid but not RFC4627 valid: I can't post the JSON here due to it being sensitive. Is there any reason json.dumps() would generate invalid JSON ? -
DRF serializer parsing comma-delimited string into a list field
Is there a way of modifying how DRF serializers parse incoming request payload? I'm trying to let clients send a comma-delimited list as query parameter but receive it inside the serializer as a list instead but DRF keeps complaining. Right now I'm manually intercepting the request in the view and doing the parsing that field manually before passing it to the serializer which doesn't seem elegant to me. What I'm doing right now class ExampleSerializer(...): list_field = serialzers.ListField(child=serializers.Integerfield(...)) # more fields def view(request): payload = request.GET payload["list_field"] = str(payload.get("list_field", "")).split(",") serializer = ExampleSerializer(data=payload) What I'd prefer (using same serializer as above) def view(request): serializer = ExampleSerializer(data=request.GET) -
How to prevent image bigger than box
I have this code : <div class="row d-flex p-3 mb-4" style="border: 1px solid rgba(0, 0, 0, 0.1)"> {{ content_page.additional_content|safe }} </div> "additional content" is text field (using CKEditor) and can contain images. I want to make it so that the contents can't be bigger than the box or parent. How can I do that? Thanks.