Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Video upload and view in different resolution in django
I am building a video streaming app like youtube in django for learning purposes. I want to implement the functionality of uploading video by user and view it in different resolutions like 360p, 480p etc. I dont know how to achieve this.. Should I save all the versions of video?? Wouldn't that be redundant?? Also how to convert the video in different resolutions! I want to use aws s3 for this. -
django-rest-framework: invalid regular expression in url_path
I have a view and action defined in it: class V(mixins.UpdateModelMixin, GenericViewSet): `` some codes`` lookup_field = 'uuid' @action(detail=True, methods=['put'], permission_classes=[IsAdminUser], url_path='approve/(?P<uuid>[\w-]+)') def approve(self, request, *args, **kwargs): obj = self.get_object() `` some codes `` The app doesn't run because of: django.core.exceptions.ImproperlyConfigured: "^url/(?P[^/.]+)/approve/(?P[\w-]+)/$" is not a valid regular expression: redefinition of group name 'uuid' as group 2; was group 1 at position 46 The correct configuration would be like ^url/approve/(?P<uuid>[\w-]+)/$, but as the error says, it's another pattern and I don't mean it. Any idea would be appreciated -
Django - Different user types with different registrations
I need to create two (and later more) user types: Individuals and Companies. When a user registers, they need to select what type they are. Depending on that, they need to fill in different forms based on each type's attributes, and later have different permissions. What I have tried so far is extending the AbstractUser model to include booleans for each user type: class User(AbstractUser): email = models.EmailField(unique=True) is_individual = models.BooleanField(default=False) is_company = models.BooleanField(default=False) Then I created two extra "Profile" models: class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='company_profile') company_name = models.CharField(max_length=100, null=False, blank=True, help_text="Company name.") contact_email = models.EmailField(null=True,blank=True) def save(self, *args, **kwargs): super(Company, self).save(*args, **kwargs) class Individual(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='individual_profile') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) avatar = models.ImageField(null=True) def save(self, *args, **kwargs): super(Individual, self).save(*args, **kwargs) I also set up signals to automatically create the profile when a user is created: @receiver(post_save, sender=User) def create_company_profile(sender, instance, created, **kwargs): if instance.is_company: if created: Company.objects.create(user=instance) elif instance.is_individual: if created: Individual.objects.create(user=instance) else: pass @receiver(post_save, sender=User) def save_company_profile(sender, instance, **kwargs): if instance.is_company: instance.company_profile.save() elif instance.is_individual: instance.individual_profile.save() else: pass This works when I add a user via Django Admin. If I tick is_individual, the an individual is added to the Individuals … -
500 (Internal Server Error) and Unexpected token < in JSON at position 0
I'm trying to create a website based on guides. When it came to updating the basket through the buttons (decrease and increase), then trying to click on them, errors are issued: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, which refers to .then((data) => { location.reload() }); cart.js:24 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) which refers to fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, and i have error in console pycharm line 104, in updateItem productId = data['productId'] KeyError: 'productId' code cart.js: var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productId = this.dataset.stuff var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser') { console.log('User is not authenticated') } else { updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Stuff.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = … -
How to cache data in django channels and celery?
I am building a web-app using django channels. I also have a task function which i run periodically ( every 30s) using celery beat. This task function sends data to my web-socket every 30s. Now, if a consumer joins my channel group, he has to wait for some time until my next data arrives. But what I want is to show the new consumer my previous data, until new one arrives. So i have to cache my previous data somewhere. What is the correct way to do that? I know using redis but how in django-channels? -
how to add an integer to current month and then update datefield in django
I am just trying to get the current month and then add an integer to it for example 3 months, then update my datefield obj to that value. my view.py : def worklist(request,pk): vessel_id = Vessel.objects.get(id=pk) vessel = Vessel.objects.all() component = vessel_id.components.all() components = component.prefetch_related( 'jobs').filter(jobs__isnull=False) if request.method == 'POST' and 'form-execute' in request.POST: this_job = Job.objects.get(pk=request.POST.get('execute_job_id')) job_type = this_job.type job_due_date=this_job.due_date job_interval =this_job.interval dt = datetime.datetime.today().month if job_type =='O': this_job.delete() else: job_due_date = dt + relativedelta(months=job_interval) return HttpResponseRedirect(request.path_info) context = {"component": components,"vessel_id":vessel_id,"vessel":vessel } return render(request, "worklist.html", context) i just want say thisjob due date equal to this month plus this job interval which is an integer here is model.py if it helps : class Job(models.Model): job_type = ( ('I', 'Interval'), ('O', 'One time'), ) name = models.CharField(max_length=100) description = models.CharField(max_length=100) type = models.CharField(max_length=1, choices=job_type) interval = models.IntegerField() is_critical = models.BooleanField() due_date = models.DateField() rank = models.ManyToManyField(UserRank,related_name='jRank') component = models.ForeignKey( Component, related_name='jobs', on_delete=models.CASCADE) runninghours = models.ForeignKey( RunningHours, related_name="RHjobs", on_delete=models.CASCADE,blank=True) def __str__(self): return self.name -
How to add points to an IntegerFiedl with serializer DRF
I've got serializer like this and each time i do Put on that url, i want the number_of_points increase(+=1), but now when i do it, it stays the same and doesnt change. Do you have any idea how to fix it? class Answer(models.Model): number_of_points = models.IntegerField(default=0) class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points += 1 return instance class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) path('answers/<int:pk>/addpoints', AddPointsAnswer.as_view()), -
Custom user model with python-social-auth on django
I am new to this so sorry if what I am asking sounds silly. I am using only steamopenid on python-social-auth for the login, that's the only option the customer will have. Now I want to create my own custom user model where I can keep the user data once they log in. I believe it should not be too complicated but I can't find anything that seems correct. I have managed to get username but I want to also get everything that's under user social auths table and users table. The fields that are saved into python-social-auth generated table: settings.py SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'main.pipeline.save_profile', ) pipeline.py from .models import CustomUser def save_profile(backend, user, response, *args, **kwargs): CustomUser.objects.create( user = user, ) models.py from django.db import models from django.conf import settings # Create your models here. class CustomUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Django model querryset changed into json serializable not working
I have model objects saved in session as below from context-processors. students = Student.objects.all() studente = serializers.serialize('json', students) request.session['students'] = students In my model Forms I have class NewIssueForm(forms.ModelForm): def __init__(self,*arg,students, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) self.fields['borrower_id'] = students I get an error when I try to run. ''''' File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 994, in render return render_value_in_context(output, context) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 973, in render_value_in_context value = str(value) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\html.py", line 376, in <lambda> klass.__str__ = lambda self: mark_safe(klass_str(self)) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 132, in __str__ return self.as_table() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 270, in as_table return self._html_output( File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 198, in _html_output bf = self[name] File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 163, in __getitem__ self._bound_fields_cache[name] = field.get_bound_field(self, name) AttributeError: 'str' object has no attribute 'get_bound_field' How can I make this field populate the students itemswithout the error? -
Django: packaging an app with a ForeignKey to settings.AUTH_USER_MODEL
I have an app that I use in many of my projects and want to package it. A model in the app has ForeignKey and ManyToManyField to settings.AUTH_USER_MODEL class LogEntry(models.Model): authenticated_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='log_entries', on_delete=models.CASCADE) involved_users = models.ManyToManyField(to=settings.AUTH_USER_MODEL, blank=True, through='LogUsers', related_name='other_log_entries') migrations of this app in different projects refer to different user models. Sometimes a custom user model ('user', ... to='registry.RdpUser) other times the standard django.contrib.auth.models.User. Is it possibile to package the app with a migrations that works for both cases? What's the best approach for a packaged app with a ForeignKey to settings.AUTH_USER_MODEL? I know a solution would be to use GenericForeignKey but I would like to avoid that. -
Django form: ¿How can I wrap checkbox widget and label within a div?
¿How can I wrap checkbox and label in django form? I have django form with a BooleanField. That field renders like this: <div id="..." class="custom-control custom-checkbox" style=""> <input type="checkbox"....> <label for="...."....> <div> help_text <div> </div> I want to wrap the input and the label but not the help text: I want something like: <div id="..." class="custom-control custom-checkbox" style=""> <div id="wrapper_div"> <input type="checkbox"....> <label for="...."....> </div> <div> help_text <div> </div> -
how to setup django ssl for development purpose?
One notice: I'm new to python but was able to run django based project for mobile. There's a js part where I need to add some functionality about camera and what I found the web page needs to be run from https:// as I need access from my phone. Is running nginx with self signed cert the best solution? Will it working using https://192.168.0.xxx? -
why does clean_password2() method work but not clean_password1() in Django usercreationform
I am trying to figure out why this works if someone could maybe explain it to me. I've just created a custom user model (shown below) and for the password validation it uses the clean_password2(self): (shown below) method however when I try to use clean_password1(self): (shown below) the validation does not work. why? Surely using either password1 or password2 to clean the data would work since they are the same? Django docs state that we can use clean_<fieldname>(): methods to clean/validate data and since password1 is a fieldname in my mind that should work. Custom user model class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True This works class UserCreationForm(forms.ModelForm): password1 = forms.CharField( label="Password", help_text=password_validation.password_validators_help_text_html(), widget=forms.PasswordInput, ) password2 = forms.CharField( label="Confirm Password", … -
Django project is not reading my static css file
I am working on a django project and for some reason the style.css file is not read. However, my static images are working. Not really sure what the issue is, any help is greatly appreciated. There are also no errors showing in the console and terminal.. Link to my github repository https://github.com/Amanuel763/petwebsite -
Remain authenticated in a mobile application
I am working on an Ionic mobile app and have a django backend. We currently use JWT authentication in order to access the django backend (multiple applications use this backend including a react frontend). So the current auth method needs to stay in tact. Now that we are working on an app we want the user to stay logged in after entering his credentials once on the app. I've been researching a good way to do this all day but can't seem to find a clear answer. What is the best option to keep the user authenticated? Should I set a high expiration on the refresh token? (Not sure if that is secure..) Should I use session auth? I found it that Django mostly supports this on services on the same domain. Seems like you have to relax quite a few security settings which doesn't seem to be the right solution. I am not sure where to go from here. Do you guys have any suggestions? -
Add products with different sizes and price to Cart | Django
I use session's to create a shopping cart. I have a product model and a model for Product-sizes, which I define the size-title(XL , etc) and price of product in it . So that I can have products with different sizes as well as different prices. But my logic has some problems if I add product_1 with size A , it's ok ... if I add product_1 with size B , it's ok ... but when I'm trying to add same product with different sizes at same time the cart only shows the price of first size #shop/models.py class ProductSizes(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() picture = models.ImageField(upload_to="products/%Y/%m/%d" ) class Product(models.Model): name = models.CharField(max_length=100) size = models.ManyToManyField(ProductSizes , blank=True , related_name="sizes" ) price = models.IntegerField() #cart/cart.py from django.conf import settings from shop.models import Product class Cart: def __init__(self,request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart # add to cart def add(self,product,size_,quantity=1,override_quantity=False): product_id = str(product.id) print(product.size.name) if product_id not in self.cart : if size_ != None: if size_.off_price: self.cart[product_id] = {'quantity':0,'price':size_.off_price} elif size_.price: self.cart[product_id] = {'quantity':0,'price':size_.price} else: if product.off_price: self.cart[product_id] = {'quantity':0,'price':product.off_price} else: self.cart[product_id] = {'quantity':0,'price':product.price} if override_quantity: self.cart[product_id]['quantity'] = … -
how to write nested tuples in django using django-environ
I am using django-environ to configure my Django app with environment variables. I am trying to write tuples data in .env From django-environ documentation tuples are supported: tuple: (FOO=(a,b,c)) But I couldn't find anything about nested tuples. (Also about nested dicts and lists) I am trying to write nested tuples: nested_tuple_setting = (('setting10', 'setting11'), ('setting20'), ('setting21')) -
I've a problem with django update in crud?
I have a problem where, in the update part when the form is displayed, in whichever fields there is more than one word (like name, address) the first one is only displayed in the form to be edited, the rest is gone. I went through the whole project multiple times but I can't find the solution. Please help me. Thanks in Advance!!! base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> </head> <body> <div class="container" align="center"> {% block body %} {% endblock %} </div> </body> </html> create.html <!DOCTYPE html> {% extends "testAppTem/base.html" %} {% block body %} <div class="jumbotron"> <h1>Employee insertion form</h1><hr> <form method='post'> <table border=3> {{form}} </table> {%csrf_token%}<br><br> <input type="submit" value="Insert" class="btn btn-lg btn-danger"> </form> </div> {% endblock %} index.html <!DOCTYPE html> {% extends "testAppTem/base.html" %} {% block body %} <div class="jumbotron"> <h1><u>Employee Information Dashboard</u></h1><br><br> <table border=4> <thead> <th>Employee Name</th> <th>Employee Number</th> <th>Employee Salary</th> <th>Employee Address</th> <th>Actions</th> </thead> {% if employees %} {% for e in employees %} <tr align=center> <td>{{e.enum}}</td> <td>{{e.ename}}</td> <td>{{e.esal}}</td> <td>{{e.eaddr}}</td> <td><a href="/update/{{e.id}}" class="btn btn-sm btn-dark">Update</a> <a href="/delete/{{e.id}}" class="btn btn-sm btn-info">Delete</a></td> </tr> {% endfor %} {% else %} <p>There is no data...</p> {% endif … -
Cannot connect JS Event Source to Python (Django) backend server
I'm working with Django Framework + Javascript and want to create a server-sent event which gonna send messages to the front-end. Here is my Js-client part: btn.addEventListener('click', function(event){ console.log('started...'); var url = new URL('http://127.0.0.1:8000/get/stream/data/'); var source = new EventSource(url); source.onopen = function(){ console.log('Source has been connected....'); }; console.log(source); source.onmessage = function(event){ data = JSON.parse(event.data); console.log('on message event', event, data); console.log(event); }; source.onerror = function(err) { source.close(); console.error("EventSource failed:", err); }; source.onclose = function(){ evtSource.close(); console.log('event source has been closed'); } }); Python-Django part: def prepare_stream_data(): import json from django.core.serializers.json import DjangoJSONEncoder while True: for i in range(30): yield json.dumps('%s' % i, cls=DjangoJSONEncoder) print(i) time.sleep(5) def send_stream_data(request): stream_data = prepare_stream_data() response = django.http.StreamingHttpResponse(stream_data, content_type='text/event-stream') return response urls.py path('get/stream/data/', main_course_api.send_stream_data, name='stream_data') Django basically works and I see the result in console...., when I click on the button, but it shows me in JS console, that event source is not connected (readyState equals to 0) and does not receive any messages) :( -
What should I do to show the previous data when I'm updating some information on website in Django?
Here, on my site admin can update product information. Hereafter clicking that green update button a form will appear. but I want that as admin is updating information, previous information will also appear in this form. So, I want to show previous data already filled up in this form. How can I do this as I'm not using any ModelForm here views.py def update_product(request,product_id): if request.method=='POST': product = Product.objects.get(pk=product_id) product.product_name = request.POST['product_name'] product.category = request.POST['product_category'] product.price = request.POST['product_price'] product.image = request.FILES['product_photo'] product.description = request.POST['product_description'] product.pub_date = datetime.today() product.save() messages.success(request, 'Product has been updated successfully!!!') return redirect("/") else: return HttpResponse("404-Not Found") form is inside a modal in fruit.html: <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#updateModal"><i class="bi bi-arrow-repeat"></i></button> <div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="updateModalLabel">Add New Products</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form action="{% url 'update_product' i.product_id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Product Name:</label> <input type="text" class="form-control" id="product_name" name="product_name" placeholder="E.g. Potato Regular" required /> </div> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Product Category:</label> <select class="form-select" aria-label="Default select example" id="product_category" name="product_category" required> <option selected>Choose Category</option> <option value="Fruit">Fruit</option> <option value="Vegetable">Vegetable</option> <option value="Toy">Toy</option> <option value="Medicine">Medicine</option> <option value="Stationery">Stationery</option> <option value="Pet">Pet</option> <option value="Electric">Electric</option> … -
Django Urls loads the page and shows 404 status
I am trying to learn Django but today I faced a problem. I have got an app that is called 'users' and ı have URLs in it. Here is the urls.py file in users app. urlpatterns = [ path('signup/', views.signup, name = "signup"), path('logout/', views.user_logout, name='logout'), path('dashboard/', views.dashboard, name='dashboard'), path('profile/', views.user_profile, name='profile'), ] ı included it in main urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name = 'index'), path("users/", include('users.urls')), path('customer/', include('customer.urls')) ] When I am trying to get a get request to the URL 127.0.0.1:800/users/dashboard terminal shows me an 404 error and it loads the page without error and I could not figure out why it happens. I am not sure if it's interested with it but /users/dashboard view has decorator loginrequired(login_url='index') [03/Feb/2022 18:08:13] "GET /users/dashboard/ HTTP/1.1" 200 6610 Not Found: /users/dashboard/... [03/Feb/2022 18:08:13] "GET /users/dashboard/... HTTP/1.1" 404 3324 -
How can I select a user and notify him that he's selected in django?
I'm working on my final year project which is campus recruitment system in django. I am a beginner and learning python and django. I want to create a module as Selection Panel and when the candidate will click on it he'll know whether he is selected for the particular job by particular company or not. I'm unable to understand the what and how should I do? -
Django Flashcards view (mark as known)
i'm currently stuck with the view of a Django Flashcards Website to mark the cards as 'known'... he're is the code, the previous card works well..: class CardView(View): template_name = 'card.html' def get(self, request, set_id, card_id): selected_set = get_object_or_404(Set, pk=set_id) try: selected_card = selected_set.card_set.get(id=card_id) except (KeyError): return render(request, 'set_index.html',) else: context = { 'set': selected_set, 'card': selected_card, } try: known_card = selected_set.card_set.filter( id__lt=card_id).order_by("id") Card.known +=1 except(KeyError, AssertionError): pass else: context['known_card'] = known_card try: prev_card = selected_set.card_set.filter( id__lt=card_id).order_by("id") prev_card = prev_card[len(prev_card) - 1] except (KeyError, AssertionError): pass else: context['prev_card'] = prev_card -
User id is not passing through in the URL in Django rest framework
I'm passing the user id in the URL but its taking '0' http://localhost:1400/api/Values/GetLeaves/0 As it is suppose to show the list of id when I select the particular id it should show the leaves of the particular member but it just showing only '0'. when I print the id which pass through it just showing '0' This is what I have tried views.py: @api_view(['GET']) def GetLeaves(request, userid): if request.method == 'GET': print("GetLeavesBRG--->", userid) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GPHGetUserLeaveDetailsBRG] @user=%s',(userid,)) result_set = cursor.fetchall() print(result_set) response_data = [] for row in result_set: response_data.append({ "FromDate":row[0] }) return Response(response_data) urls.py: path('Values/GetLeaves/<int:userid>', GetLeaves, name='GetLeaves') -
django-simple-history how to get the related foreign key objects
I have a model named Order and another OrderItem. The OrderItem table has a foreign key to the Order table. Now I have the [simple-history][1] installed and setup on both the models. I try to get the Order history and also fetch related OrderItem from history using the related name on the OrderItem table but it returns an error: AttributeError: 'HistoricalOrder' object has no attribute 'order_items' Here is my Order and OrderItem table. class OrderItem(models.Model): order = models.ForeignKey( "Order", on_delete=CASCADE, related_name="order_items" ) content_type = models.ForeignKey(ContentType, on_delete=models.RESTRICT) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") history = HistoricalRecords() ....... class Order(models.Model): po_id = models.CharField(max_length=50, unique=True, blank=True, null=True) history = HistoricalRecords() ..... Following command gives me an order. order = Order.history.filter(id=102).first() But if I run order.order_items.all() then I get the attribute error. If I run the query on the actual model then I get the order_items by using below command. Order.objects.get(id=102).order_items.all() Is it possible to get the order_items from the history table in the same way as normal django models. And how can I do this to work. Thank you. [1]: https://django-simple-history.readthedocs.io/en/latest/index.html