Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Watchlist showing in admin interface but not showing on the site django
I am working on a project and the features is that the user should be able to add the item to their “Watchlist.” If the item is already on the watchlist, the user should be able to remove it and users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. When I click on the 'add to watchlist' button, it successfully registers on the admin panel ( screenshot included) but on my webpage, it shows me an empty image (it's supposed to show the listings image) and when I click on that image, it shows me an error message 'No Auction matches the given query.' and I noticed it gives me a different url id (screenshot included and different url from the actual url id of the details page and actual url id of the details page which i'm supposed to be linked to(which is 1)). Also, when I delete one of the products/listing (still by clicking on the add to watchlist button - i would later improve this), it removes everything in the watchlist (even if there were other items in … -
Key removed from dict despite dict.copy()
I'm recently experimenting with session variables instead of writing everything in base. I'm building an app for counter sales (car, user, customer session variables). After the order and its items are saved in DB, I want to save the customer and clear its related session variables of the related customer from request.session['customers'] dict list. def save_customer(request, store): # save only customers != Client Magasin customers = request.session['customers'].copy() print(customers) current_customer = list(filter( lambda i: i['user'] == request.user.pk and i['store'] == store, customers))[0] id = current_customer.pop('id') nom = current_customer['nom'] if nom != 'Client Magasin': current_customer.pop('store') current_customer.pop('user') customer = Customer.objects.create(**current_customer) # return Customer for adding it to order return customer else: # return Client Magasin return Customer.objects.get(pk=1) When I print out request.session['customers'] I can see ID, STORE and USER keys. But after the lambda, those keys are removed from the original request.session['customers'] I know that because further in my code, I wan't to filter again this list def remove_same_customer(request): customers_list = request.session['customers'].copy() print(customers_list) # new_customers = list(filter( # lambda i: i['store'] != request.session['cart_warehouse'] and i['user'] != request.user, customers_list)) # request.session['customers'] = new_customers # request.session.modified = True I have commented the 4 last lines because they trigger an error because ID, STORE and USER … -
How do you add user-defined S3 metadata in when using django-storages
I am using django 3.1.0 with django-storages 1.12.3. I am using an S3 backend to store media files (Minio). I am trying to post the file to S3, and include additional user metadata to the S3 object. This additional metadata comes from the POST request used to upload the file to django. With S3, custom metadata can be added by including additional key-value pairs to the HTTP header for the POST request sent to the S3 server when the file is uploaded, where the custom keys would be prefixed with 'X-Amz-Meta-'. I am using a FileField in a django model, and files are uploaded using a REST API endpoint. As far as I understand it, when django receives the file, it stores it temporarily, and then, when saving the FielField on the model instance, the file is posted to the S3 server. I want to modify the flow, so that the custom metadata is taken from the request and included in the post to the S3 server. Any idea how I can take data from the initial request, and pass it to the header of the POST request being sent to S3? -
What is the simplest way to fake a Django model field?
Currently my Django models looks like this: class Car(Model): horse_power = IntegerField() I have lots of models similar to this, they are used all over the application, there are serializers of DRF endpoints using these model fields as well. Of course the field names are different in other models. However, the horse_power value as well as other fields are no longer IntegerField, but a foreign key to another table containing more complex information like below: class Car(Model): horse_power_complex = OneToOneField(ComplexDataModel, on_delete=CASCADE) To avoid lots of code change in every place the Car model is manipulated, I would like to keep the same getter and setter interfaces as before, in other words, I would like car.horse_power to return a simple integer calculated from the ComplexDataModel, and I also would like car.horse_power = 23 to access the ComplexDataModel and save the processed data so that I dont have to go over the entire application to update all references. It is important to keep in mind that the model constructor should still work, for example, car = Car(horse_power=50). I have tried python descriptors like below: class HorsePower: def __get__(self, obj, objtype=None): return obj.horse_power_complex.get_value() def __set__(self, obj, value): obj.horse_power_complex.set_value(value) class Car(Model): horse_power = HorsePower() … -
Is there a way to create a global counter variable on django templates?
I don't see any other solution other than creating a global variable counter, this counter would be then checked if it meets the criteria (let's say 9 items per page) then do a page break Ideally, here is what I expect to do: I have fruit_items define like this: Class FruitVendor(Model): .... @property def fruit_items(self): return chain( self.appleitem_set.all(), self.bananaitem_set.all() ) Then in django template I do this to list: {% for item in fruit_vendor.fruit_items %} {% if forloop.counter|divisibleby:9 %} <p style="page-break-before: always"></p> {% endif %} <table> {% for apple in appleitem_set.all() %} <tr> <td> {{apple.name}} </td> </tr> {% endfor %} </table> <table> {% for banana in bananaitem_set.all() %} <tr> <td> {{banana.name}} </td> </tr> {% endfor %} </table> {% endfor %} As you can see in above, this would page-break but the overhead looping of fruit_items generate multiple tables which is not intended. What I think I should do remove the forloop in fruit_items and have a global counter that adds + 1 in each for loop, then check if the global counter is divisible by 9 then page-break, but I'm not sure if this is possible. counter = 0 {% if counter|divisibleby:9 %} <p style="page-break-before: always"></p> {% endif %} <table> … -
inline-formset doens't get diplayed in my form
I have a model Company and a model Address, related by a one-to-one relationship in Address: class Company(CompanyParent): # some attributes class Address(AddressParent): company = models.OneToOneField(Company) # some attributes Since these are closely related, I want the user to create a Company object, an Address object and the relationship between the two by just submitting one form; so I looked into Inline Formsets. Here my forms.py: class CompanyModelForm(forms.ModelForm): class Meta: model = Company fields = # ... labels = { # ... } def __init__(self, *args, **kwargs): super(HubModelForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal style-form centered' self.helper.add_input(Submit('submit', 'Submit')) class AddressModelForm(forms.ModelForm): class Meta: model = Address fields = # ... labels = { # ... } AddressFormSet = inlineformset_factory(Company, Address, form=AddressModelForm) All the logic is handled by a view: class CreateCompanyView(SuccessMessageMixin, CreateView): model = Company form_class = ComapnyModelForm template_name = # ... success_url = '/' success_message = # ... def get_context_data(self, **kwargs): ctx = super(CreateCompanyView, self).get_context_data(**kwargs) if self.request.POST: ctx['formset'] = AddressFormSet(self.request.POST) ctx['formset'] = AddressFormSet() return ctx def form_valid(self, form): ctx = self.get_context_data() formset = ctx['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(CreateCompanyView, self).form_valid(form) When I use {% crispy form %} in my template … -
How Do I Properly Submit Two Forms Within One HTML Structure?
I am trying to submit a create view with two forms. The code below works fine if everything is filled out and the form submitted. However if fields are omitted in form2...the form submission fails and the field that was filled out for "form"..."name"....gets reset. I've read you can do multiple forms and I've largely got this working...I just need to figure out how to incorporate form2 into the if_valid().... Here's my view... def tasklist_detail_view(request, id): context = {} context["tasklist"] = TaskList.objects.get(id=id) context["tasks"] = Task.objects.filter(task_list=id).all() obj = get_object_or_404(TaskList, id=id) form = UpdateTaskListForm(request.POST or None, instance=obj) form2 = TaskForm(request.POST or None) context["task_list_id"] = id if form.is_valid(): form.save() return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu")) context["form"] = form context["form2"] = form2 return render(request, "my_task_list_tasklist_detail.html", context) My HTML... <form method="POST" enctype="multipart/form-data" id="forms"> {% csrf_token %} {{ form.name }} {% include "my_task_list_task_create_form1.html" with tasklist=tasklist %} <button type="submit" class="button66" name="status" value="Submitted">Submit</button> </form> And then in my include HTML... <div id="task-list-form" hx-target="this" hx-swap="outerHTML"> <button class="button35" hx-post="{% url 'MyTaskLists:task-create' id=task_list_id %}">Save</button> {{ form2 }} I did try to do something like.... if form.is_valid() and form2.is_valid(): form.save() return HttpResponseRedirect(reverse("MyTaskLists:my_task_list_main_menu")) But then nothing happens...the forms are not accepted at all even if the fields are filled out properly....From what I've read I understand the … -
Video not playing on Django when debug=False
Videos are not playing when I turn DEBUG to False on Django, but on DEBUG=True, everything is fine. The task is simple, the app receives youtube shorts link, downloads it to the MEDIA_ROOT (which declared in settings.py as BASE_DIR / 'media'). And it returns rendered template video.html, on template: <video height="450" autoplay="autoplay" controls style=""> <source src="{{ MEDIA_URL }}{{ file }}" type="{{ mime_type }}"> on html : ` views: {"MEDIA_URL": MEDIA_URL, "file": str(video.video).split('/')[-1],} settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = Path(__file__).resolve().parent.parent / 'media' As I said when debug mode turned on everything works perfect, but I turned it off video is not playing. Did I forget something? Or any mistake I have? how to solve this problem? P.S. I am pretty new on django, I searched for many sources, tried them all, but I couldn't solve this problem -
Paragraphs get lost when posting a form
Hey, I'm creating a forum using django. When a user posts a thread the written text (in the input field {{obj.content}}) by the user should be displayed exactly as he typed it in. The text is displayed through {{form.content}}. That means the paragraphs which were made by the user should be maintained. But in the moment they get lost and the text is displayed without paragraphs. create_thread.py (on this page a thread can be created): {% extends "forum/index.html" %} {% load static %} {% block title %} {{post.title}} {% endblock %} {% block content %} {% for obj in objects %} <div class="container-thread"> <div class="username">{{obj.username}}</div> <div class="topic">{{obj.topic}}</div> <div class="content">{{obj.content}}</div> </div> {% endfor %} {% endblock %} thread.html (on this page the thread is displayed): <div class="container-create-thread"> <h2 class="heading-create-thread">Create a thread</h2> <form method="POST" action=""> {% csrf_token %} <label class="label-topic">Topic</label> {{form.topic}} <label class="label-title">Title</label> {{form.title}} <label class="label-content">Content</label> {{form.content}} <button class="btn submit" id="submit-create-thread" type="submit" value="submit">Submit</button> </form> </div> -
Django Rest Framework data json comma separated django-taggit
I'm using django-taggit and django-taggit_serializer to tag my ecommerce products. When im making an update request via API when the json body looks like this {"tags":"dog,small,golden_retriever"} i get an error { "message": "failed", "details": { "tags": [ "Invalid json list. A tag list submitted in string form must be valid json." ] } } Although in django admin it is comma separated, i'd like to make it comma separated in django rest as well. Serializers class TagProductSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() class Meta: model = Product fields = ('tags',) def update(self, validated_data): tags = validated_data.pop('tags') instance = super(TagProductSerializer, self).create(validated_data) instance.tags.set(*tags) return instance Views class TagProductsApiView(generics.UpdateAPIView): queryset = Product.objects.all() serializer_class = TagProductSerializer lookup_field = 'pk' def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response({"message": "Tags have been updated successfully"}) else: return Response({"message": "failed", "details": serializer.errors}) -
Django Admin: How to use OneToMany Field inside list_display?
When listing the "House" Model inside the django admin panel i want to show all Houses but with the PostalCode inside list_display so i can sort them by postal code. Can i use the existing ForeignKey connection between House and HouseAddress to achieve this? I found some information on how to list parts of the "Houses" inside the "House Addresses" list view (because it has the foreign key field) but not from the "Houses" list view. Admin.py class HouseAdmin(admin.ModelAdmin): search_fields = ['Name'] list_display = ['Name'] class HouseAddressAdmin(admin.ModelAdmin): search_fields = ['PostalCode'] model = HouseAddress list_display = ['PostalCode'] Model.py class House(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) class HouseAddress(models.Model): PostalCode = models.CharField(max_length=30, null=True, blank=True) AddressInfo = models.ForeignKey(House, null=True, blank=True, on_delete=models.CASCADE, related_name='fa') -
Date filter on model methods
Hi all this project I'm using python and Django. I currently have a two models where I writing model methods to show certain linked fields(FOREIGN KEYS) I will show this below, now what I am trying to do is be able to filter by date these model methods, from what I have tried I am getting an error no signature for built in methods. So basically my template renders these model methods and now I want to search between date ranges. The code below is my models and the methods as well as the function I am trying to filter these methods. Your feedback will be highly appreciated. #Sales agent model in models.py class SalesAgent(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="sauser") Team_leader = models.ForeignKey(TeamLeader,on_delete=models.SET_NULL,null=True,related_name="team_agent") SA_name = models.CharField(max_length=40) role = models.CharField(choices=Roles,default="default",max_length=13) def __str__(self): return self.user.username def sget_totals(self): today = datetime.date.today() return self.agent_sale.filter(Date_created__year=today.year,Date_created__month=today.month) def sget_confirmed(self): today = datetime.date.today() return self.agent_sale.filter(State="Confirmed",Date_created__year=today.year,Date_created__month=today.month) def sget_debi(self): today = datetime.date.today() return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__year=today.year,Date_created__month=today.month) def sget_requested(self): today = datetime.date.today() return self.agent_sale.filter(Debi_status="Requested",Date_created__year=today.year,Date_created__month=today.month) def sget_cancelled(self): today = datetime.date.today() return self.agent_sale.filter(State="Cancelled",Date_created__year=today.year,Date_created__month=today.month) def sget_pending(self): today = datetime.date.today() return self.agent_sale.filter(State="Pending",Date_created__year=today.year,Date_created__month=today.month) #FILTERED SEARCH def sfget_totals(self): return self.agent_sale.all() def sfget_confirmed(self): return self.agent_sale.filter(State="Confirmed") def sfget_debi(self): return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted") def sfget_requested(self): return self.agent_sale.filter(Debi_status="Requested") def sfget_cancelled(self): return self.agent_sale.filter(State="Cancelled") def sfget_pending(self): return self.agent_sale.filter(State="Pending") #THIS … -
django forms for adding new elements
I've got in views.py code for my view to add new docs to database: def doc_creation(request): # add_form = forms.DocAddForm(request.POST or None) if request.method == 'POST': add_form = forms.DocAddForm(data=request.POST) if add_form.is_valid(): new_doc = add_form.save(commit=False) rnd_nip=TestClass() new_doc.doc_client_nip = rnd_nip.random_client_nip() new_doc.added_by_2 = request.user new_doc.save() else: add_form = forms.DocAddForm() else: add_form = forms.DocAddForm() return render(request,'doc_new_2.html',{'add_form':add_form}) my model code is: class Doc(models.Model): doc_client_nip = models.CharField(blank=False,null=False,max_length=100,validators=[MinLengthValidator(10)],primary_key=True) doc_application_id = models.CharField(blank=False,null=True,max_length=100,validators=[MinLengthValidator(17)]) added_by_2 = models.ForeignKey(User, on_delete=models.CASCADE,null=True) TestClass() with its method random_client_nip() is used to generate random value of this field The problem is every time when I try to submit new record nothing is added to database page is reloaded to empty form but I don't receive any error. What is going on? Is the field added_by_2 problem? -
Models and forms in Django
Is forms and models run parallelly in Django? I've created a forms.py in my app and in that forms.py I've created a loginform insted of forms.py I've created AbstractUser and registration table in models.py , then import this loginform to models.py(from user_app.forms import LoginView). Then in forms.py import the models.py AbstractUser class.(I've named this class as user_type .. from user_app.models import user_type). I got this error File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py", line 7, in from user_app.forms import LoginForm File "D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\forms.py", line 2, in from user_app.models import user_type ImportError: cannot import name 'user_type' from 'user_app.models' (D:\PROJECT\Digital-Vehicle-Project\digi_vehicle\user_app\models.py) -
Import local python packages elegantly?
I like approaches of local package management in Flutter/Dart and Rust very well, and hope there could exist some similar solution in Python. For example, I have a utility python package at /path/of/the/utility containing dozens of python files, and a myapp package at /path/to/my/app. For myapp to depend on utility, if I were using Flutter/Dart or using Rust, I could write down a line like: utility: path: /path/of/the/utility And then happily import it like import 'package:utility/somefile.dart. (The Rust case is similar so I do not repeat.) However, with Python, I have not found out such solution (pip does not seem to know this; neither is conda). Currently I have to use the following ugly approach: // myapp/somefile.py import sys sys.path.append('/path/of/the/utility') import utility and also manipulate my IDE (Intellij IDEA in my case) such that it understands this myapp package depends on utility package and do not give me a big red underline. Remark: It may not be possible (is it?) to let /path to be the package root and myapp to be a subpackage, because: (1) The myapp, for example, can be a Django project. (2) It will be hard to configure the ide (Intellij IDEA in my case) if … -
How to maintain a table of all proxy models in Django?
I have a model A and want to make subclasses of it. class A(models.Model): type = models.ForeignKey(Type) data = models.JSONField() def compute(): pass class B(A): def compute(): df = self.go_get_data() self.data = self.process(df) class C(A): def compute(): df = self.go_get_other_data() self.data = self.process_another_way(df) # ... other subclasses of A B and C should not have their own tables, so I decided to use the proxy attirbute of Meta. However, I want there to be a table of all the implemented proxies. In particular, I want to keep a record of the name and description of each subclass. For example, for B, the name would be "B" and the description would be the docstring for B. So I made another model: class Type(models.Model): # The name of the class name = models.String() # The docstring of the class desc = models.String() # A unique identifier, different from the Django ID, # that allows for smoothly changing the name of the class identifier = models.Int() Now, I want it so when I create an A, I can only choose between the different subclasses of A. Hence the Type table should always be up-to-date. For example, if I want to unit-test the behavior … -
Django ManyToManyField Model Manager
In my Python Django 3.7 source code I have the following models: class ExampleForeignKey(models.Model): name = models.Charfield(max_length=200) fields = models.ManyToManyField('ExampleField', related_name='example_foreign_keys') class ExampleField(models.Model): name = models.Charfield(max_length=200) I experience an issue with database duplication when using threading with the source code: example_field_obj = ExampleField(name='example_field_name') example_foreign_key_obj = example_field_obj.example_foreign_keys.get_or_create(name='example_foreign_key_name') I have managed to override the model manager get_or_create() method and applied a multithreading.Lock() in other cases where the model manager is being used directly in the case of direct 1:1 relationships however I don't know whether it is possible to apply the same principle in the case of ManyToManyField relationships? Apologies if this has been asked about before elsewhere - I can't seem to find much information on this particular issue. -
Celery task worker exits with WorkerLost exception and billiard.exceptions
I have celery running on a server with my Django app, the app is listening for data being posted and once data is posted it tosses that data to a celery task. In my django admin when a lot of data is sent the tasks end up failing by giving the error {"exc_type": "WorkerLostError", "exc_message": ["Worker exited prematurely: signal 9 (SIGKILL) Job: 134."], "exc_module": "billiard.exceptions"} I cannot figure out how to fix this, any help would be much appreciated -
Django problem to run python manage.py runservice
I tried to execute the commande under virtual environment: python manage.py runservice, it was still working yesterday, but then today when I run again, it shows all these Errors that I don´t understand what it means. My codes are correct, so I am lost. If anybody could help to explain me what shall I do please? output from cmd terminal enter image description here -
Django Rest Framework filtering a field with null and multiple values
I am using Django Rest Framework and want to filter the queryset in a view based on a certain field name. The filter values would be null and additionally any other particular value for the field blog_category which is a ForeignKey value. So filter query should be on two query params class Blog(ListCreateAPIView): permission_classes = [DjangoCustomModelPermissions] queryset = Blog.objects.all().select_related("blog_category") serializer_class = Blog_Serializer pagination_class = CustomPageNumberPagination filterset_fields = {'blog_category': ['isnull', 'exact', 'in']} I have added the lookup fields isnull to filter null values I have tried the following url requests but they do not work /blog/?blog_catgeory__in=1,null /blog/?blog_catgeory__in=1,isnull /blog/?blog_catgeory__in=1,isnull=true /blog/?blog_catgeory__in=1&blog_category__isnull=true How do I get this work? -
how to detect when web.whatsapp.com qrcode changes in webwhatsapi in django
I want my django application to load web.whatsapp.com so I obtained the page through a screenshot, but before the image get shown in the web page qrcode is reloaded. Please how can i reload the qrcode on my webpage through a screen shot as it is reloading in web.whatsapp. This is a sample of my code def qr_code_image(): whatapidriver.wait_for_login(90) . return HttpResponse(json.dumps({"whatapp_img":{"whats_img":"directory of the screenshot"}}), qr_code_image, content_type ="application/json", status=status.HTTP_200_OK) -
Django - possible to pass Model Enums into Template Javascript?
Is it possible in Django to pass in enum values from a model Django HTML Template - JS at bottom E.g. Can I in JS, do something like `var enumValue1 = "{{employment_ukrightowork_form.right_to_work_selection}}.UKRightoWorkSelection.PASSPORT" Django MODEL If my model in model.py looks like: # U.K. RIGHT TO WORK MODEL class UK_Right_To_Work(models.Model): class UKRightoWorkSelection(models.TextChoices): PASSPORT = 'Passport', _('U.K. or Irish - Passport') BIRTHCERT = 'Birth Certificate & N.I. Number', _('U.K. or Irish - Birth or Adoption Certificate + Proof of National Insurance Number') CERTOFREG = 'Certificate of Registration & N.I. Number', _('U.K. or Irish - Certificate of Registration or Naturalisation + Proof of National Insurance Number') right_to_work_id = models.BigAutoField(verbose_name='U.K. Right to Work ID', primary_key=True, serialize=False, auto_created=True) right_to_work_selection = models.CharField(verbose_name='U.K. Right to Work selection', max_length=41, choices=UKRightoWorkSelection.choices, blank=False, null=False, default=UKRightoWorkSelection.PASSPORT) -
ordery_by filter is not working properly in django
data = models.Booking.objects.filter(center__isnull=False,org_type='homedx').order_by('-created_at') return data.order_by( Case( When ( booking_status="resampling", then=Value(0) ), When ( booking_status="sample not received", then=Value(1) ), default = Value(1) ) ) created_at is DateTimeField in Booking Model. Here i have ordered by choice field and for that i have used Case, When and Value method from django.db.models. But when i am using this it is ignoring order_by created_at. I mean when these two conditions are met. i want to get the data in order of latest date. Why it is not working? Thank you !! -
Select2 widget showing on Django Admin site but not on the form template in Django4
I have two object models, NewsObject and StockObject. The stock object is a foreign key in the news object. class stockObject(models.Model): stock_name = CharField(max_length=100, blank=True, null=True) stock_tag = CharField(max_length=100, blank=True, null=True) def __str__(self): return self.stock_name class newsObject(models.Model): title = CharField(max_length=100, blank=True, null=True) body = TextField(blank=True, null=True) stock = ForeignKey(stockObject, on_delete=models.SET_NULL, blank=True, null=True) I have used autocomplete_fields property in the ModelAdmin class as I want a searchable dropdown for stocks in news. I have also added search_fields in the stocks ModelAdmin as mentioned in the documentation. This is what my admin.py looks like: class stockAdmin(admin.ModelAdmin): list_display = ['stock_name', 'stock_tag'] search_fields = ['stock_name'] class newsAdmin(admin.ModelAdmin): list_display = ['title', 'body', 'stock'] search_fields = ['title', 'body', 'stock'] autocomplete_fields = ['stock'] Now, the issue is that I get a searchable dropdown on the Django Admin site for this field, but it is only a dropdown (not searchable) on the actual template screen. I have a basic view which calls the template, like so: Views.py def createNews(request): form = NewsForm() if request.method == 'POST': form = NewsForm(request.POST) if form.is_valid(): form.save() return redirect('/backoffice/') context = {'form' : form} return render(request, 'NewsForm.html', context) And NewsForm.html is: {% extends "base.html" %} {% load static %} {% block content %} … -
how to get users id in django model?
I need to get id from logged user to filter query in models.how to get users id in django model? Thanks in models.py: class Portfo(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) sell = models.ForeignKey(Sell, on_delete=models.CASCADE, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) profit = models.PositiveIntegerField(null=True) final_amount = models.IntegerField(null=True) def __str__(self): return self.product.name def final_amount(self): final_amount = 0 buy = Buy.objects.filter(product_id=self.product.id, owner__exact=...) sell = Sell.objects.filter(product_id=self.product.id)