Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I send an email to a user using SMTP in Django?
I use the SMTP server to send the reset password link to the user, but the problem is when the user enters his or her email , the reset password email is not sent to him. Anyone can help me, please? settings.py : EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS= True EMAIL_HOST_USER = 'myemail' EMAIL_HOST_PASSWORD = 'mypassword' urls.py : path('ResetPassword/' , views.ForgetPassword,name = "ResetPassword"), path('Test_ChangePass/<token>/', views.Test_ChangePass, name = 'Test_ChangePass'), models.py : class Profile(models.Model): image = models.ImageField(default='default.png', upload_to='profile_pics') user = models.OneToOneField(User, on_delete=models.CASCADE) forget_password_token = models.CharField(max_length=100) def __str__(self): return '{} profile.'.format(self.user.username) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 300 or img.height > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path) def create_profile(sender, **kwarg): if kwarg['created']: Profile.objects.create(user =kwarg['instance']) post_save.connect(create_profile, sender=User) views.py : def ForgetPassword(request): try: if request.method == "POST": email = request.POST.get('email') if not User.object.filter(email=email).first(): messages.error(request, 'لا يوجد ايميل مسجل مسبقًا ') return redirect('ResetPassword') user_obj = User.objects.get(email=email) token = str(uuid.uuid4()) profile_obj = Profile.objects.get(user = user_obj) profile_obj.forget_password_token = token profile_obj.save() send_forget_password_mail(user_obj,token) messages.error(request, 'تم إرسال الايميل') return redirect('ResetPassword') except Exception as e: print(e) return render(request, 'user/ResetPassword.html') def Test_ChangePass(request, token): context = {} try: Profile_obj = Profile.objects.filter(forget_password_token = token).first() print(Profile_obj) if request.method == "POST": new_password = request.POST.get ('new_password') confirm_password = request.POST.get('confirm_password') … -
How to list latest posts in Django?
I'm working on my blog. I'm trying to list my latest posts in page list_posts.html.I tried but posts are not shown, I don't know why. I don't get any errors or anything, any idea why my posts aren't listed? This is models.py from django.db import models from django.utils import timezone from ckeditor.fields import RichTextField from stdimage import StdImageField STATUS = ( (0,"Publish"), (1,"Draft"), ) class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") title = models.CharField(max_length=255, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") is_published = models.BooleanField(default=False, verbose_name="Is published?") published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at") title = models.CharField(max_length=200, verbose_name="Title") slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = StdImageField(upload_to='featured_image/%Y/%m/%d/', variations={'standard':(1170,820),'banner':(1170,530),'thumbnail':(500,500)}) status = models.IntegerField(choices=STATUS, default=0) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['-created_at'] def publish(self): self.is_published = True self.published_at = timezone.now() self.save() def __str__(self): return self.title This is views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Category, Post def post_list(request): posts = Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at') latest_posts = Post.objects.filter(published_at__lte=timezone.now()).order_by('published_at')[:5] context = … -
"mysql server has gone away" on 404 or 403
Recently, like a few days ago, I switched my Django application from a SQLite database to a MySQL one. However, since then I'm getting failures that the "MySQL server has gone away" when hitting a 403 or 404 error (maybe more, but I can't test that). The funky thing is, the application runs fine after reloading the gunicorn service, but starts acting weird when restarting the mysql service. The gunicorn logs only gives me a bunch of stacktraces, without the actual sql error (the cause is just a hit on the database), and sadly MySQL doesn't tell me either what the problem is, even after enabling error logging. My Django application is running in a virtual environment, managed with poetry. A gunicorn service is running with uvicorn workers, with the following command: /home/XXX/.cache/pypoetry/virtualenvs/project-py3.10/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/project/project.sock project.asgi:application -k uvicorn.workers.UvicornWorker. The database is configured like DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'password', 'CONN_MAX_AGE': 3600, 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': 'SET sql_mode="STRICT_ALL_TABLES"' } } } nginx serves requests to the socket, but that works fine; I can't find any error in the nginx logs, and the request "just returns 500". I'm using mysql … -
How to connect image in Django 4?
I have a project, connected database, one picture and form for send another picture. In home page i want connect all pictures from DB but i don't understand how it's work.Please help me, because i try all what i found in internet settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path("", views.products), path("sell/", views.sell), path("created/", views.created), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) else: urlpatterns += staticfiles_urlpatterns() models.py from django.db import models class Product(models.Model): ... product_media = models.ImageField(upload_to="images", verbose_name="Фотографії товару") views.py from django.shortcuts import render from .forms import SellForm from .models import Product from main.settings import MEDIA_URL, MEDIA_ROOT def products(request): product_list = Product.objects.all() return render(request, "products.html", {"product_list": product_list, "media_url": MEDIA_URL, "media_root": MEDIA_ROOT}) products.html <!DOCTYPE html> <html lang="uk"> <head> <style> ... </style> </head> <body> <h1>Оголошення </h1><a href="sell/">Створити нове оголошення</a> {% if product_list %} <table border="1"> <tr> <th>Id</th> <th>Час створення</th> <th>Профіль продавця</th> <th>Ім'я продавця</th> <th>Прізвище продавця</th> <th>Телефон продавця</th> <th>Електронна пошта продавця</th> <th>Назва оголошення</th> <th>Опис</th> <th>Медіа</th> </tr> {% for object in product_list %} <tr> <td>{{ object.id }}</td> <td>{{ object.product_dt }}</td> <td>{{ object.product_username }}</td> <td>{{ object.product_name }}</td> <td>{{ object.product_lastname }}</td> … -
Can I test the sent email in the register view with "mailoutbox" parameter in pytest_django?
I have a register view that sends an activation email and I want to test sending emails with "mailoutbox" parameter in pytest_django. This is the register view: for EmailMessage I used mail_templated and send from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from django.urls import reverse_lazy from django.views.generic.edit import FormView from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import RefreshToken from mail_templated import EmailMessage from decouple import config from .utils import EmailThread from .forms import UserCreationModelForm User = get_user_model() class AccountsRegisterFormView(FormView): """ A view for displaying a register form and rendering a template response. """ form_class = UserCreationModelForm template_name = 'accounts/register.html' success_url = reverse_lazy('task:list') def get_token_for_user(self, user): refresh = RefreshToken.for_user(user) return str(refresh.access_token) def form_valid(self, form): """ If the form is valid, redirect to the supplied URL :param form: registration form :return: if form valid register user. """ user_obj = form.save() if user_obj is not None: email = user_obj.email username = user_obj.username token = self.get_token_for_user(user_obj) domain = 'http://127.0.0.1:8000/' url = 'accounts/activation/confirm/' activation_email = EmailMessage( 'email/activation_account.tpl', { 'user': username, 'token': f'{domain}{url}{token}/', }, 'sender@example.com', [email] ) EmailThread(activation_email).start() return HttpResponseRedirect( reverse_lazy('accounts:activation_send') ) return super(AccountsRegisterFormView, self).form_valid(form) I used EmailMessage from mail_templated package. and this is the test: @pytest.mark.django_db class TestAccountsViews: def test_accounts_views(self, client, mailoutbox): url = … -
Django pass form cleaned data to another view
I want to pass the forms cleaned data (captured from a POST method), to another view (preferably as GET params) ... in this case the Dashboard View. def post(self, request): form = FilterForm(request.POST) if form.is_valid(): response = HttpResponse(reverse('dashboard')) How can I accomplish that? -
which is the best Backend Framework for beginners in 2023? [closed]
node+express+mongodb or django+sql **which stack should choose a beginner for Backend in 2023? **which stack will better for future career? I am a junior react developer. I want to learn Bracken in 2023. please leave your valuable advice on comment. your every advice matter for me. -
Class method in timer thread within Websocket in Django
I try to put a timer within websocket consumer, so that I can check task results (taken from celery) and publish to the client. The first message connection_established is received by the client. But the task result method can't send a message. What's the reason for this? class ProcessConsumer(WebsocketConsumer): ... def publish_task_results(self): self.send(text_data = json.dumps({ 'type': 'task_result', 'result': self.results, # builds results in another method. })) def connect(self): self.accept() self.send(text_data = json.dumps({ 'type': 'connection_established', 'message': 'You are now connected', })) threading.Timer(1.0, self.publish_task_results) # calls the method within same class. -
Django 'RichTextUploadingField' object has no attribute 'needs_multipart_form'
Всем привет! Я подключил в свой проект редактор ckeditor, и в поле description изменил тип поля на RichTextField, так же в admin.py у меня используется inlines для ингредиентов. Проблема заключается в следующем, я не могу использовать редактор и inlines одновременно, когда я это делаю вылезает ошибка: 'RichTextUploadingField' object has no attribute 'needs_multipart_form' models.py class Foods(models.Model): description = RichTextField(verbose_name="Описание") class ingredients (models.Model): title = models.CharField(max_length=250,verbose_name="Название") quantity = models.IntegerField(verbose_name="Количество") food_id = models.ForeignKey(Foods,) admin.py from django.contrib import admin from ckeditor_uploader.fields import RichTextUploadingField from django import forms from ckeditor.fields import RichTextField from .models import Foods, ingredients class ingredientsInline(admin.TabularInline): model = ingredients extra = 1 class FoodsAdminForm(forms.ModelForm): description = forms.CharField(widget=RichTextUploadingField ()) class Meta: model = Foods fields = '__all__' class FoodsAdmin(admin.ModelAdmin): inlines = (ingredientsInline,) form = FoodsAdminForm admin.site.register(Foods,FoodsAdmin) admin.site.register(ingredients) Много чего пробовал, но не получилось и в интернете не нашел, джанго изучаю -
Django user creation where superuser can create admin and admin can create client
I to create a django project where there is a single superuser. Superuser can create multiple unique admins and Admins can create multiple users under them. I am new to this can anyone help with this. Thank You I tried creating a superuser and admin but i am not able to create unique admins and users . -
Please help to get content of the file in request.FILES
"""I'm studying Django and have a problem: i need to upload file to server and then re-write database from this file, without saving file in django storage. But i cant upload file and get its content""" 'urls:' path("purchase/about/new_database", xml_parsing, name="new_database"), 'Html:' <div class="container"> {% if request.user.is_staff %} <a class="btn btn-primary" href={% url "orders:new_database" %}>Кнопка</a> {% endif %} </div> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button class="btn btn-primary" type="submit">Upload</button> </form> </div> 'views:' def xml_parsing(request): myfile = request.FILES["myfile"] root_node = ElementTree.parse(myfile.read()).getroot() """and so on""" """Here i get MultiValueDictKeyError. Error in line: myfile = request.FILES["myfile"]. guess, there is no need to provide other code, it works correctly when opening file from computer xml_parsing works on button 'Кнопка', so whether i need to upload file initially, and then click the 'Кнопка' and call xml_parsing function ?""" -
image file inside css is not loading in django
I unable to display image in Django. It is loading images which is in the img tag defined in the html file just fine. But the image defined in the css file is not loading and displaying on the page. I have configured django for static files. And other images are loading properly which is in the static folder. I have a static folder and inside it I have another folder of css which contains all other css files. HTML files are in the templates folder. css file ` /* Cover Section Styling */ #cover{ background-image: url(static/img/random5.jpg); display:flex ; height: 70vh; background-position: center; align-items:center ; justify-content: center; } ` setting.py file ` STATIC_URL = '/static/' # Added manually STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] ` -
Django Server stuck after updating from python 3.9 to python 3.10 (using Django 4.1.5)
After upgrading python 3.9 to 3.10 the Django Server isn't working locally anymore (I'm using the Django Server Plugin for Pycharm). In my gitlab pipeline it seems to work allright. Below you can see further details: With a Python 3.9 venv some errors occur, but the Django Server works nevertheless With a Python 3.10 venv the same errors occur, but the Django Server doesn't start (after waiting 30 min) (Working on linux and with pycharm) I have the same requirements installed on both venv s except for the python version. I'd expect an error message, but it seems the execution is just stuck. -
Reducing number of repeated queries in Django when creating new objects in a loop
I'm populating a database using Django from an Excel sheet. In the example below, the purchases list simulates the format of that sheet. My problem is that I'm repeatedly using Customer.objects.get to retrieve the same Customer object when creating new Purchase entries. This results in repeated database queries for the same information. I've tried using customers = Customer.objects.all() to read in the whole Customer table into memory, but that doesn't seem to have worked since customers.get() still creates a new database query each time. from django.db import models # My classes class Customer(models.Model): name = models.CharField("Name", max_length=50, unique=True) class Item(models.Model): name = models.CharField("Name", max_length=50, unique=True) class Purchase(models.Model): customer = models.ForeignKey("Customer", on_delete=models.CASCADE) item = models.ForeignKey("Customer", on_delete=models.CASCADE) # My data purchase_table =[ {'customer': 'Joe', 'item': 'Toaster'}, {'customer': 'Joe', 'item': 'Slippers'}, {'customer': 'Jane', 'item': 'Microwave'} ] # Populating DB for purchase in purchase_table: # Get item and customer (this is where the inefficient use of 'get' takes place) item = Item.objects.get(name=purchase['item']) customer = Customer.objects.get(name=purchase['customer']) # Create new purchase Purchase(customer, item).save() -
Django : Only display model items that match with for each category and have at least one item
Here are the models I've created class Jeu(models.Model): nom = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField(blank=True) def courses_a_venir(): return self.course_set.filter(date_evenement__gte = datetime.today()).order_by('date_evenement') def courses_passees(): return self.course_set.filter(date_evenement__lt = datetime.today()).order_by('-date_evenement')[:3] class Course(models.Model): jeu = models.ForeignKey(Jeu, verbose_name='Nom du jeu', on_delete=models.CASCADE) ligue = models.ForeignKey(Ligue, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) date_evenement = models.DateTimeField("Date de la course") Here is the view : def home(request): jeux = Jeu.objects.all() return render( request, 'base_site/home.html', context={'title': 'Accueil', 'jeux': jeux,} ) And then here is the HTML code : {% for jeu in jeux %} <h3>{{ jeu.nom }}</h3><br> <div class="row row-cols-1 row-cols-md-3 g-4"> {% for course in jeu.courses_a_venir %} <div class="col"> <div class="card"> <!--<img src="..." class="card-img-top" alt="...">--> <div class="card-body"> <h5 class="card-title">{{ course.date_evenement }}</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> </div> <div class="card-footer"> <small class="text-muted">{{ course.date_evenement }}</small> </div> </div> </div> {% endfor %} </div><br> {% endfor %} <br><br> The thing is, one "Jeu" can be called by multiple "Course". As it is currently implemented in the HTML code, it retrieves all the "Jeu" in the table "Jeu" and the "Course" associated, no matter if some "Jeu" don't contain any "Course". Does somebody know … -
How can I decode a token sent to a user to know when it was created
Hello I did a reset password system in my web that sends a token link to the client's mail in order to client can reset the password, And I want to check the timestap of the hashed token, to make some condition like... expire in 24h. This file make the token and I "guess" is hashing user.pk and timestap and returning a hashed token. I want to make reverse process to know when that token was created. tokens.py: from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) ) account_activation_token = AccountActivationTokenGenerator() Token link is going perfect and client can change the passord whitn no problems. this is my view that handle this with 2 functions 1st for sending the mail, and 2nd for reset the password. view.py: def reset_password(request): form = ResetPasswordForm(request.POST or None) if form.is_valid(): user = User.objects.filter(email=form.cleaned_data.get('email')) if not user: messages.error(request,'This user does not exist') else: user = user.first() current_site = get_current_site(request) subject = 'Reset Password' message = render_to_string('core/reset_password_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail(subject,message,conf_settings.EMAIL_HOST_USER,[user.email,]) messages.success(request,'Password reset link sent to your email') return redirect('consumer:consumer_home') context = { 'form':form, } return render(request,'core/password_reset.html',context) def reset_password_confirm(request, uidb64, token): … -
Connecting externally to a website in a windows ec2 container
Im failing to connect externally to a django site running in an ec2 windows instance and the common problems im finding online appear to all be accounted for: eg) my firewall is fine (im permitting inbound private and public) my ports seems fine (im running on port 80, and it seems to be the only thing running and my aws security group rules permit port 80) i also have only 1 acl on my whole account, and its the default 1 that permits everything. There is evidence of all of this in images i have stuck at the bottom. What else should i try / investigate / learn about? i did this once before and it was fine. now i keep trying to recreate what i did before and i just cant connect externally. ################## images below as evidence for stuff ################# below is evidence of stuff inside my ec2 container ################################################### below is evidence from my aws account/ attempting to connect from outside ec2 container. (i did try setting my port to 8000 and opening a custom tcp at port 8000 ) ########################################### the image below shows my acl. its the only one on my account -
'Profile' object has no attribute 'User'
enter image description here I get this error every time I create a profile -
Django admin model instance is not added to the list, error : "Tweeter with ID “” doesn’t exist. Perhaps it was deleted?"
I am trying to add an instance of the model "Tweeter" through Django admin and it gives me a message that it is added, but it does not appear in the list of the model and when I click on the pop up message it says "Tweeter with ID “” doesn’t exist. Perhaps it was deleted?" Tweeter model. Tweet_df is a dataframe and tweets_df['username'] is a string: ` class Tweeter(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True) tweet_search = models.ForeignKey('TweetSearch', on_delete=models.RESTRICT, null=True) username = models.CharField(max_length=200, blank=True, null=True) followers_count = models.IntegerField(blank=True, null=True) class Meta: ordering = ['followers_count'] def save(self, *args, **kwargs): tweets_df = get_tweets(self.tweet_search.search_term) self.username = tweets_df['username'] self.followers_count = tweets_df['followers_count'] def get_absolute_url(self): return reverse('tweeter_detail', kwargs={'pk': self.pk}) ` TweetSearch model: ` class TweetSearch(models.Model): from datetime import datetime, timedelta search_term = models.CharField(max_length=200, blank=True) QUERY_CHOICES = ( ('t', 'in tweet'), ('h', 'in hashtag'), ('u', 'username'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True) query_type = models.CharField(max_length=1, choices=QUERY_CHOICES, blank=True, default='t') start_default = datetime.now() - timedelta(days=30) start_date = models.DateTimeField(default=start_default) end_date = models.DateTimeField(default=datetime.now) language = models.CharField(max_length=200, blank=True) country = models.CharField(max_length=200, blank=True) searcher = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) def get_absolute_url(self): return reverse('tweet_detail', kwargs={'pk': self.pk}) def __str__(self): return f"Tweets with the word {self.search_term} from {self.start_date} till {self.end_date} written in " \ f"{self.language} in … -
how to add conditionals in html attribute
I am using django 4.1.4 and I am new to it. In a form I want to set the correct url based on the variable 'update'. If the variable is True, then the template is used for update (in this case a different url), else save new data. I created something like this: <form action="{% if update %} {% url 'in.edit_session' session.id %} {% else %} {% url 'in.save_session' %} {% endif %}" method="POST" class="form"> but is not working. This will work... but I don't want to duplicate code: {% if update %} <form action="{% url 'in.edit_session' session.id %}" method="POST" class="form"> {% else %} <form action="{% url 'in.save_session' %}" method="POST" class="form"> {% endif %} How can I do this ? -
How Is Web Apps Like Figma and Canva are Built
So I was learning web development and had a idea of building a software like Figma and Canva But had no idea of what technologies do they use to build such web apps. I am a Django developer but is it even possible to build a project with Django , Python and Javascript. I wanna know what technology and tech stack, languages are used to build a application as such. I actually tried to build with Django and Python on the Backend and JS on the frontend for Scripting and also tried to used OpenCV. But then I am not sure about will this work and how to build a software that can edit Videos and Photos like Canva and create Artboard like Figma on the Web I also wanna know what softwares and stack these companies use if possible -
Django queryset - differing results for query and query.count()
I have a django model with three fields and I'm trying to find the duplicates. If I run: cls.objects.values('institution','person','title').annotate(records=Count('person')).filter(records__gt=1).count() I get 152 as the output. However, if I attempt to see what those records are and run the same query without the count() cls.objects.values('institution','person','title').annotate(records=Count('person')).filter(records__gt=1) I get <QuerySet []>. Any idea what's going on? If I add a .first() I get null, and a [0] gives me an out of range error, however the count continues to return 152. -
(Error) django.db.utils.IntegrityError: The row in table "" with primary key "' has an invalid foreign key
I am trying to get the primary key of my User model (which is not the default pk) by using a ForeignKey and then, with a property, get the "usertag" of the User model, but when I try migrating my changes I get the following error: django.db.utils.IntegrityError: The row in table 'user_friend' with primary key 'LOL' has an invalid foreign key: user_friend.fk_id contains a value 'fk_id' that does not have a corresponding value in user_user.id. My models.py: from django.db import models class User(models.Model): f_name = models.CharField(max_length=15) l_name = models.CharField(max_length=15) usertag = models.CharField(max_length=7, default="aabb11") level = models.IntegerField(default=1) profile_pic = models.URLField(max_length=10000) email = models.EmailField(max_length=100) password = models.CharField(max_length=25) class invites(models.Model): invite_id = models.CharField(max_length=8, primary_key=True) choices = [("P", "PENDING"), ("A", "ACCEPTED"), ("D", "DECLINED")] sent_to = models.CharField(max_length=7) from_user = models.CharField(max_length=7) invite_status = models.CharField(choices=choices, default=choices[0], max_length=9) # USE Foreign KEYS class friend(models.Model): fk = models.ForeignKey(User, on_delete=models.CASCADE, db_constraint=False) friend_tag = models.CharField(max_length=7, primary_key=True) @property def my_tag(self): return self.fk.usertag -
can we add 1 template to 2 view?
i wonder if i can add 1 template like art_detail.html into 2 views template_name if so objectcontains which ones data? unfortunately i got a problem with adding comment to posts ,i asked it in reddit but since got 0answer i would be pleased if you answer it:https://www.reddit.com/r/learnpython/comments/1029qyk/why_createview_doesnt_create_text_input/?utm_source=share&utm_medium=web2x&context=3 my only purpose was to add comment into posts -
How to stop docker-compose application from inside one of the containers
I have a simple django application, that uses a scheduler to check if the cpu_usage of the server is too high. When the cpu_usage exceeds a certain threshold a want all docker-container applications running on the server to stop. How can I stop docker-container applications from inside on of the containers ?