Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ingress health check failing on Django GKE Deployemnt
I am deploying a frontend (Nuxt) and a backend (Django) using GKE Autopilot. A CI/CD pipeline has been set up from github to GKE. The frontend gets deployed and easily viewable on xpresstracker.app while the backend spits out server error 501 on backend.xpresstracker.app. Below is the related configurations and error; Error message prodservice.yaml apiVersion: v1 kind: Service metadata: name: prod-xpressbackend-service spec: selector: app: prod-xpressbackend ports: - protocol: TCP port: 8000 targetPort: 8000 type: NodePort prodmanagedcert.yaml apiVersion: networking.gke.io/v1 kind: ManagedCertificate metadata: name: prod-managed-cert spec: domains: - xpresstracker.app - backend.xpresstracker.app prodingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: prod-ingress annotations: kubernetes.io/ingress.global-static-ip-name: xpresstrackerip networking.gke.io/managed-certificates: prod-managed-cert kubernetes.io/ingress.class: "gce" labels: app: prod-xpressbackend spec: rules: - host: xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressfrontend-service port: number: 3000 - host: backend.xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressbackend-service port: number: 8000 Deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: prod-xpressbackend-deployment labels: app: prod-xpressbackend spec: replicas: 1 selector: matchLabels: app: prod-xpressbackend template: metadata: labels: app: prod-xpressbackend spec: containers: - name: prod-xpressbackend-container image: someimage:production imagePullPolicy: Always resources: requests: memory: "200Mi" cpu: "0.2" limits: memory: "512Mi" cpu: "0.5" ports: - containerPort: 8000 env: - name: SECRET_KEY valueFrom: secretKeyRef: name: proddatabasecredentials key: SECRET_KEY - … -
Custom Django Admin Page/View
Basically I'm trying to create a custom admin web page, like a custom a view. Ideally what I want is something where like once you log in to the admin page, there would be a link somewhere like under the list of models that would redirect you to this admin center. I have a somewhat working version currently, but I would like to have it redirect to a new URL like “ /admin/social/edit/ “ instead and not just render context into the template. I’ve done a ton of googling and I just keep coming across things like “custom admin actions” which is not per se what I’m looking to do. Any help is appreciated. Thank you. -
Trying to delete an item from webpage rendered by django results in all items below it to also be deleted
In my project I have a cart application that displays any items the user decided to add to the cart. Template: {% extends '../main.html' %} {% load static %} {% block title %}Cart Summary{% endblock %} {% block content %} <main class = "pt-5"> <div class = "container"> <h1 class = "h5">Shopping Cart</h1> {% for item in cart %} {% with product=item.product %} <div data-index = "{{product.id}}" class = "row g-3 product-item"> <div class = "col-md-5 col-lg-5 order-mg-first"> <img class = "img-fluid mx-auto d-block" width = "200px" alt = "Responsive image" src = "{{ product.image.url }}" /> </div> <div class = "col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">{{ product.price }}€</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select{{product.id}}"> <option selected> {{item.qty}} </option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button type="button" id = "update-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm update-button"> Update </button> <button type="button" id = "delete-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm delete-button"> Delete </button> </div> </div> </div> </div> </div> {% endwith %} {% endfor %} … -
How can I set group permissions that filter pages according to their owners in Wagtail
I am working on a blog with Wagtail and would like to give users access to create their own content in the Wagtail admin. I would like users to be able to log into the Wagtail admin, but only have access to content that they have created themselves. I have tried to generate permissions by group, however there is no default option to limit content by author, so if I give add, edit and publish permissions, a user could edit content created by other users and could unpublish or even delete that content. I would like to know if there is a way to modify the queryset of pages that appear in the Wagtail admin for a specific user. I don't have much experience with Wagtail. So far I have seen some possible solutions but none have seemed viable or adequate. For example, there are some posts here where they propose to create a Parent page for each user, but then you would have to create a group for each user, which doesn't seem like an efficient way to do it. I appreciate any help or suggestions. Here I share some of the relevant code: class BlogIndexPage(Page): max_count = 1 … -
Django: signal doesn't work well with ForeignKey
models.py from django.db import models class Post(models.Model): text = models.TextField() approved = models.BooleanField(default=False) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) from django.conf import settings from django.db import models import os class PostMedia(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='mediafiles') media = models.FileField(upload_to='post_media/', blank=True) absolute_media_path = models.CharField(max_length=255, blank=True) def save(self, *args, **kwargs): self.absolute_media_path = self.get_absolute_media_path() return super().save(*args, **kwargs) def get_absolute_media_path(self): return os.path.join(settings.BASE_DIR, self.media.path) #Post.objects.last().mediafiles.last().absolute_media_path services.py (functions for aiogram bot and django) async def get_post_path(post_id): url = f'http://localhost:8000/api/get_media_urls/{post_id}/' async with aiohttp.ClientSession() as session: async with session.get(url) as response: if response.status == 200: data_list = await response.json() return data_list else: return None async def register_manager(CHAT_ID: str): fake = Faker() username = fake.user_name() password = fake.password() await bot.send_message(CHAT_ID, f'username: {username}\npassword: {password}\nadmin-panel: http://localhost:8000/admin', reply_markup=set_manager_kb()) # async def send_post(instance): # admin_id = '679553167' # await bot.send_message(admin_id, f'{instance}', reply_markup=set_post_kb()) async def send_post(post): message = post.split('\n') user_id = '679553167' post_id = message[0] media = [] media_paths = await get_post_path(post_id) if media_paths: for photo_path in media_paths: if photo_path.lower().endswith(('.jpg', '.jpeg', '.png')): media_type = types.InputMediaPhoto elif photo_path.lower().endswith(('.mp4', '.avi', '.mkv')): media_type = types.InputMediaVideo else: continue photo_file = open(photo_path, 'rb') input_media = media_type(media=types.InputFile(photo_file)) media.append(input_media) media[0]["caption"] = message[1] await bot.send_media_group(chat_id=user_id, media=media, reply_markup=set_post_kb()) photo_file.close() else: await bot.send_message(user_id, message[1], reply_markup=set_post_kb()) signals.py from django.db.models.signals import post_save from django.dispatch import receiver … -
cant create new model object django rest framework
model.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=30) description = models.TextField() deadline = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from django.contrib.auth.models import User from .models import Task from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): tasks = serializers.PrimaryKeyRelatedField( many=True, queryset=Task.objects.all()) class Meta: model = User fields = ['id', 'username', 'email', 'tasks'] class AuthSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'description', 'deadline', 'created_at', 'updated_at'] views class CreateTask(generics.CreateAPIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] queryset = Task.objects.all() serializer_class = TaskSerializer in the command line it says 'null value in column "userid" of relation "srctask" violates not-null constraint', do i have to access the userid by another way and attach it to the model object? -
Django - AttributeError: 'Index' object has no attribute 'constraint_type'
I am using Django 4.2.2 This is a model that is throwing the subject jessage in an error, when I run makemigrations: class AnonymousInteractionMonitor(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') interaction_type = models.PositiveSmallIntegerField(choices=Engagement.ENGAGEMENT_TYPES, null=False) visitor_ip = models.GenericIPAddressField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('visitor_ip', 'content_type', 'interaction_type') constraints = [ models.UniqueConstraint(fields=['visitor_ip', 'content_type', 'interaction_type'], name="idx_visitor_inf" ) ] The constraint is not defined on an Index, so why am I getting this error message, and how do I fix it? -
error during installation of virtual environment
I face with folliowing error when I want to install virtual env: C:\Users\MICROSOFT\Desktop\django_project>virtualenv venv 'virtualenv' is not recognized as an internal or external command, operable program or batch file. How it could be tackled? -
new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252)
I'm trying to test with Django, pytest-django and PostgreSQL on Windows 11. But I got the error below: psycopg2.errors.InvalidParameterValue: new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252) Even though I set English_World.1252 to LC_COLLATE and LC_CTYPE in run_sql() as shown below. *I wrote the code below to connect to PostgreSQL in conftest.py following the doc: # "conftest.py" import pytest from django.db import connections import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def run_sql(sql): conn = psycopg2.connect(database='postgres', user='postgres', password='admin') conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute(sql) conn.close() @pytest.fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'copied_postgres' run_sql('DROP DATABASE IF EXISTS copied_postgres') run_sql(""" CREATE DATABASE copied_postgres LC_COLLATE = 'English_World.1252' # Here LC_CTYPE = 'English_World.1252' # Here TEMPLATE postgres""") yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE copied_postgres') And, this is test_get_username() below in test_ex1.py: # "test_ex1.py" @pytest.mark.django_db def test_get_username(): user = User.objects.create_user("test-user") user.username = "John" assert user.get_username() == "John" So, how can I solve the error? -
Django Integrity error at .... null value in column
New to Django, getting a violates not-null constraint, thats preventing it posting to my DB(elephantSQL), I cant seem to get around this issue even when passing the post.id in urls, in the 'buttons' and the view.... Im not sure what I'm doing wrong hopefully someone can point me in the right direction? I have very little experience with this and im trying to learn I have tried a good few things, tho I cant seem to get it to post. HELP!!!! Views def createReview(request): form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('market_posts/') context = {'form': form} return render(request, 'market/review_form.html', context) Models from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="market_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() … -
using mongodb with motor driver and django
i'm creating an App, using async driver(motor) for mongodb. I have a telegram bot app and django framework app. I want my telegram and web apps use same database. When i try to create User via integrated CreateView class, by default django uses it's standart auth processing and adds user to its default databases(sqlite, postgre etc.) But i'd like to use mongodb and use it asyncronous(as i understood djongo is syncronous driver) the ways I see to solve this: 1) separate users' auth data(to standart database) and other data, that'll be fetched and overwritten frequently(to mongo). 2) use standart view(e.g. TemplateView, FormView) and my own form, write MyOwnUserClass with hashing and all necessary methods. Shortly I want to use instruments of Django with mongodb, how can I reach that? Well don't know if this is needed here, a piece of my current code: forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField email = forms.EmailField password = forms.PasswordInput password_confirm = forms.PasswordInput telegram = forms.CharField(required=False) views.py: class Register(CreateView): template_name = 'AIsite/register.html' form_class = RegisterUserForm success_url = reverse_lazy('login-user') -
Django admin page looks primitive
for reference: i am learning django from this page:- https://www.w3schools.com/django/django_admin.php im using virtual environment and running this on a local machine: http://127.0.0.1:8000/admin/ Expected output Reality please help. i have tried asking in subreddit and discord but im not yet able to find a fix. any help is appreciated -
WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist
Estoy aprendiendo django y me aparece el error WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. y no me deja realizar cambios en mis archivos estaticos y no se como solucionarlo intente probando con import os y cambiando STATICFILES_DIRS por STATICFILES_DIRS = \[os.path.join(BASE_DIR, "static")\] pero aun nada -
How to limit client IP of a Django app? (Through django and/or PaaS)
I am making a Django app and I wish to enhance the security as well as limit users by making sure only clients only from one IP (say a shared VPN) can access it. I plan to host the app on a PaaS like Digital Ocean App Platform or Heroku. How can I limit the client IP through: Django, to prevent other users from accessing the app, and The PaaS, so that potential attackers don't have access to the platform in the first place? (Hopefully some PaaS has this optiont) -
Model registration in django in admin.py multi model (choicefield selection)
here is my admin.py class ResumeAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = ['category'] if obj: if obj.category == 'Summary': fields.extend(['summary_title', 'summary_description', 'summary_address', 'summary_phone', 'summary_email']) elif obj.category == 'Education': fields.extend(['edu_title', 'edu_course', 'edu_start_date', 'edu_end_date', 'edu_gpa']) elif obj.category == 'Experience': fields.extend(['exp_title', 'exp_date', 'exp_where', 'ext_explanation', 'exp_project_link']) elif obj.category == 'Projects': fields.extend(['project_title', 'project_description', 'project_link']) elif obj.category == 'Certifications': fields.extend(['cert_title','cert_date', 'cert_where', 'cert_explanation','cert_project_link']) return fields admin.site.register(Resume, ResumeAdmin) and this is my model.py class Resume(models.Model): CATEGORY = ( ('Summary', 'Summary'), ('Education', 'Education'), ('Experience', 'Experience'), ('Projects', 'Projects'), ('Certifications', 'Certifications'), ) # view different fields according to the category category = models.CharField(max_length=20, choices=CATEGORY, default='Projects') class Summary(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) summary_title = models.CharField(max_length=100) summary_description = models.TextField() summary_address = models.CharField(max_length=200) summary_phone = models.CharField(max_length=20) summary_email = models.EmailField() # 2 Education option will have title, course, start_date, end_date, GPA class Education(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) edu_title = models.CharField(max_length=100) edu_course = models.CharField(max_length=100) edu_start_date = models.DateField() edu_end_date = models.DateField() edu_gpa = models.FloatField() # 3 experience filed will have same as education filed class Experience(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) exp_title = models.CharField(max_length=100) exp_date = models.CharField(max_length=100) # it holds the start and end year of the course exp_where = models.CharField(max_length=200) # college or school name ext_explanation = models.TextField() exp_project_link = models.URLField() # 4 projects filed will have … -
Heroku can't find styles.css
Trying to deploy a Django app to Heroku for the first time. When I view the app using Django, everything shows up correctly, but when I run it on Heroku, pieces of the UI are missing. I'm not too familiar with the frontend - this was a group project and I was working on backend - and my team isn't willing to help with deployment, so I'm unable to diagnose any frontend issues. Looking at the Heroku logs, I get this error "Not Found: /static/styles.css" - but there is a styles.css file under static. Does anyone know where the root problem might lie? Under settings.py I have specified this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] All functionalities work as expected, I think it has something to do with the base.html file - but this is just a stab in the dark. An example of what it's meant to look like, compared to what it looks like on Heroku. -
Django path not matching with urlpatterns in urls.py
Guys I am not a web developer, I have been learning django for a couple of hours now for my father's small business website and I am hitting a silly error for hours now. the name of the project is mysite and mysite urls.py looks like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("index.urls")), path("about/", include("about_page.urls")), path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] mysite's settings.py also includes the correct AppConfig for the app. about_page included. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'index.apps.IndexConfig', 'about_page.apps.AboutPageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] about_page's views.py is attached_below from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import Http404 # Create your views here. # return HttpResponse("website under construction !!!") def about_func(request): template = loader.get_template("about/about_page.html") context = { "about":"about_us", } return HttpResponse(template.render(context, request)) about_page's urls.py: from django.urls import path from . import views urlpatterns = [ path("about/", views.about_func, name="about_page"), ] polls and index apps have exact same pattern, i simply don't know why i cannot display about page. -
deploy project on my local machine with Apache
I built a website with Django, installed Apache and made all the adjustments. In addition, I bought a domain from GoDaddy for the site. I want to deploy the site on my computer. The problem is when I try to access the site via the internet I get to a page from GoDaddy with my domain. The steps I did: Add A record with my local IP DNS on GoDaddy Installing wsgi Updating the settings.py page with the new addresses. Update httpd-vhosts Update httpd.conf Resetting the Apache server open the ports in my firewall *I bought the domain two days ago. httpd.conf: ServerName DomainName LoadFile path LoadModule wsgi_module path WSGIPythonHome path httpd-vhosts: ServerName DomainName <VirtualHost *:80> ServerName DomainName ServerAlias www.DomainName WSGIScriptAlias / "path" ErrorLog "logs/DomainName-error.log" CustomLog "logs/DomainName-access.log" common <Directory "path"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "path" <Directory "path"> Require all granted </Directory> -
Please i want to generate username from user email in django that can be used in the url
I'm encountering an issue with populating the display_username field in my custom Django user model. Which i want to use as the username handle. My Model: class User(AbstractUser): # First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore display_username = CharField(_("Display Username"), blank=True, max_length=255) email = EmailField(_("email address"), unique=True) username = None # type: ignore USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self) -> str: """Get URL for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"pk": self.id}) My Manager: class UserManager(DjangoUserManager): """Custom manager for the User model.""" # def _create_user(self, email: str, password: str | None, **extra_fields): # """ # Create and save a user with the given email and password. # """ # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # user = self.model(email=email, **extra_fields) # user.password = make_password(password) # user.save(using=self._db) # return user # def _create_user(self, email, password=None, **extra_fields): # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # base_username = email.split('@')[0] # … -
What would be a better solution for storing data in a Django model?
Could you please give me a piece of advice? Context: I have a Django project in which each user stores many different variables linked to his profile. I created a model called Snapshot, that has a foreign key of user. Single user can have multiple Snapshots linked to his User instance, but only the latest one (by its ID, pk) is editable. Any other ones might be used to revert to past setup only. Typical use case: User modifies his setup stored in his latest Snapshot using API endpoints. Each function that an endpoint call has to query the latest Snapshot owned by user that called the function. Then it modifies some of the variables in the Snapshot and saves it. Once everything's done user approves the setup and the Snapshot is being duplicated. Now the new instance becomes the latest. Question: Is it a good idea to query the latest Snapshot this many times in each function? Wouldn't it be a good idea to link the latest Snapshot one-to-one with User, so that it's always available as User.latest_snapshot? This latest_snapshot would be automatically re-linked to User once user approves setup, thus creating a new Snapshot. -
Django tenants can't delete record from a shared model that has FK in tenant from public schema
I Have a custom user model shared between tenants and public HAS_MULTI_TYPE_TENANTS = True MULTI_TYPE_DATABASE_FIELD = 'type' TENANT_TYPES = { "public": { "APPS": [ 'django_tenants', 'clients', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'djoser', "corsheaders", 'accounts', ], "URLCONF": "server.urls_public", }, "menu": { "APPS": [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'accounts', 'products', ], "URLCONF": "server.urls_menu", }, "full-version": { "APPS": [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'accounts', 'products', 'order', ], "URLCONF": "server.urls_full", } } INSTALLED_APPS = [] for schema in TENANT_TYPES: INSTALLED_APPS += [app for app in TENANT_TYPES[schema] ["APPS"] if app not in INSTALLED_APPS] from the full-version order app, there is an FK to the user model that restrict me to delete any user from the public schema class Address(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) also, the issue appears in the menu type cuz the order models do not exist yet django.db.utils.ProgrammingError: relation "order_address" does not exist LINE 1: ...."user_type", "accounts_user"."phone_number" FROM "order_add... Is any work around or do I have to create an empty model for each type? -
How to clone github repository to azure blob
I'm trying to clone a github repository in my django application and write it to my server machine. And I have to serve that repository files to end users. I did it using below code "my implementation code"but "shutil.rmtree(repo_dir)" is taking very long time to remove existing repository files from my server machines. "Here is my implementation code" Please help and guide if there is any better way to do this. Thanks in Advance -
ploty theme change issue
I am using ploty py and django have two themes in my webapp dark and light. on light theme select graph is shown light theme and on dark theme select graphs are shown dark theme. the issue i am getting when one user change the theme it affect the other user graph theme when other user refresh or callback change. dark theme template import plotly.io as pio from plotly.graph_objs import Layout import plotly.graph_objects as go dark_template_layout = Layout( images=[ dict( source="/static/img/images/watermark/Anahit-SVG-LOGO-GreyScale-4.svg", name="Anahit", xref="paper", yref="paper", x=0.5, y=0.5, sizex=0.5, sizey=0.4, xanchor="center", yanchor="middle", layer="below", opacity=0.1, ) ], annotationdefaults={ "arrowcolor": "#f2f5fa", "arrowhead": 0, "arrowwidth": 1, }, autotypenumbers="strict", coloraxis={"colorbar": {"outlinewidth": 0, "ticks": ""}}, colorway=[ "#636efa", "#EF553B", "#00cc96", "#ab63fa", "#FFA15A", "#19d3f3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52", ], font={ "family": "Mulish, sans-serif", "size": 16, "color": "#a9afc3", }, ### title ### title={ "font": { "family": "Poppins, sans-serif", "size": 15, "color": "white", }, ### control position of title # "y": 0.5, "x": 0.5, # "xanchor": "right", # "yanchor": "middle", }, hoverlabel={"align": "left"}, # Keep adding others as needed below hovermode="closest", mapbox={"style": "dark"}, **paper_bgcolor="#080a12",** **plot_bgcolor="#080a12",** shapedefaults={"line": {"color": "#a9afc3"}}, sliderdefaults={ "bgcolor": "#C8D4E3", "bordercolor": "rgb(17,17,17)", "borderwidth": 1, "tickwidth": 0, }, updatemenudefaults={"bgcolor": "#506784", "borderwidth": 0}, xaxis=dict( automargin=True, gridcolor="#283442", linecolor="#506784", title={"standoff": 15}, zerolinecolor="#283442", zerolinewidth=2, rangeselector={"activecolor": … -
Django: Make variable of child model depend on number of siblings associated with the same parent model
Assume I have two models, one modelling a Patient and another one modelling a tissue sample. To avoid confusing among lab members, instead of refering to the samples and the patients by a PK we transform the PK into a hashed string named displyed_id below. In the ideal case we would have a patient referred to as 'H6F4A' and the samples to be 'H6F4A-1', 'H6F4A-2', etc. (be labelled by a suffix of the sample number belonging to that patient). As a requirement we would need that if a sample is deleted that the sample numbering doesn't change for the suceeding samples (as the samples have physical barcodes printed onto them). As this is kind of hard to do (probably one would need a counter for every patient counting how many samples there are) we have opted to use the tissuesample pk as the suffix which is not really what we want as this is global and not per patient. Even if this new counter would not be a pk, combined with the hashed id of its parent e.g. sample 1 of patient 1 being 'H6F4A-1' it would need to be an injective mapping as staff will always refer to this … -
How to make on update record pass the signal in Django Model?
Hello I'm trying to make on update trigger in Django Model. Model.py class Item(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) code = models.CharField(max_length=100, null=True, blank=True, unique=True) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) gsts = models.ForeignKey(Gst, on_delete=models.CASCADE) sgst = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) cgst = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) net_amount = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def ItemGenerator(sender, instance, created, *args, **kwargs): if created: id = instance query = Item.objects.get(id = int(id.id)) #gst calculation gst_cal = query.price * query.gsts.gst/100 #net amount calculation net_amounts = query.price + gst_cal #item number generate temp_count = Item.objects.all().count() no = str('ITEM') + '/' +str(temp_count) query = Item.objects.filter(id = id.id).update(code = str(no), cgst = round(gst_cal/2), sgst=round(gst_cal/2), net_amount = round(net_amounts)) When I'm insert to the data post_save signal is call and my price and gst calculation save into data base but problem is that when I'm update the record post_save signal is not working