Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the implication of using request.user over self.request.user
I want to know the major difference between self.request.user (when using generic view View) and request.user (when using a user defined view), at times when I use django's generic View (django.views.generic import View) which has access to the django User model, I'd interact with the authenticated user as request.user and self.request.user without having any problem. For instance, in a django views.py: from django.contrib.auth import get_user_model User = get_user_model() class GetUserView(View): def get (self, request, *args, **kwargs): user_qs = User.objects.filter(username=request.user.username) #Do some other stuffs here class AnotherGetUserView(View): def get(self, request, *args, **kwargs): user_qs = User.objects.filter(username=self.request.user.username) #Do some other stuffs here I realize that the two queryset works fine but I can't still figure out the best to use. -
python Bad Request: /emails
I am trying to make an email web app using python but when I try to press the submit button to send the email this is what I get: [08/Dec/2021 15:26:26] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails [08/Dec/2021 15:26:38] "POST /emails HTTP/1.1" 400 61 Bad Request: /emails ``` Please help! -
How can I solve server error 500 which I am getting during django app deployment on heroku?
When I set debug equals to false my app doesnot work on both local n live env but when I set debug equals true it works all right in local env but gives same server 500 error on live env. This is the github repo for my django project: [https://github.com/Pran1001/HomeFinder] and settings.py file : https://github.com/Pran1001/HomeFinder/blob/main/HOMEFINDER/settings.py below are the logs which I am get from running heroku logs command 2021-12-08T15:01:27.896609+00:00 heroku[router]: at=info method=GET path="/" host=searchyourghar.herokuapp.com request_id=a4b3fa9d-2551-402e-b7ca-5c41c94fbb50 fwd="49.32.177.39" dyno=web.1 connect=0ms service=21ms status=500 bytes=409 protocol=http -
File upload returns no HTTP status
I have a Django / React application hosted in AKS. React's build is hosted statically with Nginx. The Nginx container is exposed through a ClusterIP, Ingress & Nginx-Controller. The In this app, I'm doing a file upload, which returns nothing. Not an error, not an HTTP status code, nothing. That makes debugging very hard. This doesn't happen locally, and it only happens with files bigger than approx 10mb. Already increased the client_max_body_size in the default.conf of the nginx host. Can't find anything in the Controller docs that indicates a too large filesize, and this would also result in a HTTP 413. Anyone familiar with this? In React I simply use axios with formData: let formData = new FormData(); axios.post(`${API_SERVER}/builds`, formData).then(response => { console.log(response); }).catch(error => console.log(error)); The HTTP response: undefined undefined undefined date: Wed, 08 Dec 2021 15:27:35 GMT content-type: text/html content-length: 176 strict-transport-security: max-age=15724800; includeSubDomains X-Firefox-Spdy: h2 -
Cannot successfully pass foreign_key reference to PUT request in Django REST
I am getting into Django REST and I am trying to use it for a backend of type of crypto currency tracker for my use. However I have been stuck on an issue for a few days.. I have the following models.py: class Coin(models.Model): sign = models.CharField(max_length=50, primary_key=True) # capitalize all entries name = models.CharField(max_length=50, null=False) amount = models.DecimalField(max_digits=20, decimal_places=2, null=False) price_each = models.DecimalField(max_digits=20, decimal_places=2, null=False) purchased_on = models.DateField(null=True) def __str__(self): return self.sign def save(self, *args, **kwargs): self.sign = self.sign.upper() return super(Coin, self).save(*args, **kwargs) class Price(models.Model): coin = models.ForeignKey(Coin, related_name="prices", on_delete=models.CASCADE) day_date = models.DateField(null=False) current_price = models.DecimalField(max_digits=20, decimal_places=2, null=False) def __str__(self): timestamp = self.day_date.strftime("%d-%b-%Y") return timestamp and serializers.py: class PriceSerializer(serializers.ModelSerializer): coin_sign = serializers.PrimaryKeyRelatedField(queryset=Coin.objects.all(), source='coin.sign') class Meta: model = Price fields = ['id', 'day_date', 'current_price', 'coin_sign'] def create(self, validated_data): return Price.objects.create(**validated_data) class CoinSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True, read_only=False) class Meta: model = Coin fields = ['sign', 'name', 'amount', 'price_each', 'purchased_on', 'prices'] def create(self, validated_data): return Coin.objects.create(**validated_data) I am having trouble defining a view with PUT to create a new price entry in view.py: class AddPrice(APIView): def put(self, request, sign, format=None): coin = get_object_or_404(Coin, sign=sign.upper()) request.data['coin_sign'] = coin serializer = PriceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the … -
How to get Todo items with today as deadline
so i'm still creating my todo list app, and i want to render all the items that has todays date as the deadline so as to remind the user of the pending tasks. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class ToDo(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) todo = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True) created = models.DateField(auto_now=True) end = models.DateField() start = models.DateField() completed = models.BooleanField(default=False) def __str__(self): return f'{self.owner} - {self.todo}' views.py def index(request): activities = ToDo.objects.all() today = ToDo.objects.get(end=datetime.date.today) todo = ToDo.objects.count() complete = ToDo.objects.filter(completed=True).count() percent = complete * 100 // todo if request.method == 'POST': try: search = request.POST.get('todo') activities = ToDo.objects.filter(todo__icontains=search) except: search = request.POST.get('end') activities = ToDo.objects.filter(end=search) context = { 'activities' : activities, 'percent' : percent, 'today' : today, } return render(request, 'home.html', context) i imported datetime in my views.py -
Title cannot contain "Ask a public question". Please provide a title that summarizes your question. For assistance, see: How do I ask a good question?
A standard blockquote is indented A nested blockquote is indented more You can nest to any depth You can nest to any depth -
ManyToMany Model query
I have 2 models Project and Investor Project model has a field called project_investors with a ManyToMany to the Investor model. Models class Investor(models.Model): investor_name = models.CharField(max_length=50, blank=False, unique=True) investor_website = models.URLField(max_length=100, blank=True) investor_portfolio_website = models.URLField(max_length=100, blank=True) investor_description = models.TextField(blank=True) investor_investments = models.TextField(blank=True) def __str__(self): return str(self.investor_name) class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) project_investors = models.ManyToManyField(Investor, blank=True) def __str__(self): return str(self.project_name) I then have a page the shows the Investor details and im trying to show which projects have been linked to this investor. myview.py @login_required def show_investor_details(request,investor_id): investor = Investor.objects.get(pk=investor_id) form = InvestorForm(request.POST or None, instance=investor) project = Project.objects.all() project_list = get_object_or_404(Project, project_investors=investor_id) return render(request, 'pages/investor_details.html', {"investor": investor, "form": form,"project": project,'project_list':project_list}) Im not sure what is the correct query to pass in here project_list = get_object_or_404(Project, project_investors=investor_id) as this error is thrown: 'Project' object is not iterable Or maybe I have the model structure incorrect? -
Reverse for 'delete_post' with arguments '('',)' not found. 1 pattern(s) tried: ['article/(?P<pk>[0-9]+)/remove$']
i was creating a simple blog site and I created buttons to delete7edit , but as soon as I try to reset the app and go there I get this error ( title ) this is my code view.py: from django.views.generic import ListView from . models import Article from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import PostForm, EditForm from django.urls import reverse_lazy class ArticleListView(ListView): model = Article template_name = 'home.html' class ArticleDetailView(DetailView): model = Article template_name = 'detail.html' class AddPostView(CreateView): model = Article form_class = PostForm template_name = 'add_post.html' #fields = '__all__' #fields = ('title', 'body') class UpdatePostView(UpdateView): model = Article form_class = EditForm template_name = 'update_post.html' #fields = ['title', 'title_tag', 'body'] class DeletePostView(DeleteView): model = Article template_name = 'delete_post.html' success_url = reverse_lazy('home') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.ArticleListView.as_view(), name='home'), path('article/<int:pk>', views.ArticleDetailView.as_view(), name='detail'), path('add_post/', views.AddPostView.as_view(), name='add_post'), path('article/edit/<int:pk>', views.UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', views.DeletePostView.as_view(), name='delete_post'), ] help me please, I'm new on django and i don't know things yey -
Product matching query does not exist
i'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a Page Not Found error "No Order matches the given query." Bellow you can check the code Models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255, unique=True, ) description = models.TextField(max_length=1500) class Meta: verbose_name_plural = "categories" def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) Views.py class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data() form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Order, product__name=self.kwargs['product_name']) customer = form.save(commit=False) Order.objects.create(product=product, customer=customer) form.save() return super(TemplateView, self) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context forms.py class OrderForm(forms.ModelForm): class … -
Django: I get: Cannot query "admin": Must be "Follow" instance in my code when trying to implement unfollow button
I'm a beginner and I'm trying to create a small network project in which users can follow each other. I have implemented the follow button right, so it updates my models and displays proper info to users, but I can't get unfollow to work properly. I'm guessing it's something to do with the way I implemented follow model (with many to many field), but I'd like to implement it this way for practice... Anyhow, here's the code: Models: class User(AbstractUser): pass class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_follow") following = models.ManyToManyField(User, blank=True, related_name="followers") And view: def users(request, username): """Displaying user profiles""" if request.method == "POST": user = request.user profile = User.objects.get(username=username) follow = Follow(user=user) follow.save() if "unfollow" in request.POST: profile.followers.remove(user) follow.following.remove(profile) return HttpResponseRedirect(reverse('users', args=(username,))) elif "follow" in request.POST: follow.following.add(profile) return HttpResponseRedirect(reverse('users', args=(username,))) This code yields in: "ValueError at /users/test Cannot query "admin": Must be "Follow" instance." at the profile.followers.remove(user) line... Playing with it in shell I found out (at least I think so) that the line under it (follow.following.remove(profile) - which by the way was there before I tried with the profile.followers.remove(user)) removes the profile from Follow model, but for some reason it is not by itself updated in the … -
How to fet a queryset for every object in queryset
Let's assume I have an Employees model. There are 3 different titles such as "Top manager", "Sales manager" and "Sales representative" and field "reports_to". Top manager doesn't report to anyone, Sales managers report to Top and Sales representatives report to Managers. I have a list view to see employees list, it shows employees who reports to higher employee as described above. Also I try to list employees who reports to those who report to me. Like (I'm logged in as a Top manager) --Here goes Sales manager ----Here goes this manager's Sales representatives So far I achieved getting manager's representatives, but only for the first manager in the queryset. The question is: how do I get separate querysets of Representatives for every Manager in queryset? Additional question: am I right in using prefetch_related() here? View: def get_current_users_employee(user): try: employee = Employees.objects.get(user=user) return employee except User.DoesNotExist: raise Http404("Employee doesn't exist for this user.") class EmployeesListView(LoginRequiredMixin, ListView): model = Employees template_name = 'employees/employees_list.html' context_object_name = 'employees_list' fields = ['last_name', 'first_name', 'title', 'birth_date', 'reports_to'] def dispatch(self, request, *args, **kwargs): handler = super().dispatch(request, *args, **kwargs) emp = get_current_users_employee(self.request.user) if (emp.title == "Sales representative"): raise PermissionDenied return handler def get_queryset(self): current_emp = get_current_users_employee(self.request.user) return super().get_queryset().filter(reports_to=current_emp) … -
how to perform Rank query in Django
I am stuck at this point and this query seems a bit tricky to me so basically i am getting data from devices in periodic intervals 'lets say 3 hours' But every device is sending data twice on every interval(3 hours), i am required to extract data that is send last(in intervals) "date": "2021-11-28", "time": "12 : 35", "meter": "70F8E7FFFE10C495", "dr": 3, "date_received": "2021-11-28T18:05:20.473430+05:30", }, { "id": 2, "date": "2021-11-28", "time": "12 : 37", "meter": "70F8E7FFFE10C459", "date_received": "2021-11-28T18:07:09.980403+05:30", }, { "id": 3, "date": "2021-11-28", "time": "12 : 37", "meter": "70F8E7FFFE10C459", "dr": 3, "date_received": "2021-11-28T18:07:11.533388+05:30", }, { "id": 4, "date": "2021-11-28", "time": "12 : 50", "meter": "70F8E7FFFE10C463", "date_received": "2021-11-28T18:20:44.197284+05:30", }, { "id": 5, "date": "2021-11-28", "time": "12 : 56", "meter": "70F8E7FFFE10C47D", "date_received": "2021-11-28T18:26:43.221316+05:30", }, { "id": 6, "date": "2021-11-28", "time": "12 : 56", "meter": "70F8E7FFFE10C47D", <---- only want to get this occurrence "date_received": "2021-11-28T18:26:44.925292+05:30", }, So if device : 70F8E7FFFE10C459 sends data twice i want to retrieve only last sent data , and this needs obj in queryset , i was told about RANK concept don't understand how to apply that here -
Django mysql query to queryset
i really want to change select u.name, p.id, p.title, p.keyword_id, (SELECT count(id) FROM postings where user_id = u.id) as total_posting from users u JOIN postings p ON p.user_id = u.id where p.keyword_id = 14 this mysql query to django queryset... help me :/ elements are from users.models import User from postings.models import Posting from django.db.models import Count,Subquery ... helllppppp plzzz ㅜ,ㅜ -
How to mock and test a django view including external api call
I want to test a django view which includes a call to an external API. The API call is wrapped up by another package (jira). When the view is called a jira ticket is created for a Project (model). How would I properly test the view while preventing that the external API is called. The view looks like this: class RequestHelp(View): def get(self, context, pk=None, **response_kwargs): # get the project to create the ticket for project = Project.objects.get(id=pk) # initialize the jira client jira = JIRA( server=settings.JIRA_URL, basic_auth=(settings.JIRA_USERNAME, settings.JIRA_PASS), ) # create the ticket in jira new_issue = jira.create_issue( project=settings.JIRA_PROJECT, summary= project.title , description="Would you please be so nice and help me", reporter={"name": "My User"}, issuetype={"name": "An Issue"}, ) return HttpResponseRedirect("/") The test at the moment looks like this: class TestRequestHelp(TestCase): @classmethod def setUpTestData(cls): cls.std_user = User.objects.create_user( username="john", email="john@doe.de", password="secret", is_staff=False, is_superuser=True, ) def test_get_help_logged_in(self): self.client.login(username="john", password="secret") project, status = Project.objects.get_or_create(title="Test") response = self.client.get(f"/project/help/{project.pk}", follow=True) self.assertEqual(200, response.status_code) A "normal" test of the view works but always creates a ticket which is not desirable. Any help with this would be appreciated. -
How can I autofill a field in my django form in class based view?
I create an opportunity for users to comment on the book. I have a list of books, where all the books in the database are placed, and also a detail book for each book. I created a form for the possibility of commenting in detail book, where I pass various fields, but some I want to be autofilled not by the users themselves, such as the title of the book and the author. I managed to do it with the author, but the title of the book does not work. I would be grateful if you can help with this. models.py import uuid from django.db import models from django.db.models.enums import TextChoices from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User class Genre(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) image = models.ImageField( upload_to="photos", default=None, blank=True, null=True) author = models.ForeignKey("Author", on_delete=models.SET_NULL, null=True) summary = models.TextField() isbn = models.CharField(max_length=10, unique=True, blank=True, null=True) genre = models.ManyToManyField("Genre", related_name="book_genre") publisher = models.ManyToManyField("Publisher") languages = models.ManyToManyField("Language") publication_date = models.DateTimeField(default=timezone.now) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_detail", kwargs={"pk": self.pk}) class Meta: ordering = ["-created_date"] constraints = [ models.UniqueConstraint( fields=["title"], … -
"depth" in django rest framework: How to access values?
Here my requirement is to access values in the below structure which is get by using "depth" in the serializer. serializers.py class Meta: model = Course fields = ("is_favorite", "backgroundcolor", "instructor", "instructor_rating", "review_status", "id", "name", "description", "is_free", "image", "keyarea", "subject", "course_type", "beneficiary", "section", "datetime_created", "general_status", "review_status", "difficulty", "publish_date", "enrollment", "revenue", "category", "created_by", 'last_modified_by', 'course_rating', 'enrollment_type', 'expiry_data', "course_banner") depth = 3 The result structure: { "status": 200, "data": { "course": { "is_favorite": false, ..... ..... ..... "section": [ { "id": "5bf83a1c-e240-4907-9f71-e449644860b1", "deleted": null, "datetime_created": "11/29/2021 09:33 AM", "datetime_updated": "11/29/2021 09:33 AM", "name": "section1", "code": "22833", "description": "Description", "is_locked": true, "is_free": true, "modules": [ { "id": "0e82f2a5-6365-4206-b9e3-cd4e8e54f16c", "deleted": null, "datetime_created": "11/29/2021 09:32 AM", "datetime_updated": "11/29/2021 09:32 AM", "name": "module1", "description": "Description", "is_free": true, "videos": [ { "id": "8c7e70ec-703d-4c07-97ff-c69202451de8", "deleted": null, "datetime_created": "11/29/2021 08:05 AM", "datetime_updated": "11/29/2021 08:05 AM", "video_name": null, "description": null, "duration": "03:20:00", "create_date": "11/29/2021 08:05 AM", "video_type": "micro", "file_url": "https://vimeo.com/369126918", "general_status": "High", "review_status": "Draft", "created_by": null }, { "id": "ec4e3ce7-69e9-45d6-b00f-60f0012044bb", "deleted": null, "datetime_created": "11/29/2021 08:02 AM", "datetime_updated": "11/29/2021 08:02 AM", "video_name": null, "description": null, "duration": "00:01:40", "create_date": "11/29/2021 08:02 AM", "video_type": "micro", "file_url": "https://vimeo.com/369126918", "general_status": "High", "review_status": "Draft", "created_by": null } ] } ] } ], ...... ...... }, "success": … -
Python & Django - 'ModuleNotFoundError: No module named 'GoalCategoryTest'' when trying to import TestCase
So I have this TestCase file CategorySearchTest.py class CategorySearchTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.access_token = get_test_user_access_token() cls.user = get_or_create_test_user_in_DB() cls.goal_category_name_list = ['Health', 'Fitness', 'Art', 'Relationships', 'Artist'] I'm trying to import this in the init.py file in the same folder so I can run all the tests in this folder with the command python manage.py test <root>\test\CategoriesTest. my __init__.py file looks like this from GoalCategoryTest import * then here's my folder structure I'm getting the error from my __init__.py file which is ModuleNotFoundError: No module named 'GoalCategoryTest'. Why is this happening? I've tried from GoalCategoryTest import * and import GoalCategoryTest and both give the same error. -
how i can set the margin-left of the page to don't let the data spread along the width of the paper
Am newbie and am trying to use the library "reportlab" to generate the PDF, I want to fix the margin-left of the page but i did'nt know how i can do that : this is my code: c = canvas.Canvas(buf, bottomup=0) c.translate(inch,inch) textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 6) posts = Post.objects.all() lines = [] for post in posts: lines.append(post.title) lines.append(post.content) This is how it looks like : enter image description here But what i want is to fix the margin left -
Django - Show list datetime values in template
I have below code which outputs datetime values as shown below: available_hours = [hour for hour in hours_between if hour not in reserved_times] print(available_hours) [datetime.datetime(2021, 12, 8, 12, 0), datetime.datetime(2021, 12, 8, 13, 0), datetime.datetime(2021, 12, 8, 14, 0), datetime.datetime(2021, 12, 8, 16, 0), datetime.datetime(2021, 12, 8, 17, 0), datetime.datetime(2021, 12, 8, 18, 0), datetime.datetime(2021, 12, 8, 19, 0), datetime.datetime(2021, 12, 8, 20, 0), datetime.datetime(2021, 12, 8, 21, 0)] I render them in the template like: {{ available_hours }} and i got all above datetime values. How can i change the format so i can show them like Mon 12 2021, 21:00? Thank you -
django cascade delete on 2 foreign keys of the same table
I have a model A and model B. Model B has 2 foreign keys to model A as shown. There is a 1 to many relationship between Model A to B such that a dataset (A) can have multiple data elements(B). Model A: id (primary key) dataset_id dataset_version dataset_name Model B: id (primary key) dataelement_id dataelement_version dataelement_name fk_dataset_id fk_dataset_version My question is: How to cascade delete a row from Model A such that the deletion occurs on Model B using fk_dataset_id and fk_dataset_version together ? Currently, django runs 2 separate queries to delete data from Model B on columns fk_dataset_id and fk_dataset_version but I want the deletion query to use an AND condition for deletion for e.g. DELETE from model B where B.fk_dataset_id = 1 AND B.fk_dataset_version = 3 Iam using a django rest framework with ModelViewSet for both Model A and B -
How to skip validation in django model serializers?
Its a general question. I have a code where I have implemented the validation of the serializer. Now when I make a post request and validate the data by is_valid function, it should run the validate method. But when I make a patch request it validates the data again. I want to skip this part because in my validate function I am validating data using some fields which are sent by the client during the post request but not during the patch request. I am not sure how to deal with this. Can someone help me with this ? -
Django ORM using external database to unmanaged model in view says relation does not exist
I have two Postgres database connections and when using another than default ORM calls fail on views, but not raw. I am using docker and containers are connected and using Django's own runserver command. Using ORM in django command or django shell works fine, but not in a view. As a side note, both databases are actually Django-projects, but main project is reading some data directly from another project's database using own unmanaged model. Python: 3.9.7 Django: 3.2.10 Postgres: 13.3 (main project), 12.2 (side project) # settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'pguser', 'PASSWORD': 'pguser', 'NAME': 'mainproject', 'HOST': 'project-db', # docker container 'PORT': '5432', }, 'external': { 'ENGINE': 'django.db.backends.postgresql', 'USER': 'pguser', 'PASSWORD': 'pguser', 'NAME': 'sideproject', 'HOST': 'side-db', # docker container, attached to same network 'PORT': '5432', }, } # My unmanaged model class MyTestModel(models.Model): class Meta: # table does not exist in 'default', but it does exist in 'external' db_table = 'my_data_table' managed = False # my_data_table is very simple it has id field as integer # and primary key (works out of the box with django) # it has normal fields only like IntegerField or CharField # But even if this model is empty then … -
Update inheritance for multiple objects using django signal
I am implementing django signals to update a model which has been inherited by multiple other models. For instance, class A: name = models.CharField(max_length=199, blank=True, null=True) class B(A): id = models.PositiveIntegerField() class C(A): id = models.PositiveIntegerField() class D(A): id = models.PositiveIntegerField() If there are any changes upon save, I want to perform an operation. My implementation for Signal is as follows: @receiver(post_save, sender=B) def base_update(sender, instance, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: # raise an error else: # do something At the moment, it works for B , but if I consider rest of the models I'd end up replicating the same function with different sender names. Is there a way to make a generic Signal that applies to all the models that inherits A ? -
How to Make a div fit A4 page
I have a django admin action function that display Transactions and loops through as many as queryset selected that will be rendered in html page, and converts the html to pdf. I want at the pdf that each transaction object fit in A4, not to have another transaction object in same page. here is code.. def report_pdf(self, request, queryset): if request.user.is_superuser: transaction = queryset else: transaction = queryset.filter(user=request.user) template_path = "single-pdf.html" context = {"transactions": transaction} template = get_template(template_path) html = template.render(context) file = open('test.pdf', "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() file.close() return HttpResponse(pdf, 'application/pdf') and here is my html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Report</title> <style> </style> </head> {% for transaction in transactions %} <body> <div class="container"> {% if transaction.complete %} <table class="tg" > <thead> <tr> <th class="tg-4rlv">Report for Tenant</th> </tr> </thead> <tbody> <tr> <td class="tg-c6of" CHP Reference</span></td> <td class="tg-c6of">{{transaction.chp_reference}}</td> </tr> <tr> <td class="tg-c6of"> Rent Effective From(dd/mm/yyyy)</td> <td class="tg-c6of">{{transaction.rent_effective_date}}</td> </tr> <tr> <td class="tg-c6of"> CRA Fortnightly Rates valid for 6 months from</td> <td class="tg-c6of">{{transaction.cra_rate_from}}</td> </tr> <tr> <td class="tg-l8qj">Market Rent of the property :</td> <td class="tg-c6of">{{transaction.property_market_rent}}</td> </tr> <tr> <td class="tg-l8qj" >Number of Family Group(s) :</td> …