Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django connect two unrelated models using has_many_through
I have 3 Django models: Company, Category, Country. a Company has many-to-many relations with Category and belongs to a Country a Country has many Company below is my code for the 3 models class Company(models.Model): name = models.CharField(max_length = 255, unique = True) country = models.ForeignKey(Country, on_delete = models.CASCADE, related_name = 'companies') categories = models.ManyToManyField(Category, related_name = 'companies') class Country(models.Model): name = models.CharField(max_length = 255, unique = True) class Category(models.Model): name = models.CharField(max_length = 255, unique = True) # show method in the country view def show(request, slug): country = get_object_or_404(Country.objects.prefetch_related('companies'), slug = slug) context = { 'country': country } return render(request, 'countries/show.html', context) # show.html template for country {% for company in country.companies.all %} <a href="{{ company.get_absolute_url }}">{{ company.name|title }}</a><br> {% empty %} <p>no companies yet</p> {% endfor %} How do I get the categories in a country through the companies and also the number of companies in that category in the country in the country view -
Django Tabular Inline has no foreign key issue
In Django I am setting up two models one for product and one for image. One product can have multiple images associated with it and therefore I am using a one to many model. In my models.py I have from django.db import models from django.db.models.fields import CharField # Create your models here. class Image(models.Model): image = models.ImageField() imageMetaKeyWords = models.CharField("Meta keywords for SEO", max_length = 255, help_text = "Comma delimited words for SEO") imageMetaDescription = models.CharField("Meta description", max_length = 255, help_text = "Content for image meta tag description") defaultImage = models.BooleanField(default= False) class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) productAvailable = models.BooleanField(default = True) productCreated_at = models.DateTimeField(auto_now_add = True) productUpdated_at = models.DateTimeField(auto_now = True) productSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from product name") productMetaKeywords = models.CharField("Meta keywords for SEO", max_length = 255, help_text ="Comma delimited words for SEO") productMetaDescription = models.CharField("Meta description", max_length = 255, help_text="Content for meta tag description") productImages = models.ForeignKey(Image, on_delete=models.CASCADE) class Meta: db_table = 'products' ordering = ['-productName'] def __str__(self): return self.productName In admin.py from django.contrib import admin from .models import Product, Image from .forms import ProductAdminForm # Register your models … -
how to use django authentication
views.py from django.contrib.auth import authenticate def loginf(request): username = "ph" password = "mypassword" user = authenticate(username=username, password=password) if user is not None: print(user) else: print("not found") return render(request,'myapp/login.html',) urls.py from django.contrib import admin from django.urls import path from django.urls.conf import include from . import views urlpatterns = [ path('',views.Home.as_view(),name='index'), path('signup/',views.SignUpView.as_view(),name='signup'), path('login/',views.loginf, name ='login') ] it always return "not found". my username and password are valid, i have double checked username and password, and tried with many users, what i am doing wrong. password saved in database in pbkdf2_sha256 algorithm, how do i authenticate. -
I am using tiny mce in django and in react.js . Tiny mce text editor gives html in front-end
I am using django and react.js in our project. I use tiny mce to write the blog the blog is save in backend and I fecth the blog in front-end It gives me html in the front-end like this Why Jammu and Kashmir Is The Perfect Location For Pre Wedding Shoots In India BY SHIVANGI GOEL MAY 2, 2019 Searching for the perfect location for your pre wedding shoot? Well, they say you get married only once, so why not make it memorable and larger than life? The most important thing on every soon to be hitched couple’s bucket list – a pre wedding shoot, requires some good planning. The most important aspect of planning a pre-wedding shoot is searching for the most romantic and picturesque locations. Jammu and Kashmir is the perfect location for a unique experience and a gorgeous pre wedding shoot. Only because if there’s paradise on earth- it’s here! From the very beautiful Dal Lake, Shalimar Bagh, Chashma Shahi and Mughal Gardens to the marvelous hill stations like Gulmarg, Pahalgam & Sonamarg; Kashmir has it all. Leh Ladakh or the Biker’s heaven is yet another feast for the eyes in Kashmir which is gaining popularity as one of the … -
How to save Foreign Key in table and get populated data in Django rest framework?
I'm trying to save advisor id in advisor_id field in Booking table but it is storing null value in booking table when ever I use advisor = AdvisorSerializer(read_only=True) which I'm using to populate data from Advisor Model serializer.py from django.db import models from django.db.models import fields from rest_framework import serializers from .models import Advisor, Booking class AdvisorSerializer(serializers.ModelSerializer): class Meta: model = Advisor fields = '__all__' class BookingSerializer(serializers.ModelSerializer): advisor = AdvisorSerializer(read_only=True) class Meta: model = Booking fields = '__all__' models.py from django.db import models from users.models import User # Create your models here. class Advisor(models.Model): name=models.CharField(max_length=255) photo=models.URLField() class Booking(models.Model): user=models.ForeignKey(User, related_name='users', blank=True, null=True, on_delete=models.CASCADE) advisor=models.ForeignKey(Advisor, related_name='advisors', blank=True, null=True, on_delete=models.CASCADE) booking_time=models.DateField() views.py - post method to store data in booking table class bookAdvisorMeetingDate(APIView): def post(self, request, user_id, advisor_id): token = request.COOKIES.get('jwt') if not token: return Response({"success": False, "message": "UnAuthorized"}, status=status.HTTP_401_UNAUTHORIZED) try: payload = jwt.decode(token, 'secret', alogrithm=['HS256']) except jwt.ExpiredSignatureError: return Response({"success": False, "message": "UnAuthorized"}, status=status.HTTP_401_UNAUTHORIZED) if not str(payload['id']) == user_id: return Response({"success": False, "message": "UnAuthorized | You have no access to this route"}, status=status.HTTP_401_UNAUTHORIZED) # print(user_id, advisor_id) user = User.objects.filter(id=user_id).first() advisor = Advisor.objects.filter(id=advisor_id).first() print('user adn advisor', user.id, advisor.id) data = {**request.data, 'user': user_id, 'advisor': advisor_id} serializer = BookingSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"success": True}, … -
Django images not found in page view but was save after post request
I was trying to save an image but it can't be displayed through the browser. It was successfully saved in the exact location but when I pasted the link it says, "Page not found". Could someone help me with what's going on? See output: Browser View Code: Code Snippet Settings configuration: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_LOCATION = "static" MEDIA_LOCATION = "media" -
Termux django requirements.txt pip install error
WARNING: Discarding https://files.pythonhosted.org/packages/fa/aa/025a3ab62469b5167bc397837c9ffc486c42a97ef12ceaa6699d8f5a5416/bcrypt-3.1.7.tar.gz#sha256=0b0069c752ec14172c5f78208f1863d7ad6755a6fae6fe76ec2c80d13be41e42 (from https://pypi.org/simple/bcrypt/) (requires-python:>=2.7, !=3.0., !=3.1., !=3.2., !=3.3.). Command errored out with exit status 1: /data/data/com.termux/files/home/qforum/bin/python3 /data/data/com.termux/files/usr/tmp/pip-standalone-pip-bgwdkmi6/env_pip.zip/pip install --ignore-installed --no-user --prefix /data/data/com.termux/files/usr/tmp/pip-build-env-g9xko9te/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel 'cffi>=1.1; python_implementation != '"'"'PyPy'"'"'' Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement bcrypt==3.1.7 (from versions: 1.0.0, 1.0.1, 1.0.2, 1.1.0, 1.1.1, 2.0.0, 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, 3.1.7, 3.2.0) ERROR: No matching distribution found for bcrypt==3.1.7 WARNING: You are using pip version 21.2; however, version 21.3.1 is available. You should consider upgrading via the '/data/data/com.termux/files/home/qforum/bin/python3 -m pip install --upgrade pip' command. -
git push -u origin username password
I have a problem with git push -u origin when I enter my github username and password it gives this error: git push -u origin master remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead. remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information. fatal: Authentication failed for 'https://github.com/Ahmadmohseni/Concert_ticketsales_system_project.git/' -
Django Error admin.E202 'stamm.Workplan' has no ForeignKey to 'enquiry.Costing'
I'm struggling with the following Problem: I have created two apps, "stamm" and "enquiry". In the first app "stamm" I have the model Workplan. In the second app "enquiry" I have the model "Costing". I use a M2M relationship via a through-model called "CostingWorkplan" below my Costing model. Then I want to add a TabularInline from the Workplan to my CostingAdmin. When I do this, I get the Error "<class 'enquiry.admin.WorkplanInline'>: (admin.E202) 'stamm.Workplan' has no ForeignKey to 'enquiry.Costing'.". I checked a couple of threads with a similar Problem, but can't get rid of it. Did I overlook something? Here is my Python Code: # stamm.models.py class Workplan(model.Model): some_fields = ... # enquiry.models.py from stamm.models import Workplan class Costing(model.Model): some_fields = ... costing_workplan = models.ManyToManyField(Workplan, through='CostingWorkplan') class CostingWorkplan(models.Model): workplan = models.ForeignKey(Workplan, on_delete=models.RESTRICT) costing = models.ForeignKey(Costing, on_delete=models.RESTRICT) # enquiry.admin.py from .models import Costing from stamm.models import Workplan class WorkplanInline(admin.TabularInline): model = Workplan @admin.register(Costing) class CostingAdmin(admin.ModelAdmin): inlines = (WorkplanInline, ) -
Django reverse_lazy to a URL with a related field id
I have created 2 related models, Applicant and ApplicantStatus. After creating an ApplicantStatus, I would like to reverse_lazy to the applicant detail page based on the applicant status create view entry. class Applicant(models.Model): first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) class ApplicantStatus(models.Model): applicant = models.ForeignKey(Applicant, on_delete=models.PROTECT, related_name='applicant') Here is the applicant status create view class ApplicantStatusCreateView(LoginRequiredMixin, CreateView): model = ApplicantStatus form_class = ApplicantStatusCreateForm template_name = 'recruitment/applicant_status_create.html' def get_success_url(self): return reverse_lazy('recruitment:applicant_detail', kwargs={'pk': self.object.pk}) I already know that this will redirect to the non-exisiting page as that applicant doesn't exist yet. This is where I would like to get the id of the applicant from the form and use that in the kwargs, so i will see the applicant detail page with the list of applicant statuses. Here is the applicant detail view: @login_required() def applicant_detail_view(request, pk): applicant_detail = Applicant.objects.get(id=pk) form = ApplicantStatusCreateForm applicant_status_detail = ApplicantStatus.objects.filter(applicant__id=applicant_detail.id) context = { 'applicant_detail': applicant_detail, 'form': form, 'applicant_status_detail': applicant_status_detail, } return render(request, 'recruitment/applicant_detail.html', context) The applicant status create form appears in the detail view too as I'm using a modal to display the form in the detail view. -
Django ORM for intermediate images table gives error "The QuerySet value for an exact lookup must be limited to one result"
I have multiple Images associated with a Spots using the intermediate table ImageSpots, and I am trying to render each image for each spot but keep getting the error "The QuerySet value for an exact lookup must be limited to one result using slicing.". Can someone help me figure out what I'm doing wrong? models.py class Spots(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) author = models.ForeignKey(Authors, models.DO_NOTHING) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') summary = models.TextField(blank=True, null=True) content1 = models.TextField(blank=True, null=True) content2 = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'spots' verbose_name_plural = 'Spots' def __str__(self): return str(self.id) + ": " + str(self.title) class Images(models.Model): note = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(upload_to="images", blank=True, default='logo-00-06.png') class Meta: managed = True db_table = 'images' verbose_name_plural = 'Images' def __str__(self): return str(self.id) + ": " + str(self.note) class ImageSpots(models.Model): images = models.ForeignKey('Images', models.DO_NOTHING) spots = models.ForeignKey('Spots', models.DO_NOTHING) class Meta: managed = True db_table = 'image_spots' verbose_name_plural = 'ImageSpots' def __str__(self): return str(self.spots) + ": " + str(self.images) views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) spots = Spots.objects.filter(articlespots__article=article).distinct() images = Images.objects.filter(imagespots__spots=spots) context = {'spots': spots, 'article': article, … -
I need to connect my Django app to a live Mysql server
I made an integration app for clickup with webhooks that sends data to my Django api whenever an action is performed. So far I've been saving the data in my local postgres database. But I need to send the data to a Mysql live server that is the database for a sap B1 app. I looked into how to hook the live database into my Django app and found something called pymssql but I need to write the queries myself instead of using the Django ORM. So I was thinking of if there's any type of synchronisation that can be done between my Django database that I will deploy on heroku and the live Mysql server. Any tips on how to do that would be appreciated. -
Adding the quantity of a product and updating it in cart using django
I am going through a django e-commerce video tutorial in which I can add product to cart using Ajax perfectly but am unable to update the quantity of the product to the cart. I have gone through many video tutorial as well as many stack overflow questions and many blogs but couldn't find a solution. please help me out Product/models.py class Product(models.Model): title = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2, max_digits=20) quantity = models.IntegerField(default=1) cart/models.py class CartManager(models.Manager): def new_or_get(self,request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count()==1: new_obj = False; cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj=user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action =='post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: … -
Django: Many to many field MultiSelect Into DropdownList
I have one manytomany field in one of my model which is currently coming as Multiselect but I need a dropdown where user can select multiple values as I have huge data to show. I am trying this in forms.py but it is not showing dropdown field. model.py: class Chain(models.Model): chain_id = models.AutoField(primary_key=True) chain_name = models.CharField(max_length=255, unique=True) chain_type = models.ForeignKey(ChainType, on_delete=models.CASCADE) history = HistoricalRecords() class Meta: ordering = ('chain_name') def __str__(self): return self.chain_name class Brg(models.Model): brg_campaign_id = models.AutoField(primary_key=True) campaign_tracking = models.ForeignKey(CampaignTracking, on_delete=models.CASCADE) brg_name = models.ForeignKey(Chain, on_delete=models.CASCADE, related_name="primary_brg", help_text='Add Brgs/chain names for these above campaign has run') brg_benchmark = models.ManyToManyField(Chain, related_name="competitor_brg", null=True, blank=True, help_text='Add max.5 other benchmarks brgs to check overall impact') history = HistoricalRecords() class Meta: verbose_name = 'Brg Campaign Tracking' def __str__(self): return "Brg names list" forms.py: class ChainForm(forms.ModelForm): class Meta: model: Chain # fields = ('campaign_tracking', 'brg_name', 'brg_benchmark',) widgets = {'chain_name': Select()} -
get default_storage path in django for use with google storage
how i can get the path of default_storage? i need to declare this path to use with google storage and openpyxl, the problem is that i can write and read files with default_storage.open, but i only need the path for use with openpyxl, but when i use default_storage.path i got the error: this backend doesnt support absolute paths. something like this i what i need: directory = default_storage.path() plantilla_excel = openpyxl.load_workbook(f"{directory}/ficha.xlsx") -
How to create dynamic model and form in Django
In my Django application I have a model named Service that contains multiple value. And I want a system that for each value different kinds of form to appear. I know I need models to generate forms and store data. But since the admin from custom admin panel can add or remove data in the Service model dynamically, I want a system that he can select the form for each data he enters in Service model. I need a guide on how can I achieve my goal. -
Popup-model is not opening in for loop (HTML)
I am trying to open a Pop up Model in for loop for every instance but the pop up model is opening for first instance But is not opening for other instances. I am using Django in template loop. template.html {% for comment in comments %} <button id="ModelButton">Open Model</button> <div id="Model" class="flagModel"> <div class="modal-content"> <div class="modal-mod"> <div class="container-fluid"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit"> </form> </div> </div> </div> </div> <script> var formModel= document.getElementById("Model"); var formButton = document.getElementById("ModelButton"); formButton .onclick = function () { formModel.style.display = "block"; } window.onclick = function (event) { if (event.target == formModel) { formModel.style.display = "none"; } } </script> {% endfor %} When I Place the JavaScript outside the for loop then it doesn't even work for one. I have tried many times but it is still not working. Any help would be much Appreciated. Thank You -
TypeError: dict object is not callable (inside Thread function)
I am getting an error in a program which is using threading to perform functions simultaneously, this process is a job which is run once per hour, The data that comes in is from a view in sql. The function that is called in target arg returns a dictionary and says "dict object is not callable". Inside the function, is returned a dictionary. My doubt is what should return in this function, if I don't return anything will it affect any other thread? # inside the jobs in django I call this function def ticket_booking(): query = " SELECT * FROM vw_ticket_list;" ttd = [] try: result = query_to_dicts(query) tickets = json.loads(to_json(result)) if tickets: # Calling the vaccination push message (php). for ticket in tickets: # Getting Generic details used by all categories full_name = tickets['full_name'] gender = tickets['gender'] email =tickets[email] if tickets['language_id'] == 1: # book english movie tickets # Calling the function inside the Thread for a Syncronuz Call (Wait and Watch) myThread = threading.Thread(target=book_english(email, full_name)) myThread.start() myThread.join() if tickets['language_id'] == 2: # book italian movie tickets myThread = threading.Thread(target=book_italian( email, full_name, gender)) myThread.start() # Starting the Thread myThread.join() #Will return here if sth is returned As you … -
Django REST Framework: Does ModelSerializer have an option to change the fields dynamically by GET or POST?
Does ModelSerializer have an option to change the fields dynamically by GET or POST? While GET requires complex fields such as nested serializers, these are not required for POST. I think the solution is to use separate serializers for GET and POST. But in that case, I'd have to create quite a few useless serializers. Is there any good solution? -
Django open excel.xlsx with openpyxl from google cloud storage
i need to open a .xlsx file from my bucket on google storage, the problem is i get :FileNotFoundError at /api/ficha-excel [Errno 2] No such file or directory: 'ficha.xlsx' this are the settings from my bucket. UPLOAD_ROOT = 'reportes/' MEDIA_ROOT = 'reportes' This are the route bucket/reportes/ficha.xlsx This are the code of mi get function: directorio = FileSystemStorage("/reportes").base_location os.makedirs(directorio, exist_ok=True) # read print("Directorios: ", directorio) plantilla_excel = openpyxl.load_workbook(f"{directorio}/ficha.xlsx") print(plantilla_excel.sheetnames) currentSheet = plantilla_excel['Hoja1'] print(currentSheet['A5'].value) what is the problem with the path? i cant figure out. -
Django ORM : Using pivot/intermediate tables
I am trying to render the view article by filtering through the model Spots and Images. I have managed to render the spots associated with each article, but cannot seem to render the images for each spot. I have an intermediate table ArticleSpots to link the 2 tables Spots and Articles. I have another intermediate table ImagesSpots to link the tables Spots and Images. All spots associated with the article is rendered, but how can I render the images for each spot? views.py def article(request, slug): article = get_object_or_404(Articles, slug=slug) spots = Spots.objects.filter(articlespots__article=article).distinct() images = Images.objects.filter(imagespots__spots=spots) context = {'spots': spots, 'article': article, 'images':images} return render(request, 'articletemplate.html', context) models.py class Articles(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') class Meta: managed = True db_table = 'articles' verbose_name_plural = 'Articles' def __str__(self): return str(self.id) + ": " + str(self.title) class Spots(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) author = models.ForeignKey(Authors, models.DO_NOTHING) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') summary = models.TextField(blank=True, null=True) content1 = models.TextField(blank=True, null=True) content2 = … -
How can I solve strftime TypeError when making a POST request in Django?
I am creating an API that contains a DateTimeField using Django but I am getting the following error "TypeError: descriptor 'strftime' for 'datetime.date' objects doesn't apply to a 'str' object" I have tried checking different sources but I haven't found a solution. The error is arising from the start_date line. from datetime import datetime def question_view(request): if request.method == 'GET': return HttpResponse("Вопрос не создан") elif request.method == 'POST': poll_question = request.POST['poll_question'] title = request.POST['title'] start_date = datetime.strftime(request.POST['start_date'],'%Y-%m-%d') Question.objects.create(poll_question=poll_question,title=title, start_date=start_date) return HttpResponse("Вопрос создан") else: return "Попробуйте снова" -
Is Nested aggregate queries possible with Django queryset
I want to calculate the monthly based profit with the following models using django queryset methods. The tricky point is that I have a freightselloverride field in the order table. It overrides the sum of freightsell in the orderItem table. That's why I have to calculate order based profit first and then calculate the monthly based profit. Because if there is any order level freightselloverride data I should take this into consideration. Below I gave a try using annotate method but could not resolve how to reach this SQL. Does Django allow this kind of nested aggregate queries? select sales_month ,sum(sumSellPrice-sumNetPrice-sumFreighNet+coalesce(FreightSellOverride,sumFreightSell)) as profit from ( select CAST(DATE_FORMAT(b.CreateDate, '%Y-%m-01 00:00:00') AS DATETIME) AS `sales_month`, a.order_id,b.FreightSellOverride ,sum(SellPrice) as sumSellPrice,sum(NetPrice) as sumNetPrice ,sum(FreightNet) as sumFreighNet,sum(FreightSell) as sumFreightSell from OrderItem a inner join Order b on a.order_id=b.id group by 1,2,3 ) c group by sales_month from django.db import models from django.db.models import F, Count, Sum from django.db.models.functions import TruncMonth class Order(models.Model): CreateDate = models.DateTimeField(verbose_name="Create Date") FreightSellOverride = models.FloatField() class OrderItem(models.Model): SellPrice = models.DecimalField(max_digits=10,decimal_places=2) FreightSell = models.DecimalField(max_digits=10,decimal_places=2) NetPrice = models.DecimalField(max_digits=10,decimal_places=2) FreightNet = models.DecimalField(max_digits=10,decimal_places=2) order = models.ForeignKey(Order,on_delete=models.DO_NOTHING,related_name="Item") result = (OrderItem.objects .annotate(sales_month=TruncMonth('order__CreateDate')) .values('sales_month','order','order__FreightSellOverride') .annotate(profit=Sum(F('SellPrice')-F('NetPrice')-F('FreightNet')),freight=Sum('FreightSell')) ) -
django live reload doesnt work with 2nd docker-compose file
I want to create 2 environments. Test and the standard dev environment. I need to run the django test server within test environment and the regular server, manage.py runserver on the other. The main dev environemnt will use the docker-compse.yml and the test environment will use test.yml. When I run docker-compose up, live-reload works normally. When i run docker-compose -f test.yml up, the test server runs but docker does not do live reloads. I add the same services to both files to shorten the CLI syntax. docker-compose.yml version: "3.9" services: web: build: dockerfile: ./compose/django/Dockerfile context: . container_name: main_app_django env_file: - ./.local/.env command: compose/django/start.sh volumes: - .:/code ports: - "8000:8000" redis: container_name: main_app_redis image: "redis:alpine" command: redis-server ports: - "6379:6379" celeryworker: build: dockerfile: ./compose/celery/Dockerfile context: . container_name: main_app_celery command: celery -A app worker -l INFO env_file: - ./.local/.env volumes: - .:/code depends_on: - redis test.yml version: "3.9" services: web: build: dockerfile: ./compose/django/Dockerfile context: . container_name: test_main_app_django env_file: - ./.local/.env command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py testserver cypress/fixtures/user.json cypress/fixtures/tracks.json --addrport 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" redis: container_name: test_main_app_redis image: "redis:alpine" command: redis-server ports: - "6379:6379" celeryworker: build: dockerfile: ./compose/celery/Dockerfile context: . container_name: … -
Patch with only one field with generics.RetrieveUpdateDestroyAPIView
I ma having the following models, and I wanted to achieve the best practice of patching data with RetrieveUpdateDestroyAPIView. Below is the models class Post(TimeStampedModel, models.Model): """Post model.""" title = models.CharField(_('Title'), max_length=100, blank=False, null=False) # TODO: Add image upload. image = models.ImageField(_('Image'), upload_to='blog_images', null=True, max_length=900) body = models.TextField(_('Body'), blank=False) description = models.CharField(_('Description'), max_length=400, blank=True, null=True) slug = models.SlugField(default=uuid.uuid4(), unique=True, max_length=100) owner = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) class Meta: ordering = ['created'] def __str__(self): """ Returns a string representation of the blog post. """ return f'{self.title} {self.owner}' def save(self, *args, **kwargs): """Generate slug field.""" if not self.id: date = datetime.datetime.now() uid = uuid.uuid4() slug_str = '{} {} {}'.format(self.title, date, uid) self.slug = slugify(slug_str) super(Post, self).save(*args, **kwargs) class Tag(models.Model): """Tags model.""" name = models.CharField(max_length=100, blank=False, default='') owner = models.ForeignKey(User, related_name='tags_owner', on_delete=models.CASCADE) posts = models.ManyToManyField(Post, related_name='tags', blank=True) class Meta: verbose_name_plural = 'tags' def __str__(self): """ Returns a string representation of the tags post. """ return f'{self.name}' So in my views this is the Class which might help in patching : class PostDetail(generics.RetrieveUpdateDestroyAPIView): """Blog post details""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = [permissions.IsAuthenticatedOrReadOnly] lookup_field = 'slug' def patch(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, partial=True, context=request) if serializer.is_valid(): serializer.save() return …