Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store data from website designed by DJANGO to MSSQL or POSTGRESQL
Im currently designing a website which includes user registration , I want to store/import the information/data to SQL database after someone signs up. I would be really happy if someone can help me or guide me to a reference. Thank you! -
How to store session data between users? Django
I'm creating an e-commerce webapp in django. I'm on the part of implementing the cart. I'm using session to store the items in the cart. However, when I switch between AnoymousUser and an authenticated User, I lose the items that were in the cart. How to store this data between users? Bellow is my cart view. carrinho = cart. produto = product class ProdutosDetail(DetailView): model = Produto template_name = 'produto/produto_detail.html' context_object_name = 'produto' def post(self, request, *args, **kwargs): produto = request.POST.get('produto') carrinho = request.session.get('carrinho') #print(carrinho) if carrinho: quantidade = carrinho.get(produto) if quantidade: carrinho[produto] = quantidade + 1 else: carrinho[produto] = 1 else: carrinho = {} carrinho[produto] = 1 request.session['carrinho'] = carrinho return redirect('produtos:ordemview') -
Searchable DropDown with crispy Form in Django
Does anyone know how to add a searchable dropdown box in a form that uses crispy ? Here is the code : views.py class GroupMemberPermissionUpdateView(UpdateView): model = AadGroupmember fields = ['id_aadgroup','id_aaduser'] template_name = 'modify_layout.html' success_url = lazy(reverse, str)("permissions_groupmembers") modify_layout.html {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row justify-content-center"> <div class="col-8"> <h1 class="mt-2">Form for Update</h1> <hr class="mt-0 mb-4"> <form method="POST" enctype="multipart/form-data"> <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form |crispy}} <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> {% endblock %} I am having trouble since I am using using crispy and bootstrap v.5.2 for the forms. Thank you ! -
How to filter a queryset with another queryset to get a single value from a list of value in the former queryset
I'm currently working on a functionality in my web app, There is a form for users to upload images and when there's more than one images, i'm looping through the images to save each to the db. The Property Model: class PostProperty(models.Model): poster = models.ForeignKey(User, on_delete=models.CASCADE) publish = models.BooleanField(default=False) title = models.CharField(max_length=300) category = models.CharField(choices=CategoryTypes.choices, default= CategoryTypes.FOR_RENT, max_length=50) category_type = models.ForeignKey(PropertyTypes,on_delete=models.CASCADE) Then i have another model which is linked to the property model which allows users to upload images for the property on another page: class PostPictures(models.Model): post = models.ForeignKey(PostProperty, on_delete=models.CASCADE) pictures = models.ImageField(default='property_post.jpg', upload_to='images/') Have created a view function, which gets the images from the form and compresses it, after compression, it loops through each and saves it to the db. memory_upload = [] for x in range(len(images)): img = images[x] im = Image.open(img) im_io = BytesIO() if im.mode != 'RGB': im = im.convert('RGB') im = im.resize(img_res) im.save(im_io, format= 'JPEG', optimize=True, quality=50) memory_upload.append(InMemoryUploadedFile(im_io, None, img.name, 'image/jpeg', im_io.tell(), None )) for items in memory_upload: parser = PostPictures.objects.create(post = property, pictures = items) parser.save() return redirect('profile') After the images are saved in the db. I want to create a view for the property list where the user can see all the … -
Create Front-end for azure function
I got several azure functions built in python, like blobTrigger functions or TimerTrigger functions, and I wanted to know if it was possible to create a front end interface for our azure functions to simplify the UX, add boutons etc ... for people who are not familiar with. I would like to do it with Django to simply trigger a function, drag and drop files ... Thanks. -
AttributeError: module '__main__' has no attribute 'cleaner'
We are creating web-site with ai assistant. We trained our model in Google Colab and now we are trying to upload it to our project. But we get the following problem: AttributeError: module 'main' has no attribute 'cleaner'. In our file "views.py" declared the class VoiceAssistant and the function "cleaner" for pipeline. The problem is hidden on the line: talk_model = joblib.load(r'artifitial_assistant/model.pkl') While training our model we used the following code: Pipeline(steps=[('bow', CountVectorizer(analyzer = cleaner)), ('tfidf', TfidfTransformer()), ('classifier', DecisionTreeClassifier())]) Views.py: import string import traceback import webbrowser import joblib import pyttsx3 import speech_recognition import wikipedia from django.shortcut import render def cleaner(x): """ cleaning function required for neural model """ return [a for a in (''.join([a for a in x if a not in string.punctuation])).lower().split()] class VoiceAssistant: """ Settings of our voice assistant """ name = "" sex = "" speech_lang = "" is_talking = False recognition_lang = "" # initializing speech recognition and input tools recognizer = speech_recognition.Recognizer() microphone = speech_recognition.Microphone() # initialization of the speech synthesis tool ttsEngine = pyttsx3.init() def assistant_answer(self, voice): """ a function that loads user input into the neural model and predicts the response """ answer = self.talk_model.predict([voice])[0] return answer # loading a neural model from … -
get checkbox values in django template and pass to view
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) where I want the leader to have the ability to remove Users who have joined the Group. On the frontend, I have the list of members rendered: {% if user.id == group.leader_id %} <form action="{% url 'remove_members' group.pk %}" method="POST"> {% csrf_token %} <ul id='leaderList'> {% for member in list %} <input type='checkbox'>{{ member }}</input> {% endfor %} </ul> <button type="submit">REMOVE</button> </form> {% endif %} However, before I even write the view I need to be able to access the values of these checkboxes and pass the values over to my remove_members view. The view will be function based and will look something like this: def remove_members(request, pk): group = Group.objects.get(id=request.POST.get('group_id')) # I need a line here to access the checkbox values from the template so that I can run a for loop for member in checkbox_values: group.joined.remove(member) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) If I can retrieve the values of the checkboxes and pass them to this view on submit I think this should work to remove the members. Is there some simple thing I'm missing to passing the values? -
Save Excel file to specific path with Django and then zip it
I have the following view which enables me to create an Excel report and then to zip it. def download_report(request, slug): report = get_object_or_404(Report, slug=request.session['slug']) transporter_list = get_transporters_list_with_files(report=report.pk) folder = create_report_folder() if request.method == 'GET': files = [] for transporter in transporter_list: reports_detail = get_object_or_404(ReportResults, report=report, transporter=get_object_or_404(Transporter, name=transporter)) general_result_data = reports_detail.result weights_data = reports_detail.result_comparison_weights file = create_excel_report(report=report, name=transporter, folder_name=folder) files.append(file) zip_files = create_zip_files(list_files=files) response = serve_report_zip_file(zip_files) return response Since multiple reports are to be generated, I'm aiming at generating all the reports and then zip them. I created the following functions: def create_report_folder(): """ Create a folder for the files """ # Creating the folder random_string = get_random_string(length=10) folder_name = "temp" + "/" + random_string if not os.path.exists(folder_name): os.mkdir(folder_name) return folder_name def create_excel_report(report, name, folder_name): """ Create a downloadable report """ # Getting transporters transporter_list = get_transporters_list_with_files(report=report.pk) for transporter in transporter_list: reports_detail = get_object_or_404(ReportResults, report=report, transporter=get_object_or_404(Transporter, name=transporter)) general_result_data = reports_detail.result weights_data = reports_detail.result_comparison_weights general_result_data = json.loads(general_result_data) df_general_result = pd.DataFrame(general_result_data) weight_data = json.loads(weights_data) df_weights = pd.DataFrame(weight_data) # Create a Pandas Excel writer using XlsxWriter as the engine. folder = folder_name filename = "Report - " + name + ".xlsx" with BytesIO() as b: writer = pd.ExcelWriter(b, engine='xlsxwriter') wb = writer.book # … -
Django - Apache - AWS --- 403 Forbidden : You don't have permission to access this resource. error
I have been trying to launch my Django application through apache but I am getting 403 error after configuring apache and giving the permissions. My settings are as follows: Apache conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following … -
Why There Is Error showing "File Not Found" on my Django about webpage even after putting txt file in codebase?
Here Is My about File code from django.http import HttpResponse def readfile(request): openit = open("hell.txt", 'r') hhhhh = openit.read() return HttpResponse(hhhhh) Here Is my urls.py from django.contrib import admin from django.urls import path from . import views from . import about urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), path('about/', about.readfile, name="readfile"), ] Here Is My hell.txt file in same directory vdsseebelouvbuobewoubouerbrobgerubrobogougbeoebergbrobeobwebewbvdsseebelouvbuobewoubouer -
Django admin model add page save button not working
I am trying to add a model from the admin page and when I press save the model doesn't add and nothing happens, the button darkens and that's as far as it goes. Here's my models.py from distutils.command.upload import upload from django.db import models from tinymce.models import HTMLField # Create your models here. class Actualite(models.Model): titre = models.CharField(max_length=200) auteur = models.CharField(max_length=500) miniature = models.ImageField(upload_to='uploads/thumbnails') contenu = HTMLField() date_creee = models.DateTimeField(verbose_name="Date créée", auto_now_add=True, auto_now=False) date_modifiee = models.DateTimeField(verbose_name="Date Modifiée", auto_now=True) def __str__(self): return f"{self.titre} | {self.auteur} | {self.date_creee}" class Meta: ordering = ['date_modifiee'] verbose_name = "Actualité" class Message(models.Model): nom = models.CharField(max_length=200) email = models.EmailField(max_length=200) contenu = models.TextField() date_recu = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.nom} | {self.date_recu}" and settings.py """ Django settings for jac project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os.path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+1j_(+ad1&!9_0+r+u1d&6pieo5q$zv%c-*$vykrx8lnk8c244' # SECURITY WARNING: don't run with … -
To prevent session data between two users Django
Im using django sessions to store user's one of the multiple accounts so that user can proceed with that selected account Flow. When i tried login with another user same account of the previous customer is fetching from session. My scenario is only logged in user should have post/fetch data in session and once logged out all data should be erased. I'm using django JWT. Please help on this. Thanks in advance. -
Django Rest Framework testing destroy view fails
I got fallowing test case: def test_delete_address(self) -> None: """test disable address""" # res = create_object_helper(self.client, self.url, self.data, self.headers) res = self.client.post(self.url, json.dumps(self.data), **self.headers) self.assertEqual(res.status_code, 204) address = AddressBook.objects.all().first() url = reverse( "marketplace_api:add-order-address-detail", kwargs={"pk": address.id} ) res = self.client.delete(url, **self.headers) self.assertEqual(res.status_code, 204) address.refresh_from_db() breakpoint() self.assertTrue(address.disabled) And fallowing view: def destroy(self, request, *args, **kwargs): try: instance = AddressBook.objects.get(id=kwargs.get('pk'), user=request.user) except ObjectDoesNotExist: return Response( {"error": "Address was not found"}, status.HTTP_404_NOT_FOUND ) breakpoint() if instance.disabled: return Response( {"error": "Address was not found"}, status.HTTP_404_NOT_FOUND ) instance.disabled = True instance.save() add = AddressBookSerializer(instance=instance) return Response(add.data, status.HTTP_204_NO_CONTENT) What I'm trying to achieve, is to test my overridden method, where I'm not destroying the instance, but just changing the flag. The problem I am encountering is that, my test case getting different DB data than in view. To test it out, I printed some results in pdb: The response data is (res.data) -> returned from view: {'id': 1, 'invoice': False, 'user': 81, 'first_name': 'Test name', 'last_name': 'Test name', 'street': 'Unknown', 'building': 'Unknown', 'place': 'Unknown', 'city': 'Unknown', 'zip_code': 'Unknown', 'phone_number': 'Unknown', 'email': 'test@test.pl', 'company_name': None, 'nip': None, 'remarks': None, 'disabled': True, 'created': '2022-08-02 15:17:50'} Object address data is (address.__dict__): {'_state': <django.db.models.base.ModelState object at 0x0000026308ED92B0>, 'id': 1, 'user_id': 81, … -
How can I read response content (that is JSON) from Django middleware so I can convert it to HTML?
From my django view I am returning a serialized JSON as below: def features(request): features = db_service.fetch_all_features() data = serializers.serialize('json', features) return HttpResponse(data, content_type='application/json') I have registered a middleware, where I want to fetch this JSON and convert it into HTML class ReturnResponseAsHTML: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after #return HttpResponse(data, content_type='application/json') return response Once I have access to the response object, how may I fetch the JSON from it so I may convert it to HTML -
Get Highest Likes User with Django
class Profile(models.Model): .. goldcoin = models.IntegerField(default=0) likes = models.ManyToManyField(User, blank=True, related_name='user_like') dislikes = models.ManyToManyField(User, blank=True, related_name='user_dislike') def __str__(self): return self.user.username def get_avatar(self): .. from likes = models.ManyToManyField(User, blank=True, related_name='user_like') How to get Highest Likes User? Example i have user like this User Likes Jhon 30 Aish 25 Josh 5 Adam 50 Output User Likes Adam 50 Jhon 30 Aish 25 Josh 5 Django 4.0.6 Python 3.10.2 -
Django,Profile matching query does not exist error at profile/1
I'm learning django,whenever I click on the profiles(links) on the profile_list page,I get the profile doesn't exist error it always goes to profiles that do not longer exist in the database. This is the models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) follows=models.ManyToManyField( "self", related_name="followed_by", symmetrical=False, blank=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile=Profile(user=instance) user_profile.save() user_profile.follows.add(instance.profile) user_profile.save() th This is the admin.py from django.contrib import admin from django.contrib.auth.models import Group,User from .models import Profile class ProfileInline(admin.StackedInline): model=Profile class UserAdmin(admin.ModelAdmin): model=User fields=["username"] inlines=[ProfileInline] # Register your models here. admin.site.unregister(Group) admin.site.unregister(User) admin.site.register(User,UserAdmin) This is the views.py from django.urls import reverse from django.shortcuts import render from requests import request from users.models import Profile from django.http import HttpResponseRedirect # Create your views here. def dashboard(request): return render(request,"inbox/layout.html") def feed(request): return render(request,"inbox/feed.html") def outbox(request): return render(request,"inbox/outbox.html") def profile_list(request): profiles=Profile.objects.exclude(user=request.user) return render(request,"inbox/profile_list.html",{"profiles":profiles}) def profile(request, pk): if not hasattr(request.user, 'profile'): missing_profile = Profile(user=request.user) missing_profile.save() profile = Profile.objects.get(pk=pk) if request.method == "POST": current_user_profile = request.user.profile data = request.POST action = data.get("follow") if action == "follow": current_user_profile.follows.add(profile) elif action == "unfollow": current_user_profile.follows.remove(profile) current_user_profile.save() return render(request, "inbox/profile.html", … -
Django ORM prioritise a column with (almost) duplicate data
Basic DB table is: class ModelA(models.Model): type_of_input = models.CharField(max_length=10) # say "USER" or "SOURCE" date = models.DateField() volume = models.IntegerField() object_referenced = Foreign_key... Problem We sometimes have two duplicate entries in ModelA - which means the two values for the date and the object_referenced are the same, but the values for the type_of_input are different. This means we need to prioritise one value ("SOURCE") for type_of_input over the other ("USER"), in order to make sure the volume value is correct (as "USER" can sometimes be incorrect). We always get the data from the (sometimes unreliable) "USER" type_of_input, but only occasionally get the (always correct) "SOURCE" type_of_input. So when the "SOURCE" type of input value is present we need to return only the "SOURCE" row and not the "USER" row Question How could we do this with the Django ORM to only retrieve one row per date (prioritising the "SOURCE" value for type_of_input? -
Django and Postgre: psycopg2.errors.UniqueViolation: could not create unique index "main_customuser_pkey" DETAIL: Key (token)=(Key) is duplicated
this error show up when i migrate to db using python manage.py migrate, model: class CustomUser(AbstractUser): username = models.CharField(max_length=322,unique=True) email = models.EmailField(max_length=320,unique=True) token = models.UUIDField(primary_key=True,default=uuid.uuid1,editable=False) USERNAME_FIELD ='email' REQUIRED_FIELDS = ['username'] -
Wagtail - customise FieldPanel to show results for current Locale
I have a site which is i18n enabled and using wagtail-localize. When editing (or creating) the original language of a page, all the snippets show values for every language, if you use the standard FieldPanel. Using the SnipperChooserPanel is not an option because there are a lot of ParentalManytoManyFields in the model, it would be too cluttered for the editors. This is how the model and snippet is constructed. @register_snippet class Level(TranslatableMixin): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: verbose_name = "Educational Level" unique_together = ('translation_key', 'locale') class Activity(Page): ... level = ParentalManyToManyField(Level, verbose_name='Education level', blank=True) MultiFieldPanel([ .... FieldPanel('level', widget=forms.CheckboxSelectMultiple), ]) I'm trying to work out how to subclass FieldPanel so it uses the page's locale to filter the snippet queryset. I have hacky/temporary solution to this using the limit_choices_to kwarg for ParentalManyToManyField but I can only filter by the user language not the page language. def limit_lang_choice(): limit = models.Q(locale__language_code=get_language()) return limit -
Synthax error on my code - what is wrong in my logic?
It looks like there is a syntax error in my code at the last line. Django doesnt like it. It considers the "return" is outside the function. It was making sense to me. Any clues? class ProfileView(request): user = request.user up = user.userprofile form = FORM(instance = up) if request.is_ajax(): form = FORM(data = request.POST, instance = up) if form.is_valid(): obj = form.save() obj.has_profile = True obj.save() result= "Success" message = "Your profile has been updated" else: message = FormErrors(form) data = {'result':result,'message':message} return JsonResponse(data) -
Detail: Unsupported media type "application/json" in request in django and Vue JS
I am trying to upload a file in my website . However, i got an error Unsupported media type "application/json" in request in python django backend. Not too sure if it is frontend problem or backend problem. But in the django backend , it shows that the API has unsupported media type. Can anyone help me this ? frontend <v-file-input type="file" label="Attachment" multiple prepend-icon="" prepend-inner-icon="mdi-file" v-model="inputs[i].value" :outlined="outlined" > </v-file-input> models.py class ClinicVisit(models.Model): upload_attachment = models.FileField(null=True , blank=True, upload_to='uploads/') views.py class ClinicVisitList(generics.ListCreateAPIView): serializer_class = ClinicVisitSerializer filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_class = ClinicVisitFilter permission_classes = [permissions.IsAuthenticated,] pagination_class = LargeResultsSetPagination ordering = ['-created_at'] parser_classes = [MultiPartParser, FormParser] queryset = get_user_model().objects.all() def get_queryset(self): return ClinicVisit.objects.based_on_access_level(self.request.user) def post(self, request, format=None, *args, **kwargs): file_serializer = ClinicVisitSerializer(data=request.data,instance=request.user) if file_serializer.is_valid(): file = request.FILES['file'] file_serializer.save() print('hello') return response.Response(file_serializer.data, status=status.HTTP_200_OK) else: print('error') return response.Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) -
Heroku Postgis - django releases fail with: relation "spatial_ref_sys" does not exist
Since Heroku changed their extension schema management (https://devcenter.heroku.com/changelog-items/2446) deployments to our existing django 4.0 application fail with the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedTable: relation "spatial_ref_sys" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 106, in handle connection.prepare_database() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 26, in prepare_database cursor.execute("CREATE EXTENSION IF NOT EXISTS postgis") File "/app/.heroku/python/lib/python3.9/site-packages/sentry_sdk/integrations/django/__init__.py", line 544, in execute return real_execute(self, sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "spatial_ref_sys" does not exist Has anyone experienced the same issue? Is there … -
add manual parameters using drf-yasg, modelviewset
how do I add a manual parameters using drf-yasg? I need two parameters for product id and quantity this is what it looks like right now Swagger api, this is what i want to achieve RestFrameWorkBrowsableAPI. I've tried to add manual parameters with swagger_auto_schema decorators, but nothing changes. this is my views class OrderItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'patch', 'delete','head', 'options'] def get_serializer_class(self): if self.request.method == 'PATCH': return UpdateOrderItemSerializer elif self.request.method == 'POST': return AddOrderItemSerializer return OrderItemSerializer def get_queryset(self): return OrderItem.objects.filter(order_id=self.kwargs['order_pk']).select_related('product') def get_serializer_context(self): return {'order_id': self.kwargs['order_pk']} this is my serializers class AddOrderItemSerializer(serializers.ModelSerializer): #product_id = serializers.IntegerField() product_id = openapi.Parameter('product', in_=openapi.IN_QUERY, type=openapi.TYPE_NUMBER) @swagger_auto_schema(manual_parameters=[product_id]) def save(self, **kwargs): order_id = self.context['order_id'] product_id = self.validated_data['product_id'] quantity = self.validated_data['quantity'] try: order_item = OrderItem.objects.get( order_id=order_id, product_id=product_id) order_item.quantity += quantity order_item.save() self.instance = order_item except OrderItem.DoesNotExist: self.instance = OrderItem.objects.create( order_id=order_id, **self.validated_data) return self.instance class Meta: model = OrderItem fields = ['id', 'product_id', 'quantity'] -
Use different delete behavior in admin-django and models.CASCADE
I have two Django models, one referencing the other with a ForeignKey. Something like this: class Data(models.Model): [some fields] class Backup(models.Model): data_source = models.ForeignKey(Data, on_delete=models.CASCADE) storage_destination = models.ForeginKey(S3Bucket, on_delete=models.CASCADE) The behavior I want is that After the deletion of a "Data" instance, Its backups get deleted from the S3 bucket (I can handle this by invoking a Temporal workflow like DeleteFromS3Workflow, no Django hack is needed), and after the completion of DeleteFromS3Workflow, the "Backup" model gets deleted from the database. Beyond this, I want to be able to delete a "Backup" object from Django admin without invoking the Temporal workflow and directly deleting the object from the database (the thing uncustomized delete() method of the model does). Overwriting the delete() method on the "Backup" model doesn't satisfy this as long as it deletes the model before the completion of workflow and this behavior is mutual in both cases. -
how to use prefetch_related or select_related with multitable inheritance
hey guys i have these models class Product(models.Model): ....... class Course(Product): ......... class Book(Product): ......... class Cart(models.Model): product = models.ForeignKey(Product) what I want is to prefetch the products with the Cart objects i know we can do this Cart.objects.select_related('product') but how do we also get the product to children too without making an impact on the performance and if i get it's children how can get it's child when accessing the product like: cart_instance.product.its_child