Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
URL Formatting in Django Template
In my index.html file within my Django templates is a multitude of JIRA queries that pass in a couple of variables. Here's an example: https://bugs.jira.com/issues/?jql=type%20in%20(Bug%2C%20%22New%20Feature%22%2C%20Improvement%2C%20Sub-task%2C%20Task%2C%20%22DSCI%20Experiment%22%2C%20%22Library%20Update%22%2C%20Request%2C%20Work%2C%20Event%2C%20Problem%2C%20Documentation)%20AND%20status%20changed%20to%20reopened%20by%20{{username}}%20after%20%27{{timelineDateStart}}%2000%3A00%27%20before%20%27{{timelineDateEnd}}%2000%3A00%27%20ORDER%20BY%20project%2C%20key');">{{count}}</a> With >10 of such URLs, the index file is quite cluttered and spans a great deal of width per line in the IDE. Is there a better practice for formatting or storing these URLs? Or is what I'm currently doing considered best practice? FWIW, I am a new django developer. -
Django and ajax: reloading value on template after posting rate
in my project user can rate movie. Movie class has get_average method and I display it like this: <p><div id="average">{{ movie.get_average }}</div></p> I want to reload this value after posting rate. My current rate.js looks like: $(document).ready(function(){ $("#rateButton").click(function(){ var serializedData = $("#rateForm").serialize(); $.ajax({ url: $("rateForm").data('url'), data: serializedData, type: 'post', success: function(data){ console.log(data); $('#myRate').html(data); } }) }); }); I was trying few ways to resolve it but it doesn't work. Maybe there is problem with my code. For example i tried $('#average').html(data); my view.py class MovieDetailView(FormMixin, DetailView): model = Movie template_name = 'main/detail_movie.html' context_object_name = 'movie' form_class = RateForm def get_context_data(self, **kwargs): context = super(MovieDetailView, self).get_context_data(**kwargs) if Rate.objects.filter(movie=self.object, sender=self.request.user).exists(): context['form'] = RateForm( initial={ 'movie': self.object, 'choice': Rate.objects.filter(movie=self.object, sender=self.request.user).first().choice }) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if request.method == 'POST': if form.is_valid(): new_rate, _ = Rate.objects.update_or_create( sender=self.request.user, movie=self.object, defaults={'choice': form.cleaned_data['choice']} ) return JsonResponse({'rate': model_to_dict(new_rate)}, status=200) else: return self.form_invalid(form) -
Issue with pagination when filtering
I'm using a simple form to order my result by "title "-title" "price" "-price" : <form class="form-inline" action="{% url 'books:display-filtered' %}" method="get"> {% csrf_token %} [....] <select class="border-0 bg-light search-target-input-md search-style rounded px-2 search-target-input-md-size" name="filtering" id="Search_Target"> <option value="title"> title A-Z </option> <option value="-title"> title Z-A </option> <option value="price"> price ascending </option> <option value="-price"> price descending </option> </select> [... then the submit button ] Thrn i capture the selected option in my view like this : def home_display_books_filtered(request): main_list = Books.objects.order_by( request.GET["filtering"]).filter(pub_date__lte=timezone.now()) paginator = Paginator(main_list, 24) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) side_list = Books.objects.order_by( "-pub_date").filter(pub_date__lte=timezone.now())[:5] context = {"page_obj": page_obj, "side_list": side_list} return render(request, "books/filtered_page.html", context) The first page is rendered perfectly but when switching to the next one I get MultiValueDictKeyError at /books/index_filtering/ I'm quite sure it's because of the link it follows ( I assume it's requesting for a new dictionary value but nothing is provided, am I wrong ? ) : <a class=" text-primary text-decoration-none " href="?page={{page_obj.next_page_number}}"> <i class="fas fa-angle-right fa-lg"></i> </a> If anyone has an idea how to get a proper link from this button .. thanks in advance -
Child/Parent relation with two models, who are submitted to at the same time
I got two models: Invoice & InvoiceItem My InvoiceItems model got an ForeignKey, which relates to my Invoice model. Now I want to make one form, displaying fields taken from both models, but with the option of multiple InvoiceItems if wished. How can I do this in practise? Visualisation of the wished result: So to make it clear: One form, that I via jquery allowed to add multiple inputs, so I can submit services to my InvoiceItem model, but the basic information you type in at the same time, like client, yourself etc. should be submitted to the model Invoice. Thank you in advance! -
XML Fields Not Unique Python Django
Devs, My XML file is here below. I am trying to pull moms phone number and dads phone number, however the field names aren't unique. How do i go about doing this ? Thanks <student> <_extension_data> <_table_extension> <recordFound>false</recordFound> <_field> <name>motherdayphone</name> <type>String</type> <value>732-555-555</value> </_field> <_field> <name>fatherdayphone</name> <type>String</type> <value>347-555-5555</value> </_field> </student> Code: mother_phone = student.find("_extension_data").find("_table_extension").find("_field").find("value").text <--- How would you write this ? Both field names for mom and dad are _field. -
problem with python requests on my server
Hello I have a problem I'm basically scratching my head over this. on my server side this happens; example link r = requests.get("http://www.instagram.com/{invalid username}/ checking the r.ok gives the result True r.status_code gives 200 example link2 r = requests.get("http://www.instagram.com/{valid username}/ Now I'm scratching my head as same thing yields different result on my local machine the invalid one returns a 404 the valid one returns a 200 Is there something I am missing? -
Celery beat running periodic task even after the given crontab schedule
I've been trying to debug my way into figuring out why my beat triggers tasks even after the time they're not supposed to run. So, I want to run a task every 15 mins from let's say 10am to 11pm and I have done this: Made an entry into django_celery_beat_periodictask like: # id, name, task, args, kwargs, queue, exchange, routing_key, expires, enabled, last_run_at, total_run_count, date_changed, description, crontab_id, interval_id, solar_id, one_off, start_time, priority, headers, clocked_id, expire_seconds 20, foo, app.tasks.foo, [], {}, , , , , 0, , 271, 2020-07-14 23:08:15, foo, 38, , , 0, , , {}, , The 38 above is an FK to django_celery_beat_crontabschedule which is a crontab specifying the run times, which looks like: # id, minute, hour, day_of_week, day_of_month, month_of_year, timezone '38', '*/15', '10-23', '*', '*', '*', 'Asia/Kolkata' That's how my foo looks like: @task() def foo(): print("Hello World") logger.info("Factorial of 5 {}".format(math.factorial(5))) print("Hello World") These are the versions of the packages I'm using: celery==4.3.0 django-celery-beat==1.5.0 django-redis==4.8.0 redis==3.3.8 Django==2.2.10 Now, the problem that I am facing is, my cron runs even after 11pm. I tried changing that to 5pm or 3pm. It doesn't seem to cause any effect on beat - which schedules it anyway every … -
Best practises for sending promotional/mass mail in Django with Amazon SES and hiding other recipients
I have surfed the internet 🌍 for a day but didn't find the perfect article which gives the best practices for sending mass emails. I have configured amazon ses using django-ses and mails are sending correctly. Now the problem is I don't know how people send mass mail, hide other recipients 🕵, which function they use, and what pattern they follow to make sending mass mail efficient and ease. Also, we are using templates for mail and below is the best solution I got by mixin all best things I found on the internet: # 1. 📜 Getting queryset of all recipients which will receive mail # (mine is a little bit different but at the end, it gives queryset of all emails - not list) subscribers = EmailNotificationSubscriber.objects.all().values_list('user__user_email', flat=True) # 2. Opening a connection # 3. [Looping] using `.iterator()` to fetch email one by one from queryset (I think this is to handle the cases where we have an email list of around 10k or even bigger) # 4. Creating EmailMessage instance and sending an email using `.send()` # Function to get HTML Message (instance of `EmailMessage`) def get_html_msg(subject, from_email, to, template_name, ctx, connection=None): message = get_template(os.path.join(settings.BASE_DIR, 'templates', 'email', … -
In Django can you create a field that is a table?
I am tryng to make a model in Django contain a table. I am inexperienced with Django. It should look like this: Image with every value editable, obviously I can use a stylesheet to edit it later. Ideally I would not have to make a character field for every single cell of the table as that would be extremely long winded. Hope someone can help! -
Animation back-ground
I am just trying to excute the same code in [https://codepen.io/arickle/pen/XKjMZY][1] ' but i am not getting give the output properly (java script is not working at all), I tried in Django as well as Notepad++ also but same problem comes. code here: <html> <head> <tittle>Tamil</tittle> <style> html { height: 100%; } body { height: 100%; margin: 0; overflow: hidden; background: linear-gradient(to bottom, #202020, #111119); } .rain { position: absolute; left: 0; width: 100%; height: 100%; z-index: 2; } .rain.back-row { display: none; z-index: 1; bottom: 60px; opacity: 0.5; } body.back-row-toggle .rain.back-row { display: block; } .drop { position: absolute; bottom: 100%; width: 15px; height: 120px; pointer-events: none; animation: drop 0.5s linear infinite; } @keyframes drop { 0% { transform: translateY(0vh); } 75% { transform: translateY(90vh); } 100% { transform: translateY(90vh); } } .stem { width: 1px; height: 60%; margin-left: 7px; background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.25)); animation: stem 0.5s linear infinite; } @keyframes stem { 0% { opacity: 1; } 65% { opacity: 1; } 75% { opacity: 0; } 100% { opacity: 0; } } .splat { width: 15px; height: 10px; border-top: 2px dotted rgba(255, 255, 255, 0.5); border-radius: 50%; opacity: 1; transform: … -
Extending Wagtail Modeladmin CreateView I get a NoReverseMatch and if I comment the code the routing problem persists
On wagtail modeladmin for a given model, I need to modify the Create_Button so that it shows a create view with a subset of model fields and adding an API call to an external service. Overriding the Edit Button I could do this seamlessly, just binding the property #wagtail_hooks.py class MyModelAdmin(Modeladmin): model = MyModel ... edit_view_class = MyModelEditView ... and on the MyModelEditView(EditView) just added my extended logic on the form_valid method. Following the same pattern, I created a MyModelCreateView(CreateView), added the property to MyModelAdmin as: create_view_class=MyModelCreateView which is defined like: #wagtail_hooks.py class MyModelCreateView(CreateView): """ we only want user to define 2 fields of the model, then call an API REST that returns the other fields, then save object to backend db """ panels = [ FieldPanel('field1'), FieldPanel('field2') ] def get_edit_handler(self): panels = self.panels edit_handler = ObjectList(panels).bind_to(model=MyModel, request=self.request) return edit_handler def create_mymodel(self, form): data = form.cleaned_data for field in data: data[field] = cleanup(field) res = requests.post(...) if res.status_code == 200: logger.info("created mymodel") ... else: logger.error(f"something went wrong: {res.status_code}\n{res.content}") ... return True def form_valid(self, form, *args, **kwargs): res = self.create_mymodel(form) try: self.form_valid(form, *args, **kwargs) except Exception: print(Exception) form_valid_return = super().form_valid(form, *args, **kwargs) return form_valid_return Once define this, with many doubts on … -
Child not in full parent's width on slick slider css
I am sing an slick slider with dynamic data, and I have realized that for some reason mates-grid-content (child) is not on the full width of the mates-container (parent) even tho I am using width: 100% on it. When cheking chrome's editor I realized that width on mates-grid-content is being set by default on the html and it changes when the page becomes thinner or widther but it is never 100% width. I will like to make mates-grid-content full width of parent but I dont know how can this be fixed. html ( I have) <div class="mates"> <div class="mates-container" id="mates-containerrr"> {% for content in contents %} {% if content %} <div class="mates-grid-content" id="mates-grid-contenttt"> <div class="mates-grid-1-1-content"> <div class="mates-grid-1-content"> <div class="mates-item-content"> <img class="mate-pic" src="{{ user.profile.profile_pic.url }}" > </div> <div class="mates-item-content"> <a href="{% url 'profile' username=content.user.username %}" style="float: left">{{ content.user }}</a> </div> <div class="mates-item-content"> </div> </div> </div> </div> {% endif %} {% endfor %} </div> </div> <script type="text/javascript"> $(document).ready(function(){ $('.mates-container').slick({ infinite: true, speed: 450, slidesToShow: 1, slidesToScroll: 1, prevArrow: "<button class='prev-h' id='prev-hh'>prev</button>", nextArrow: "<button class='next-h' id='next-hh'>next</button>", }); }); </script> html (from chrome's editor) <div class="mates-grid-content slick-slide slick-current slick-active" id="mates-grid-contenttt" data-slick-index="0" aria-hidden="false" style="width: 315px;" tabindex="0"> css #mates-containerrr { display: flex; width: 60%; height: 100%; … -
Specialising @action with partial application gives TypeError
I need similar @action detail routes on multiple ViewSets. I want to make sure they remain consistent. My first attempt was to put them in a base class and have my ViewSets inherit from it, but because decoration of methods is not inherited DRF does not recognise my @actions as such in the inheriting classes. So, I am trying to specialise @action by using partial application: this way I don't depend on inheritance but I can still avoid duplicating its arguments all over the place (remember, I need the same @action on many ViewSets). This leaves me with something like this: specialised_action = partial(action, methods=["post"], detail=True, url_path="my-action-url") class SomeViewSet(GenericViewSet): @specialised_action def action_handler(self, request, *args, **kwargs): print("do something") But it doesn't work, I get this error: TypeError: action() got multiple values for argument 'methods' My questions: Why is methods passed multiple times? How can I fix this? Is there a better way to achieve consistent, duplication-free, @actions across many ViewSets? -
How to display a selected field in django Form?
I am creating a purchase order app with django. When creating an order, I am using a ForeignKey for the delivery address, based on the customer database. What I have been trying to achieve the last few days is to select one address from the customer database and display the field of the selected address. It doesn`t seem to work. How can I achieve this feature? views.py def create_order(request): form = OrderCreateForm(request.POST or None, request.FILES or None) if form.is_valid(): order = form.save(commit=False) order.save() return render(request, 'orders/detail.html', {'order': order}) context = { "form": form, } return render(request, 'orders/create_order.html', context) models.py(Order) class Order(models.Model): name = models.CharField(max_length=250, blank=True, null=True) notes = models.CharField(max_length=250, blank=True, null=True) site = models.ForeignKey(Chantier, default=1, on_delete=models.CASCADE, blank=True, null=True) company = models.ForeignKey(Company, default=1, on_delete=models.CASCADE, blank=True, null=True) contact = models.ForeignKey(Contact, default=1, on_delete=models.CASCADE, blank=True, null=True) project = models.ForeignKey(Project, default=1, on_delete=models.CASCADE, blank=True, null=True) models.py (Company) class Address(models.Model): name = models.CharField("Full name",max_length=1024,) address1 = models.CharField("Address line 1",max_length=1024,) address2 = models.CharField("Address line 2",max_length=1024,) zip_code = models.CharField("Postal code",max_length=12,) city = models.CharField("City",max_length=1024,) country = CountryField() class Meta: verbose_name = "Site Address" verbose_name_plural = "Site Addresses" forms.py class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['company','site','contact','notes'] html.py <div class="card-body"> <div class="row"> <div class="col-sm"> <h5 class="mb-3">Supplier Details:</h5> <div>{{ form.company … -
Django Image uploaded from the admin panel not located on the address after refreshing the site
When I upload the image from the admin panel, the image shows up on the site for the first time. But, after sometime when I reload the site, the image does not loads and when I search for the addres by clicking on "open image in new tab" it gives the following error: This is the error I'm getting I have deployed my site on Heroku server and using postgresql as the database. If anyone knows the solution, it will be of a great help. -
Comparison of queryset and list using template tags in Django
I have a list and a queryset that always consists of the same number of objects. query = object1, object2, object3 list = ['true', 'false', 'true'] I would like to always show my user object when the in list is true. In my case, the user should see object1 and object3 from query (because the first and last item on the list is true). I tried it: {% for object in query %} <!-- Show all objects in query --> {% if list.forloop.counter == 'true' %} <!-- get element from list and check if true --> {{ object.name }} <-- Show my object name from query if the equation is true --> {% endfor %} {% endfor %} But mine {{ forloop.counter }} does not work properly in markup. How can I get the expected result? -
Split media files in 2 servers
I manage a django project which host a lot of files uploaded by the users. Currently media files are hosted on the same server than the django project but I would like to store some of them in an amazon S3 bucket. I don't want to move all of them because the files are accessed really often and I want to minimize the cost. Is it possible to manage 2 differents sources for media files ? I don't think django-storages allow to do this. -
Question related ORM django and sqlite3 databse
I am creating an BOM App to generate a PDF file for Bill of Materials for our IT Network Department. I need help with database structure and foreign key to establish ORM. Based on these model I have created form which will take input from IT users and calculate the BOM for that instance using below models click here. Here we could have different vendors with each vendor has different device models types which includes parts/items which should tie into each other to utilize DRY principles and ORM mappings etc. Any basic layout should definitely help in this regards. Any ideas would be a great start for me as I am Network Architect and don't have lot of experience into programming world just started getting into python coding and learning django. class CiscoModel(models.Model): router_switch_type = models.CharField(max_length=50) def __str__(self): return self.router_switch_type class CiscoParts(models.Model): model = models.ForeignKey(CiscoModel, on_delete=None) part_number = models.CharField(max_length=50) voice = models.BooleanField(default=False) desc = models.CharField(max_length=200) service_duration = models.IntegerField(blank=True, null=True) unit_list_price = models.FloatField() qty = models.IntegerField() unit_net_price = models.FloatField(blank=True, null=True) discount = models.IntegerField(blank=True, null=True) extended_net_price = models.FloatField() def __str__(self): return self.part_number class RuckusModel(models.Model): switch_type = models.CharField(max_length=50) def __str__(self): return self.switch_type class RuckusParts(models.Model): model = models.ForeignKey(RuckusModel, on_delete=None) sku = models.CharField(max_length=50) desc = … -
Trying to do an INNER Join and display the result on the API
This question has been asked before but I cannot use any of the answers to my case. I'm trying to have the equivalent of this, to show the results on the API. SELECT denom_name,retail_name,retail_adr FROM denomination d INNER JOIN Retailer r ON r.id = d.retailer.id These are my models (models.py): class Retailer(models.Model): retail_name = models.CharField(max_length=30) retail_addr = models.CharField(max_length=300,null=True) def __str__(self): return self.retail_name class Denomination(models.Model): denom_name = models.CharField(max_length=1000) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) I've created a viewset on the views.py class DenomRetailViewset(viewsets.ModelViewSet): queryset = Denomination.objects.select_related('Retailer') serializer_class = DenomRetailSerializer But here lies the issue, at least one of them. I'm creating the serializer through the serializer.py class DenomRetailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model= retailer,denomination fields = ('denom_name','retail_name','retail_adr') But as you can see, the serializer cannot accept two models. And beside, I have doubts about the viewset, queryset = Denomination.objects.select_related('Retailer'). Any tips are more than welcomed as I'm starting to lose my sanity. Thanks. -
django.core.exceptions.FieldError: Cannot resolve keyword 'item' into field. Choices are: Item, Item_id, id, order, ordered, quantity, user, user_id
kindly help me tackle this issue frustrating me. i am trying to build an ecommerce website with django and got this error "django.core.exceptions.FieldError: Cannot resolve keyword 'item' into field. Choices are: Item, Item_id, id, order, ordered, quantity, user, user_id." Thanks Attached is the views.py views.py def add_to_cart(request, pk): item = get_object_or_404(Item, pk=pk) order_item, created = OrderItem.objects.get_or_create( item = item, user = request.user, ordered=False ) order_qs = Order.objects.filter( user = request.user, ordered=False ) if order_qs.exists(): order = order_qs[0] if order.items.filter(Item_id=item.pk).exists(): order_item.quantity += 1 order_item.save() messages.info(request, f"Your cart xxxxxxxxxxxx") return redirect("/") else: order.items.add(order_item) messages.info(request, f"Your cart is a ood one") return redirect("/") else: ordered_date=timezone.now() order = Order.objects.create(user = request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, f"Your cart is xxxxxxxx") return redirect("/") Attached is the models.py models.py class Item(models.Model): title = models.CharField(max_length=50) description = models.TextField(max_length=250) label = models.CharField(choices=label_choices, max_length=2, blank=True, null=True) category = models.CharField(choices=category_choices, max_length=2, blank=True, null=True) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) #image = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse("product", kwargs={'pk': self.pk}) def get_add_to_cart_url(self): return reverse("add_to_cart", kwargs={'pk': self.pk}) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) quantity = models.IntegerField(default=1) Item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): item = models.ManyToManyField(OrderItem) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) start_date = models.DateTimeField(auto_now_add=True) ordered_date = … -
how to use if condition in templates Django
I'm new to Django and want to create html template but I dont know how to use if condition in it, here is my template file(movie_list.html): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> something </title> </head> <body> <h1> List of movies </h1> {% if 1==1 %} hello {% else %} bye {% endif %} </body> </html> output is: List of movies {% if 1==1 %} hello {% else %} bye {% endif %} does anybody know how to fix it? -
fetch returning 500(internal server error) JavaScript
I have had a hunt arround but can't seem to find an answer that works. I am following Dennis Ivy's Django tutorial for an ecommerce website but I have run in to an issue where I am trying to add an item to my cart but nothing happens, checking the console I am getting these two errors: POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) updateUserOrder @ cart.js:26 (The fetch line) (anonymous) @ cart.js:15 (when the function is called) 127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 omise.then (async) updateUserOrder @ cart.js:39 (the second .then) (anonymous) @ cart.js:15 (when the function is called) Here is my JavaScript cart.js updateUserOrder function console.log('User is logged in, 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() }); } Here is my view updateItem 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 = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif … -
Can bulk_update fail to update some records but succeed overall?
I have a situation where I export between 5 to 20k records to a csv file and then bulk update the exported rows to reflect they've been updated with a Boolean field once the file has been successfully created. I'm using: MyData.objects.bulk_update(data, ['exported']) We've ran this process a few times for a total of ~60k records exported but we're seeing that ~0.17% of the MyDatas were not updated across all runs. So, some of the records included in the bulk update were updated while others were not; no exceptions thrown. How can this be? -
Mozzilla Pontoon Environment Variable
I'm trying to configure Mozzilla Pontoon on an Ubuntu OS hosted on Google Compute Engine. According to the documentation I should be able to pass some environment variables using a config.env file. From the documentation: "If you do so, you will only have to give the path of this file to Pontoon through the DOTENV_PATH environment variable: DOTENV_PATH=/path/to/my/config.env" I did a lot of test but without any success. For instance I exported a variable DOTENV_PATH with the correct path of the file, but nothing. Is it possible that the variable is not visible from the docker environment? Any suggestion? -
Django: ORM Design Issue
Scenario: Vehicle Testing - (Vehicles are booked into a test cell and then tested) For example purposes I have created two simplified models: class Vehicle(models.Model): registration = models.CharField(unique=True, max_length=10) tyre_pressure = models.IntegerField() class Booking(models.Model): STATUS_CHOICES= (('Booked','Booked'),('Complete','Complete')) booking_datetime = models.DatetimeField(auto_now=True) vehicle = models.ForeignKey(Vehicle, on_delete=SET_NULL) status = models.CharField(max_length=20, choices=STATUS_CHOICES) When a booking is created/booked, it creates a Booking object with the status Booked and the booking has an assigned vehicle. Once the test has completed, the Booking object changes it's status to Complete. The vehicle is now vacant for the next test. Issue The tyre_pressure for the vehicle (for example) may change later on after the Booking completed (Maybe for a different test) and cause the test to have incorrect data for that particular time. I want the Booking record to reflect the vehicle state at that particular time of the booking rather than the present value. What I've considered When a vehicle is edited/updated it creates a unique id. This would conflict with the unique=True parameter in the registration field. Include all vehicle fields inside Booking Model for given test instead of Vehicle object.