Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url not cannot find some UTF-8 usernames
i am experimenting with UTF-8 for usernames in a django app. Django is Version 3.2.11 Python used is 3.9.4 Some users might have a profile visible to others and ther username in the url: re_path("^u/(?P<username>\w+)/$", views.author_profile_view, name="author_profile_view"), Normal Example works fine: Browser shows -> /u/brainyChowder3/ Django shows -> GET /u/brainyChowder3/ HTTP/1.1" 200 10593 UTF-8 example 1 works also fine: Browser shows -> /u/ɊȁⱲÒđΈⱦİĬd/ Django shows -> GET /u/%C9%8A%C8%81%E2%B1%B2%C3%92%C4%91%CE%88%E2%B1%A6%C4%B0%C4%ACd/ HTTP/1.1" 200 12508 But this UTF-8 does not work: Browser shows -> /u/ɂáⱳ1⁄4%7Cĭğę Django shows -> "GET /u/%C9%82%C3%A1%E2%B1%B31%E2%81%844%7C%C4%AD%C4%9F%C4%99 HTTP/1.1" 404 5585 The browser does show it strange, as he does not "translate" %7C to |, but that should be just optical? Error shown is just Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/u/%C9%82%C3%A1%E2%B1%B31%E2%81%844%7C%C4%AD%C4%9F%C4%99 The current path, u/ɂáⱳ1⁄4|ĭğę, didn’t match any of these. In Django shell I can query this user: >>> User.objects.get(username='ɂáⱳ1⁄4|ĭğę') <User: ɂáⱳ1⁄4|ĭğę> The URI decoding looks ok to me. I hope someone can explain why this is happening to one UTF-8 string, but not the other. Or maybe even knows how to fix it? :-D I know it may not be the smartes thing to allow all UTF-8 for usernames, but this is more an experiment for me. … -
How do I pass Django local variable of a funtion in views to javascript fetch API?
I am all new to javascript. I am making a like button that will increase the number of likes of a post asynchronously without reloading the whole page. Following is my Django views function. views.py @login_required def likepost(request,id): post = NewPost.objects.get(id = id) is_like = False for like in post.likepost.all(): if like == request.user and request.method == "POST": is_like = True break if not is_like: post.likepost.add(request.user) else: post.likepost.remove(request.user) return JsonResponse({ "id" : id, "is_like" : is_like, "num_like" : post.likepost.count() }) Here id is the primary key of NewPost model. My javascript will fetch an API using this id variable. Here is my js function. document.addEventListener("DOMContentLoaded",function(){ document.querySelector('#like').addEventListener('click', ()=> like_function()); }) function like_function(){ fetch(`index/${id}/like`) .then(response => response.json()) .then(result => { if(result.is_like){ document.querySelector('#like').innerHTML = "Like"; } else{ document.querySelector('#like').innerHTML = "Unlike"; } }) } <button onclick="like_function()" id = "like" class="btn btn-link"><i class="fa fa-heart"></i> </button> <small id="num_of_likes">{{ posts.likepost.all.count }}</small> {% block script %} <script src="{% static 'network/controller.js' %}"></script> {% endblock %} <button class="btn btn-link" style="text-decoration: none;">Comment</button> <a href="{% url 'postpage' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">View Post</a> Here, I've shared my javascript function as well as my HTML template. If I click the like button following message appears. What should I do now? -
RegisterSerializer WARNING:django.request:Bad Request:
Hi I override my User and now i create app connect Django Forms and Django DRF with model. And i have bad POST in serializer and i dont know why its not work, Its happend when i change image in project using Model but dont know why. I'm using swagger drf to POST.I'm using default when avatar == None and use link when no. class CreateUserManager(BaseUserManager): def _create_user(self, email, password, date_of_birth, is_verified, is_admin, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, **extra_fields ) user.is_admin = is_admin user.is_verified = is_verified user.is_superuser = is_superuser user.set_password(password) user.save(using=self._db) return user def create_user( self, email, password, date_of_birth, is_verified=False, is_admin=False, is_superuser=False, **extra_fields): return self._create_user(email, password, date_of_birth, is_verified, is_admin, is_superuser, **extra_fields) def create_superuser( self, email, password, date_of_birth, is_verified=True, is_admin=True, is_superuser=True, **extra_fields): return self._create_user(email, password, date_of_birth, is_verified, is_admin, is_superuser, **extra_fields) class CreateUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) date_of_birth = models.DateField(blank=True, validators=[validate_date_of_birth]) date_joined = models.DateTimeField(blank=False, default=timezone.now) username = models.CharField(max_length=150, blank=True) email = models.EmailField(max_length=150, blank=False, unique=True) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) avatar = models.ImageField(default='./default/accounts/user/default_user.png', blank=True, upload_to='./images/accounts/user/', validators=[validate_image, validate_exist_image]) password = models.CharField(max_length=120, blank=False, validators=[validate_password]) objects = CreateUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def … -
getting wrong slug when trying to return to last page
Trying to create a function to return to last page, but slug is wrong and i cannot seem to get the correct slug. models.py class Checklist(models.Model): title = models.CharField(max_length=55) slug = models.SlugField(max_length=500, unique=True, blank=True) due_date = models.DateTimeField() check_completed = models.BooleanField(default=False) notes = models.ManyToManyField(Note, blank=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Checklist, self).save(*args, **kwargs) def get_url(self): return reverse('task_detail', kwargs={ 'slug':self.slug }) def return_url(self): return reverse('project_detail', kwargs={ 'slug':self.slug }) def __str__(self): return self.title @property def last_comment(self): return self.notes.latest("date") 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 __str__(self): return self.title @property def num_checklists(self): return self.checklist.count() @property def num_checklist_completed(self): return self.checklist.filter(check_completed = True).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 … -
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)