Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the difference of form_class and model in django CreateView?
why only "form_class" work but using "model" with "fields" not work error : 'ModelFormOptions' object has no attribute 'private_fields' -
When I send a letter to the mail gives an error 'tuple' object has no attribute 'get'
I do so that after registration to the post office a letter is sent but it gives me an error The letter arrives in the mail, but gives an error and should redirect to another url 'tuple' object has no attribute 'get' my Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\deprecation.py" in call 96. response = self.process_response(request, response) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\middleware\clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /register/ Exception Value: 'tuple' object has no attribute 'get' Settings EMAIL_HOST = 'smtp.mail.ru' EMAIL_PORT = 2525 EMAIL_HOST_USER = "itraptor@mail.ru" EMAIL_HOST_PASSWORD = "labrador75" EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER views.py def register(request): if request.method == 'POST': form = RegisterForm(request.POST) username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] context = {'form': form, 'username': username, 'password1': password1, 'password2': password2, 'email': email} if form.is_valid(): form.save() return redirect('/loginNow/') , send_mail('Тема', 'Тело письма', settings.EMAIL_HOST_USER, [email]) else: form = RegisterForm() context = {'form': form } return render(request, 'registration/registred.html', context) -
Why is this code failing in a 32-bit enviroment?
I'm moving a very simple django app from my desktop pc to a virtualbox server. I have copied the hole proyect, except for the virtualenv sources folder. Then, i've created a virtualenv and installed dependencies in the same way. When i run manage.py a circular reference error cames in claming The included URLconf 'pmkwebPdf.urls' does not appear to have any patterns in it This is the project dir: PmkwebPdf media pmkwebPdf __init.py settings.py urls.py wsgi.py src migrations ... processor ... __init__.py admin.py apps.py models.py tests.py urls.py views.py templates ... venv ... db.sqlite3 manage.py It's certanly an error with the urlpatterns. So i did this. pmkWebPdf.urls from django.contrib import admin #from django.urls import path, include urlpatterns = [ #path('', include('src.urls')), path('admin/', admin.site.urls), ] In this file, if i remove the path('', include('src.urls')), and its dependecies the error is gone. src/urls.py from django.conf.urls.static import static from django.urls import path from pmkwebPdf import settings #from src.views import index urlpatterns = [ #path('', index, name='index') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) After leaving the pmkWebPdf.urls without the lines commented, i discovered that, in this file, if i leave the urlpatters empty and remove the from src.views import index line. The server runs. I've created the … -
How auto create model in Django?
i has model where i add writes , how at add write auto- create model in other apps with name of this added record? In which I can create entries -
Django forms : how to use Html and css template forms
How can I use (Html+CSS Template forms ) in django ? Hi Guys. I really don't like django forms appearances or even crispy_forms so I downloaded a form Html and Css from this website "colorlib.com" and pasted in my 'signup.html', and 'signup.css' ,form showed up but after filling from and sending it it shows error . I use CBVs .... I'm sure view and url are correct but I think I have to change tags in html to django Tags, Thank you in advance :Btw I use bootstrap , do i need change its href This is form template in django which is very simple and I need more beautiful one : <!-- templates/signup.html --> {% extends 'base.html' %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} Html of form (https://codepen.io/colorlib/pen/aaaoVJ) which i like to use <!-- Author: Colorlib Author URL: https://colorlib.com License: Creative Commons Attribution 3.0 Unported License URL: http://creativecommons.org/licenses/by/3.0/ --> <!DOCTYPE html> <html> <head> <title>Creative Colorlib SignUp Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- Custom Theme files … -
Is there default logging for an errors?
I'm new to Django and programming and failed to write loggers for my application. Is there a way to get all the default errors that come up with out explicitly capturing them with a logger. Maybe this is a basic question and just not true. For instance, I try to run my application and a ValueError comes up like: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.3 Exception Type: ValueError Is there a way for this to log this without having wrapping the logger output around that specific function. -
Django - How to add items to Bootstrap dropdown?
For some background I'm using Django and Bootstrap to build a to-do list as a side project. The issue I'm having is that I can't add items to the dropdown list. I want to have a dropdown to have a list of people's names but when i try to add them to the dropdown they do not appear. this is my view. As you can see I'm passing a list of names as an example. def index(request): form = TodoForm() people = ['person1', 'person2', 'person3'] if request.user.is_authenticated is False: return render(request, 'main/index.html', {'todo_list': [], 'form': form}) user = User.objects.get(pk=request.user.id) todo_list = user.todo_set.all().order_by('id') return render(request, 'main/index.html', {'todo_list': todo_list, 'form': form, 'people': people}) This is dropdown which I got from Bootstrap: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Remind others </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for person in people %} <a class="dropdwon-item" href="#">{{ person }}</a> {% endfor %} </div> </div> When I run this code, I do see the dropdown button but when I clicked, it drops down but it doesn't show any names. It's just a blank dropdown. I know the dropdown list work because when I run the code below it works perfectly. <div class="dropdown"> <button … -
Passing and element form DetailView into CreateView in django
Am Building this voting playform where voters can simply pay for vote cast for a candidate. Am having problem biding a selected candidate to the VoteAmount model I display all the nomination list but i can't get the selected candidate bid into a form in createview to save into database model.py class Award(models.Model): STATUS_PUBLISHED = ( ('Closed', 'Closed'), ('Opened', 'Opened'), ) slug = models.SlugField(max_length=150) name = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='award_images') status = models.CharField(max_length=20, choices=STATUS_PUBLISHED, default='Closed') def __str__(self): return self.name class Category(models.Model): Award = models.ForeignKey(Award, on_delete=models.CASCADE) category = models.CharField(max_length=100,) slug = models.SlugField(max_length=150) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.category class Nomination(models.Model): Fullname = models.CharField(max_length=120) Category = models.ForeignKey(Category, on_delete=models.CASCADE) votes = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=150) image = models.ImageField(upload_to='nominations_images') def __str__(self): return self.Fullname class VoteAmount(models.Model): Nominee = models.ForeignKey(Nomination, on_delete=models.CASCADE) votes_amount = models.IntegerField(default=0) def __str__(self): return self.votes_amount Views.py class AwardView(ListView): template_name = 'award.html' context_object_name = 'award_list' queryset = Award.objects.filter(status='Opened').order_by('-date') class CategoryView(DetailView): model = Award template_name = 'category.html' class NominationView(DetailView): model = Category template_name = 'nomination.html' class VoteAmountView(DetailView): model = Nomination template_name = 'voteamount.html' class AmountView(CreateView): template_name = 'voteamount.html' form_class = VoteAmountForm class PaymentView(DetailView): model = VoteAmount template_name = 'PaymentView.html' form.py class VoteAmountForm(forms.ModelForm): class Meta: model = VoteAmount fields … -
How to send mail to admin email address for withdrawal in django?
I am working on a project. For each user there is payment and I want to make a withdraw option for user whenever he/she needs a payment, they write the amount they need and click on withdraw button. But I don't know how to send email to admin page to make aware admin that he/she needs money and you should send him/her. How to do it? Especially the one I have commented. -
PYTHON 3.7.4 NOT USING SQLITE 3.29.0
OS/Software installed: root@TACIT admin]# cat /etc/*release* CentOS Linux release 7.6.1810 (Core) root@TACIT admin]# python3.7 --version Python 3.7.4 [root@TACIT admin]# sqlite3 --version 3.29.0 2019-07-10 17:32:03 fc82b73eaac8b36950e527f12c4b5dc1e147e6f4ad2217ae43ad82882a88bfa6 (T3PSA) [root@TACIT src]# django-admin --version 2.2 Software locations: [root@TACIT admin]# which python3.7 /usr/local/bin/python3.7 [root@TACIT admin]# which sqlite3 /usr/bin/sqlite3 (T3PSA) [root@TACIT src]# which django-admin /root/.local/share/virtualenvs/T3PSA-6bzDXn0f/bin/django-admin I compiled Python 3.7.4 from source and installed following these instructions without any problems: https://tecadmin.net/install-python-3-7-on-centos/ I upgraded from Sqlite 3.7.17 to Sqlite 3.29.0 following these instructions without any problems (other than I had to install some additional ".so" libraries): https://linuxhint.com/upgrade-to-latest-sqlite3-on-centos7/ Unfortunately Python 3.7.4 is still using the old version of Sqlite3 (3.7.17): [root@TACIT admin]# python3.7 Python 3.7.4 (default, Aug 16 2019, 16:34:12) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.sqlite_version '3.7.17' I'm using Django and need it to run at least v3.8.3 (see the very end of the following output): (T3PSA) [root@TACIT src]# python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/root/.local/share/virtualenvs/T3PSA-6bzDXn0f/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/.local/share/virtualenvs/T3PSA-6bzDXn0f/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/root/.local/share/virtualenvs/T3PSA-6bzDXn0f/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
Allow CustomUser staff member to create new users in Django admin
I'm creating a new CustomUser to extend the current User and add some new fields. My problem is that I want to allow to staff members to add new users without see the create Group in the admin view, but when I tried to give some perms to the staff member this show all the fields (Group and CustomUser) in my admin view. Is there any way to show only the CustomUser field in the staff session? models.py from django.contrib.auth.models import AbstractUser from django.db import models from core.models import University, Campus, School, Career from core.models import Country, Region, City from django.core.validators import RegexValidator from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Los usuarios deben tener un Email') user = self.model( email=self.normalize_email(email), ) user.is_staff2 = False user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser,PermissionsMixin): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) rut = models.CharField(verbose_name="Rut",max_length=8, null=True, blank=True, … -
I need help,How to transfrom object via celery
I want use celery upload image ,but there have some error. Object of type InMemoryUploadedFile is not JSON serializable please help me ,thank you very much. class UserViewSet(CusModelViewSet): queryset = UserProfile.objects.all().order_by('-last_login') serializer_class = UserSerializer pagination_class = PageSet def create(self, request, *args, **kwargs): data = request.data serializer = self.get_serializer(data=data) if serializer.is_valid(): self.perform_create(serializer) image = data self.upload_files.delay(image) return json_response(serializer.data, status.HTTP_200_OK, '创建成功!') return json_response(serializer.errors, status.HTTP_400_BAD_REQUEST, get_error_message(serializer)) EncodeError at /get_data/users/ Object of type InMemoryUploadedFile is not JSON serializable Request Method: POST Request URL: http://127.0.0.1:8000/get_data/users/ Django Version: 2.1.7 Exception Type: EncodeError Exception Value: Object of type InMemoryUploadedFile is not JSON serializable Exception Location: /usr/local/lib/python3.7/dist-packages/simplejson/encoder.py in default, line 273 Python Executable: /media/morgan/project/develop/WebOnline/venv/bin/python Object of type InMemoryUploadedFile is not JSON serializable -
Cannot Import name from myapp.models
I am using django 2.2.4 and python 3.7.3 When I try to import anything from forum.models into gallery/models.py , I get importError: cannot import name 'Project' from 'forum.models', but it works fine the other way around (importing from gallery.models into forum/models.py. ├── db.sqlite3 ├── forum │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ └── views.py ├── gallery │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── tests.py │ └── views.py ├── makerplatform │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py With that said, I tried this in gallery/models.py: import forum.models as m print(m.__dir__()) and its when I run manage.py runserver: ['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__file__', '__cached__', '__builtins__', 'models', 'User', 'post_save', 'receiver'] Notice that User,post_save, and receiver are all modules I imported into forum/models.py. I also tried importing forum.models in the django shell, and it works fine. Thanks in advance for any help. -
Django Download file specfic file
I have generated the file and saved in the following directory: project/media/ following code is setup, but not able to download the file from the media. Not able to download, Can you help, thank you Files are generated and upload to MEDIA folder, Inside the folder there are multiple files. VIEW.py file_list = ['file1','file2','file3'] def download(request): file_path = os.path.join(settings.MEDIA_ROOT, '/') response = "" if os.path.exists(file_path): for file in file_list: if 'data1' in request.POST and 'file1' in file: file_wrapper = FileWrapper(file(file_path,'rb')) file_mimetype = mimetypes.guess_type(file_path) response = HttpResponse(file_wrapper, content_type=file_mimetype ) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(file) return response HTML <form method="POST" id="data1"> {% csrf_token %} ... </form> <button id="data1" type="submit" name="download" class="card-link">Download</a> URL.py urlpatterns = [ path('download', views.download, name='download'),] -
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table
I am 'Dockerizing' my Django project and I am facing the following issue when applying migrations on my container: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "web_accountant" This is my model: from django.contrib.auth.models import User class Accountant(User): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now=True) I tried adding id = models.BigIntegerField(primary_key = True) as suggested in this post with no success. I also tried extending the Django User model another way (one to one field) but the error persists. What am I doing wrong here? -
ProgrammingError: relation " " does not exist
I am creating a web app using Django 2.2 and it is working in production on heroku with a couple of models already in place. Today I added in a third model, and I can still load the site in production but when I try to access a url that uses the third model I get the error as per the title. I have run python manage.py makemigrations and python manage.py migrate. The app also works perfectly in local host server, so it must have someting to do with the database on heroku? I'm using sqlite 3. error ProgrammingError at /calculus_tool/ relation "calctool_function" does not exist LINE 1: ...nction"."id", "calctool_function"."equation" FROM "calctool_... ^ Request Method: GET Request URL: ---REMOVED---(exists on my error page) Django Version: 2.2.3 Exception Type: ProgrammingError Exception Value: relation "calctool_function" does not exist LINE 1: ...nction"."id", "calctool_function"."equation" FROM "calctool_... ^ Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 84 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages', '..'] Server time: Fri, 16 Aug 2019 22:03:23 +0000 Views from django.shortcuts import render,redirect from django.http import HttpResponse # we can set post formats in the models directory from .models import Function # import post views … -
Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
when I try to log-in Django admin panel using my superuser id & pass a runtime-error appears"Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." What to do ? I have tried adding 'django.contrib.sites', in INSTALLED_APPS & SITE_ID = 1 as shown in some solutions but it didn't work. my settings.py looks like this INSTALLED_APPS = [ 'newsfeed', 'user_profile', 'django.contrib.sites', 'Alumni_Portal.apps.AlumniPortalConfig', 'django.contrib.admin', 'django.contrib.auth', #'django.contrib.sites', 'django_extensions', 'django.contrib.contenttypes', #'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'NSU_Alumni_Portal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` -
Clean database in production
I successfully deployed my website on Linode on a Ubuntu server. I am using Postgres for database. I can perform all the actions correctly. However, I would like to clean my database (deleting all the users, posts, files, etc. that I created for my "in production" testing). I generally use: python manage.py flush when I want to clean my database of all of its elements (not tables) in development. Can I use the same command in production using the bash on my Ubuntu server? Or is there another way? -
How do I write a Django query with "icontains" and another condition?
I'm using Django and Python 3.7. I want to write a query that checks if the "created_by" column is not null and scans theh "title" field to see if it includes various words. I tried this def get_articles_with_words_in_titles(self, long_words): qset = Article.objects.filter(created_on__is_null=False, reduce(operator.or_, (Q(title__icontains=x) for x in long_words))) result = set(list(qset)) return result but I'm getting an error Positional argument after keyword argument Something about the way I have written my multiple conditions. What's the right way to write the conditions? -
How do I write a Django query that finds words in a Postgres column?
I'm using Django and Python 3.7. How do I scan for words in a Django query? A word is a string surrounded by whitespace (or the beginning or end of a line). I have this ... def get_articles_with_words_in_titles(self, long_words): qset = Article.objects.filter(reduce(operator.or_, (Q(title__icontains=x) for x in long_words))) result = set(list(qset)) but if "long_words" contains things like ["about", "still"], it will match Articles whose titles have things like "whereabouts" or "stillborn". Any idea how to modify my query to incorporate word boundaries? -
Questionnaire modeling
I am making a questionnaire app and am looking for a way to best represent a user answer. So far after looking at a bunch of survey apps online this is the general modeling I have come up with: A questionnaire is a collection of questions A questionnaire run associates a questionnaire with a user with a collection of answers taken at a certain time A question is a label, type and possible options An answer is a label, value and possible score, associated with a question, indicating whether it was defined by the user (to be used as an option for multiple choice question types or to store a user's text input answer) A run_answer associates a questionnaire_run and question with all the answers for that question and most importantly it associates an answer group which is needed for array/matrix type questions where the user can possibly add another of a particular type of question such as: "Add another medication" where every row added prompts the user to answer a series of questions related to the selected medication. So: which medication do you take?, how often is it taken?, How does it help?, etc... This way I know "How … -
Customizing user model and forms in django
I'm trying to set up a custom user using AbstractUser with a couple more added fields, but when I check the add user form in the site admin, the form fields appear in different order (password, groups and user permissions first, then the username, etc.) In my settings I have registered the AUTH_USER_MODEL to my custom User class. I have a user class with a cople of test fields, when I run it the fields appear in the order specified above. Then I created a CustomUserCreationForm and a CustomUserAdmin to try and order the fields, but then it only ended up showing only user and password. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) forms.py from django.contrib.auth.forms import UserCreationForm from .models import User class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'password', 'bio', 'location', 'birth_date') admin.py from django.contrib import admin from .models import User from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm admin.site.register(User) #This one shows all the fields scrambled #admin.site.register(User, CustomUserAdmin) #This one only shows 3 fields on the creation (user, … -
dynamically place file in s3 when creating a new Model in Django
When I create a new model "Truck" in Django one of my fields is a FileField which saves files to S3. I want to place this file in a folder that matches my model instance. When I save a new instance of Truck, for instance "Red Truck" I want to upload the file to a folder in S3 called "Red Truck". This is for keeping documentation neat at my company. from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.template.defaultfilters import slugify class Truck(models.Model): @staticmethod def pre_save(sender,instance,**kwargs): s3_truck_name = self.truck_number truck_number = models.CharField(max_length=20) vin = models.CharField(max_length=17) registration = models.FileField(upload_to=f'trucks/{s3_truck_name}') cab_card = models.FileField(upload_to=f'trucks/{s3_truck_name}') title = models.FileField(upload_to=f'trucks/{s3_truck_name}') def __str__(self): return f'Truck: {self.truck_number}' pre_save.connect(Truck.pre_save, Truck) NameError: name 's3_truck_name' is not defined -
Context manager to assert no database queries are issued in a block
How can I write a context manager that, in test/dev, asserts that there are no database queries in its block? The goal here is to force usage of select_related/prefetch related, and make it an error to forget to do so. Eg, given these models: class SomeSingleThing(models.Model): somefield = models.IntegerField() someotherfield = models.CharField(max_length=42) class SomeManyThing(models.Model): parent = models.ForeignKey(SomeSingleThing) This should raise an exception, because select_related is missing, and so a query gets performed inside the forbidden zone: obj = SomeSingleThing.objects.get(pk=1) with forbid_queries(): val = obj.parent.somefield # => exception And this should not, because we selected everything we needed: obj = SomeSingleThing.objects.select_related('parent').get(pk=1) with forbid_queries(): val = obj.parent.somefield # no exception -
How to get the Datetime when a task is marked as done in Django?
I'm developing a maintenance app, I can add tasks and get the exact time when it was created by implementing this: created_date = models.DateTimeField(db_column='Date', auto_now_add=True) # Field name made lowercase. I have a field called done: done = models.BooleanField(db_column='Done', default=False) # Field name made lowercase. Now what I need is to, when I set the done to 'True' it gives me the date and time at that moment, how can I achieve this? Thanks