Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Ordering Objects Manually w/ A Field
I have a django model with an index IntegerField. I want to allow users to manually order these objects via a drag and drop interface. The idea is to update the ordering by updating this index field when one of the objects is dragged to a new position. So, for example if a user drags the 4th item to the top, that object will then be index 0, former index 0 will be index 1, former index 1 will be shifted to index 2 and so on. Is there a good way to do this in a single Django ORM call, without needing to iterate through the entire list of objects and increment the index? Say I want to insert an object that was at Index 4 at Index 2– is there a way to shift all indexes >= 2 by +1? -
Django admin add context to index.html
I'm trying to override Django admin index.html to show table contain latest 5 records from a model I managed to override the template with the following in my app: from django.contrib import admin admin.site.index_template = 'admin/dashboard.html' admin.autodiscover() But i have no idea how to add the latest records from model as a context to the index.html Hope someone can help me -
Django AllAuth - Link UserProfile stored in session to User created from Google Signup
I want to allow users to sample my Django website before prompting them to sign up with Google (which I implement using the django-allauth package). I want them to be able to create a UserProfile with their name, age, preferences, etc. and allow them access to the site. class UserProfile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=25, null=True, blank=True) age = models.IntegerField(null=True, blank=True) I do this by creating a UserProfile with no associated User, and storing their UserProfile pk in the session as follows: userprofile = UserProfile(name='Harry', age=28) userprofile.save() request.session['userprofile_pk'] = userprofile.pk Then when the user eventually decides to sign up via Google, I'd like to link their UserProfile to the User model like so: userprofile_pk = request.session.get('userprofile_pk') userprofile = UserProfile.objects.filter(pk=userprofile_pk).first() userprofile.user = request.user # User that has just been created using the django-allauth Google package userprofile.save() The problem I'm facing is that the django-allauth package creates the User, logs them in, and redirects to the url specified in my LOGIN_REDIRECT_URL, which clears the session and all access to the userprofile_pk. Is there a way I can link the UserProfile stored in the session to the newly created User? -
Is there anyway to run a game irrespective of reloding page in django
I need a way to run this number game irrespective of request. It should accept the forms submitted from this same page. I found that js clock and backend clock are not synchronized so I have started reloading this game tab for each second. So that time modules are creating newly after every refresh. And another problem is when a new user visits this page it will create time modules newly which ruin this game. So please suggest me a better way to do this. views.py class NumberSection(ListView): template_name = "gamepage.html" def get(self, *args, **kwargs): context = {} silver_created=False if not silver_created: silver_end,silver_gold_buffer,silver_gold_new,silver_gold_correct,silver_gold_start = create_time_modules() self.silver = True silver_game = NumbersGame.objects.create(mode='silver') self.silver_game_id = silver_game.id context['silver_status'] = 'accepted' silver_created =True if silver_created: if silver_end<=datetime.now(): self.silver = False context['silver_status'] = 'blocked' if silver_gold_buffer<=datetime.now(): pass if silver_gold_new<=datetime.now(): silver_created = False while True: silver_x = silver_gold_correct - silver_gold_start context["silver_minutes"]=(silver_x.seconds//60)%60 context["silver_seconds"]=silver_x.seconds%60 return render(self.request,self.template_name,context=context) def post(self, *Args, **kwargs): name = self.request.POST.get("choosen") amt = self.request.POST.get("total") if name == 'silver' and self.silver: hist = History.objects.create(user=self.request.self.user.userprofile,investment=amt,color_num_selected=name) hist.id_made = self.silver_game_id hist.save() return redirect('core:next') -
Understanding Django Rest Framework's ModelViewSet Router
I have my Comment model: class Comment(models.Model): """A comment is a content shared by a user in some post.""" user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) post = models.ForeignKey('posts.Post', on_delete=models.CASCADE, null=False) content = models.TextField(max_length=1000, null=False, blank=False) def __str__(self): """Return the comment str.""" return "'{}'".format(self.content) Its serializer: class CommentSerializer(serializers.ModelSerializer): """Comment model serializer.""" user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Comment fields = '__all__' def create(self, validated_data): """Create a new comment in some post, by request.user.""" validated_data['user'] = self.context['request'].user return super().create(validated_data) def list(self, request): """List all the comments from some post.""" if 'post' not in request.query_params: raise ValidationError('Post id must be provided.') q = self.queryset.filter(post=request.query_params['post']) serializer = CommentSerializer(q, many=True) return Response(serializer.data) The viewset: class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer queryset = Comment.objects.all() def get_permissions(self): permissions = [] if self.action == 'create' or self.action == 'destroy': permissions.append(IsAuthenticated) return [p() for p in permissions] def get_object(self): """Return comment by primary key.""" return get_object_or_404(Comment, id=self.kwargs['pk']) # this is the drf's get_object_or_404 function def destroy(self, request, *args, **kwargs): """Delete a comment created by request.user from a post.""" pdb.set_trace() instance = self.get_object() if instance.user != request.user: raise ValidationError('Comment does not belong to the authenticated user.') self.perform_destroy(instance) def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): … -
'WSGIRequest' object has no attribute 'type' error in Django API integration
I'm trying to integrate easyship API with my system. I'm able to create a shipment order using the Easyship API, but at first when the make shipment event is triggered, I receive this error 'WSGIRequest' object has no attribute 'type' and later when I refresh my page the shipment log is created and the error is gone. def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): if order.status=='Prepare to Ship' and order.shipment_status=='Not Created': values = { "platform_name": "Amazon", "platform_order_number": "#1234", "selected_courier_id": "null", "destination_country_alpha2": "US", "destination_city": "null", "destination_postal_code": "10022", "destination_state": "New York", "destination_name": order.name, "destination_company_name": "My Company", "destination_address_line_1": order.address, "destination_address_line_2": 'null', "destination_phone_number": order.phone, "destination_email_address": "order.email", "items": [ { "description": "Silk dress", "sku": "test", "actual_weight": 0.5, "height": 10, "width": 15, "length": 20, "category": "fashion", "declared_currency": "SGD", "declared_customs_value": 100 } ] } headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer xxxxxxAPI KEYxxxxxxxxx' } r = requests.post("https://api.easyship.com/shipment/v1/shipments", data=json.dumps(values), headers=headers) print(r.json()) order.shipment_id = r.json()['shipment']['easyship_shipment_id'] order.shipment_status = 'Created' order.save() print(r.text) response_body = urlopen(request).read() print(response_body) return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
Why I can't display data of a user in Django?
I want to display or list all current user's leaveforms (consider it as posts). For some reasons those data are not showing up. Can you spot me the mistakes? models.py class StudentLeave(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) leave_from_date = models.CharField(max_length=200) leave_till_date = models.CharField(max_length=200) student_name = models.CharField(max_length=200) leave_reason = models.TextField() def __str__(self): return self.student_name views.py @login_required def home(request): current_student = request.user all_student_leaveforms = StudentLeave.objects.filter(student=current_student) # student_leaveform_model = StudentLeave.objects.all().order_by("-date_created") return render(request, 'attendance/content/home.html', { 'all_student_leaveforms': all_student_leaveforms }) how I render in template {% for leaveform in all_student_leaveforms %} <div class="row"> <div class="ml-3"> <a href="#"> <h3>{{ leaveform.leave_from_date }} - {{ leaveform.leave_till_date }}</h3> </a> <p>Submit at {{ leaveform.date_created }}</p> </div> <a href="{% url 'leaveform_detail' leaveform.id %}" class="btn btn-info mt-3 ml-auto mr-3" > View </a> </div> <hr /> {% endfor %} -
Return a template after fetch
I made a fetch POST with data I want to handle on my server. I want to get that Json values sent by the fetch and use them to return a template, so i'm doing: def prepricing(request): if request.method == "POST": content = json.loads(request.body) return render(request, "letter/pricing.html", { "mail":content['mail'], "name":content['name'], "content2":content['content'] }) The post method is triggered. But here the problem is that, it doesnt' return anything. If i do instead return JsonResponse(content) it returns the value back to the js, but i need to render the template, not other thing. Any ideas? -
Django 'tuple' object has no attribute 'save'
I have this model CustomerPurchaseOrderDetail, Product, Customer, I just want that if the same productID and same CustomerID exists in the CustomerPurchaseOrderDetail model, the quantity will add 1 if the same productID and same CustomerID exists in the CustomerPurchaseOrderDetail. userID = request.POST.get("userID") client = Customer(id=userID) vegetables_id = request.POST.get("id") quantity = request.POST.get("quantity") v = Product(id=vegetables_id) price = request.POST.get("price") discount = request.POST.get("discount_price") insert = CustomerPurchaseOrderDetail.objects.get_or_create( profile=client, product = v, quantity=quantity, unitprice=price, discounted_amount = discount, discounted_unitprice = discount, ) insert.save() this is my models class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") quantity = models.FloatField(max_length=500, null=True, blank=True, default=1) class Product(models.Model): product = models.CharField(max_length=500) class Customer(models.Model): user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) firstname = models.CharField(max_length=500, blank=True) lastname = models.CharField(max_length=500, blank=True) contactNumber = models.CharField(max_length=500, blank=True) email = models.CharField(max_length=500, blank=True) this is my error this is my full traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/batchaddtocart/ Django Version: 2.2.4 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'customAdmin', 'sweetify'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, … -
Django: child drop down value is not returning, from dependent drop down set
I have a dependent drop down set for Makes and Models. Javascript is used to detect the change on the Make and then to filter/populate the Model dropdown from a Model. This appears to work well. I need the child drop down value to then perform a search of inventory on another html page, which I'm creating through a view. I instead of passing the child value, the parent value is always returned. This means I can generate a search/filter using the make but not the model as is required. I have tried many combinations of requests and changing the drop downs as well as an attempt at hidden variables to obtain the java script variable in place of pulling back the dropdown option via the name attribute ..... so far no success. Really need some guidance here. Index - drop down values are rendered {% extends "app/layout.html" %} {% block content %} <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" /> <script> $(document).ready(function() { var $makevar = $("#makeddl"); $modelvar = $("#modelddl"); $options = $modelvar.find('option'); $makevar.on('change',function() { $modelvar.html($options.filter('[value="' + this.value + '"]')); }).trigger('change'); }); </script> <script type="text/javascript"> function getOption() { selectElement = document.querySelector('#modelddl'); var $modelval = selectElement.value; }; </script> </head> … -
How to get inline style values and send to Django
I created Django application using draggable images with jQuery, it's working well, however I need to save, the new top and left positions in Django Model. I was trying a way to send inline style informations for some input type="hidden" value = "??? style" Look, after user move picture Jquery Draggable send this : <div id="draggable-1" class="ui-draggable ui-draggable-handle" style="position: relative; left: 3px; top: 1453px; "> <img src="static/img/image.png" width="80" height="200"> </div> Javascript to this resource in only: <script> $( "#draggable-{{forloop.counter}}" ).draggable(); </script> I need these numbers from left and top informations to send to a Django view and save database model. any suggestion, thank you! -
How to use task decorator in django celery
I have this task in this setup that needs to be run periodically: app.tasks.sum import sys from celery.decorators import periodic_task class Sum: @periodic_task def __call__(self, a, b): return a + b sys.modules[__name__] = Sum() project.settings.py: CELERY_BROKER_URL = 'redis://user:password@redis:6379/' CELERY_RESULT_BACKEND = 'redis://user:password@redis:6379/' CELERY_BEAT_SCHEDULE = { "sum": { "task": "app.tasks.sum", "schedule": crontab(minute="*"), }, } I'm getting this error Scheduler: Sending due task sum(app.tasks.sum) The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) Traceback (most recent call last): File "/opt/bitnami/python/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 562, in on_task_received strategy = strategies[type_] KeyError: 'app.tasks.sum' I'm not sure if i put the decorator in the correct place -
Typeerror: Metaclass conflict
I received this error via my console: it points out the problem to be this view: Please how do I solve this issue?Thanks -
how to fetch and return a template in django-javascript
I made a fetch post that includes information i need to handle on my server. So i'm doing: def prepricing(request): if request.method == "POST": if json.loads(request.body): content = json.loads(request.body) return render(request, "letter/pricing.html", { "mail":content['mail'], "name":content['name'], "content2":content['content'] }) This is what is running when the fetch post is done. Clearly this is not working. It's not returning anything. I should be doing instead: return JsonResponse(content) But I want to render that template and pass those variables. Should I return the JsonResponse and handle the template return in JavaScript? How can i do this? I just need to return that template with the values from the fetch POST. -
pytest: How to DRY up similar model manager method tests
What I have Manager and Model With the manager I can get those cases that are fulfilled, caducated or prescribed. from datetime import date class CaseManager(models.Manager): """Define a manager for Case model.""" def fulfilled(self): """Get all cases that will fulfill soon.""" return self.get_queryset().filter(fulfillment=date.today()) def caducated(self): """Get all cases that will caducate soon.""" return self.get_queryset().filter(caducity=date.today()) def prescribed(self): """Get all cases that will prescribe soon.""" return self.get_queryset().filter(prescription=date.today()) class Case(models.Model): """Representation of a legal case.""" fulfillment = models.DateField(verbose_name=_("Fulfillment"), default=date.today) caducity = models.DateField(verbose_name=_("Caducity"), default=date.today) prescription = models.DateField(verbose_name=_("Prescription"), default=date.today) objects = CaseManager() Factory Create fake cases for testing. class CaseFactory(DjangoModelFactory): """Define Case Factory""" fulfillment = Faker("date") caducity = Faker("date") prescription = Faker("date") class Meta: model = Case What I've tried Tests class TestCasesManagers: def test_fulfilled(self): case = CaseFactory(fulfillment=date.today()) assert case in Case.objects.fulfilled() def test_caducated(self): case = CaseFactory(caducity=date.today()) assert case in Case.objects.caducated() def test_prescribed(self): case = CaseFactory(prescription=date.today()) assert case in Case.objects.prescribed() Problem With this approach I have to repeat almost the same test for all the methods of my manager that are similar which is not scalable. What I want Create cases and change the keyword args that are passed to the factory to create a fake model. Call the different methods of the manager in … -
Django password form assign widget doesn't work
I'm creating a registration form for my website and everything functions, except the 'password1' and 'password2' won't recognize the widgets I assign to them. Below is a part of my code, which should be relevant to the issue from my forms.py file. Note the email part works correctly. fields = ['password1', 'password2', 'email'] widgets = { 'password1': forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Wachtwoord'} ), 'password2': forms.PasswordInput( attrs={'class': 'form-control', 'placeholder': 'Wachtwoord'} ), 'email': forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'E-mailadres'} ), } Below is a part of the registration.html in which the form is drawn. The top part is from the last name part which functions normally, the bottom part is from password1 which doesn't function: <div class="col-md-6"> <label for="last_name" class="text-info"> {{lid_form.last_name.label}}</label> {{lid_form.last_name}} </div> </div> <div class="row"> <div class="col-md-6"> <label for="password1" class="text-info"> {{user_form.password1.label}}</label> {{user_form.password1}} </div> Picture Example -
I want to display random blog views so that users will see different types of posts not according to time uploaded
I want my users to be able to view little info of other posts while in one but I don't get on how to make it work. Here is my views.py def blog_detail_view(request, slug): template_name = 'blog_details.html' instance = get_object_or_404(Blog, slug=slug) initial_data = { 'content_type':instance.get_content_type, 'object_id': instance.id, } share_string = quote_plus(instance.Content) #latest_blog_list = Blog.objects.order_by("?").first()[:5] latest_blog_list = Blog.objects.random().order_by('-publish_date')[:5] context = {'blog' : instance, "latest_blog_list":latest_blog_list, "share_string": share_string} return render(request, template_name, context) Here is my models.py file too from django.db import models from django.db.models.signals import post_save from django.utils import timezone from django.dispatch import receiver app_name='blog' # Create your models here. class Blog(models.Model): Your_Post_Title = models.CharField(max_length=2000) slug = models.SlugField(unique=True) publish_date = models.DateTimeField(auto_now_add=True) Content = models.TextField() def __str__(self): return self.slug If anyone can help me, with would be greatly appreciated -
How to make a like button with jquery inside a form so that it will save it to database and also change the style of like button?
I am working on a django project and I want to add a like button to the posts. this is my template: <form action="{% url 'like' post.id %}" method="GET" name="liked" class="l-form"> {% csrf_token %} <button style="display: inline;" class="like__btn"> <i class="like__icon fa fa-heart" style="display: inline;"></i> </button> </form> <script> $('.like__btn').on('click', function(){ $('.like__icon.fa-heart.fa').toggleClass("liked"); }); </script> All I want to do this, when user clicks on a heart icon, it will submit the form. But also change the icon color to red. (liked class is basically, color:red) When I click on the button it submits the form, increases the like count, but then it refreshes the page so my heart icon doesn't stay red. If I add type="button" this time it doesn't refresh the page, change the color of the icon but doesn't submit the form. I tried to do another button to submit the form and make it hidden but whenever the form is submitted it refreshes the page and goes back to the white heart. Also tried to return false; in jquery but it doesn't submit the form again. I am stuck for hours, so any advice would be great! -
Should race conditions be handled in form or view?
Lets suppose I have to withdraw money from a specific wallet object. So I first check if x amount of money is in wallet.. Then I lock wallet object in form clean() method, then check it. If the wallet has enough money, form is valid and we proceed to the view. In the view the withdraw action happens but in the view, the wallet object won't be locked anymore.. If two threads manage to reach to the view at the same time, race condition may occur. should the transfer action happen in the clean() form method where the wallet object will be locked or validate the amount of money of the wallet in the view? -
Hello, I need update delete and read function in my code
#1. Read Function should open the image in XL size and there should be a item name and item price and description should appear. #2. When i click order, the row data (data which is there in that row-id) in the table should be stored in other database. Picture shows the Views, URL, HTML, Model, Pitures https://photos.app.goo.gl/v1b8PU9m1vFH8RxZ6 -
How to prevent websockify process spawned by Django process does not get killed when restarting UWSGI?
I have the following oversimplified code: def openvnc_connection(request): Popen(['websockify', ...]) ... Problem is when I deploy the code, involves restarting the uwsgi service, the websockify process gets killed as well, resulting any active vnc connection gets dropped. I am aware the websockify process is the child of the django process and it gets killed because of that. I have tried the double-fork or similar stuff like detaching the child process but they don't seem to work. -
limit_choices_to with Q objects not working in production
I have these models where a Person can be a player, and if so, can be added to a team. I had the following code working in development, but in production it raises the error (requirements are exactly the same, but production as python 3.6.9 and development has python 3.7.3): Cannot resolve keyword 'is_active' into field. Choices are: players, < and the remaining fields of Team> The code models.py class Role(models.Model): role = models.CharField(max_length=30, verbose_name='Função') is_active = models.BooleanField(default=True, blank=False, null=False, verbose_name='Ativo') class Person(models.Model): name = models.CharField(max_length=150, verbose_name='Nome Próprio') roles = models.ManyToManyField(Role, blank=True, verbose_name="Funções") is_active = models.BooleanField(default=True, blank=False, null=False, verbose_name='Ativo') #...other non relevant fields class Team(models.Model): #...other non relevant fields players = models.ManyToManyField('Person', blank=True, verbose_name='Jogadores', limit_choices_to=Q(roles__role__startswith='player', roles__is_active=True, is_active=True )) # The above Q means Person's whose role starts with 'player' AND the role is active AND the Person is also active This works great in development but not in production... Any tips? Thanks! EDIT: Production server is an EC2 instance, with gunicorn, nginx and postgres, it was working ok before -
Why is the Django Admin bad for multiple users
I'm trying to find out why Django Admin is bad to use for users around > 10000 users and why people insists that I should serialize with for example Django REST API and use JavaScript on frontend to handle the data. Why is that? Why do I need to focus on that when the Django Admin is functioning well enough for my and the users needs? -
Is it possible to create an alias for deep joins/relationships?
I am adding some functionality to an app where a user can sort records in a table on the frontend (react) by passing additional url parameters to the backend. We use this in several places, and have a Mixin for pagination. In the pagination mixin I have the following: def get_queryset(self): order_by_field = self.request.GET.getlist("order_by") if order_by_field: return super().get_queryset().order_by(*order_by_field) else: return super().get_queryset() This works great, I can pass urls like {app_base_path}/{some_resource}/?order_by=title to get it to sort the returned query set by the queried model's title field. It also works with multi-sort (e.g. {app_base_path}/{some_resource}/?order_by=title&order_by=date). However, this looks very ugly and reveals unneccessary information to the end user for deeply nested relationships. For instance if I want to sort by a related field through an intermediary table: {app_base_path}/{some_resource}/?order_by=intermediary_model__related_model__field_of_interest. Is there a way I can make this nested relationship an alias on the model I am querying? Something like: class MyModel(models.model): # other model fields, etc. @property def alias(): return "intermediary_model__related_model__field_of_interest" -
Cannot resolve keyword 'last_activity' into field
As title says I was trying to sort a list of posts using the django order_by method and since the field I used was later added to the list (The field was not created inside the model) it failed. Is there anything I can do about it other than adding the field to the model which is something I really don't wanna do? Here is the model code class post(models.Model): title = models.CharField(max_length=236) content = models.TextField() post_board = models.ForeignKey(board, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) release_date = models.DateField(auto_now_add=True) views = models.IntegerField(default=0) def __str__(self): return self.title The function that adds the extra field: def forumdisplay(request, boardslug=None): context = { 'board': None } if boardslug: context['board'] = board.objects.all().filter(slug=boardslug).first() if context['board']: context['posts'] = post.objects.all().filter(post_board=context['board']) for eachpost in context['posts']: eachpost.reply_count = len(reply.objects.all().filter(reply_to=eachpost)) eachpost.last_activity = eachpost.release_date if eachpost.reply_count: eachpost.last_activity = reply.objects.all().filter(reply_to=eachpost).order_by('release_date').first().release_date context['posts'] = context['posts'].order_by('last_activity') alter_posts(context['posts']) else: pass return render(request, "board/forumdisplay.html", context) The error I got: Request Method: GET Request URL: http://127.0.0.1:8000/forumdisplay/news/ Django Version: 3.0.4 Exception Type: FieldError Exception Value: Cannot resolve keyword 'last_activity' into field. Choices are: author, author_id, content, id, post_board, post_board_id, release_date, reply, title, views```