Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translation redirect back to the current page
How to redirect back to the current page. In my site I'm implementing two language which is 'en' and 'fa' right now It's working but doesn't redirect to current page like docs.djangoproject.com we have instead it redirect me to home 'localhost:8000/fa/' or /en here is the code: for template hearders.py <li class="dropdown default-dropdown"> <form action="{% url 'selectlanguage' %}" method="POST">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="{% trans 'Go' %}"> </form> </li> code for urls.py is: path('selectlanguage', views.selectlanguage, name='selectlanguage'), and for views.py is: def selectlanguage(request): if request.method == 'POST': # check post cur_language = translation.get_language() lasturl= request.META.get('HTTP_REFERER') lang = request.POST['language'] translation.activate(lang) request.session[translation.LANGUAGE_SESSION_KEY]=lang #return HttpResponse(lang) return HttpResponseRedirect(lang) -
Django - Select a specific pk at a view where multiple pk's are available
I'm currently building a support page where people can open each ticket as a box. Problem now is that I need to seperate the pk for each opened suppot ticket where people can reply on as I have everything on a single page and a single view and a single form but with multiple pk's, as all support tickets of the user are getting displayed: def support(request, pk=None): template = 'App_Support/support.html' form = SupportTicketMessagesForm() if request.method == "POST": support_ticket = get_object_or_404(SupportTickets, pk=pk) form = SupportTicketMessagesForm(request.POST) if form.is_valid(): support_ticket_reply = form.save(commit=False) support_ticket_reply.author = request.user support_ticket_reply.content_object = support_ticket support_ticket_reply.save() messages.success(request, 'Reply has been added successfully') return redirect('support') else: messages.error(request, 'Something went wrong') return redirect('support') else: list_support_tickets = sorted( chain( SupportTickets.objects.filter(requester=request.user, status=0) ), key=attrgetter('creation_date'), reverse=True ) paginator = Paginator(list_support_tickets, 10) page = request.GET.get('page') support_tickets = paginator.get_page(page) args = {'support_tickets': support_tickets, 'form': form } return render(request, template, args) My problem is at the following two lines: support_ticket = get_object_or_404(SupportTickets, pk=pk) support_ticket_reply.content_object = support_ticket As I'm unable to properly access the pk of just one object/Support Ticket, as in this view I only have multiple pk's I can potentially reply onto. So how to select? In addition, please also see my models.py logic: referential_models = … -
How do I show checkbox value checked if it already exists in Database?
If user checks Orange and banana then save it. The value Orange and Banana will be stored in Database(Postgresql). Now when I open the checklist page(As shown In the image),Checkbox Orange and banana should be checked and Kiwi, Apple and Grapes should be unchecked Here is models.py class details(models.Model): name = models.CharField(max_length = 20) class savedata(models.Model): checked_value = models.CharField(max_length=50) Here is views.py def choice(request): list = details.objects.values('name') done = savedata.objects.get(pk = 16) temp = done.checked_value print(list) print(done) print(temp) if request.method == "POST": data = savedata() data.checked_value = request.POST.get('checked_values') data.save() return render(request, 'choice.html',{'list':list,'data':data,'done':done,'temp':temp}) else: return render(request, 'choice.html',{'list':list,'done':done,'temp':temp}) When I print list I get: <QuerySet [{'name': 'Orange'}, {'name': 'Kiwi'}, {'name': 'Banana'}, {'name': 'Apple'}, {'name': 'Grapes'}]> When I print done I get: savedata object (16) When I print temp I get: Orange, Banana Here is Django Template choice.html {% for l in list %} {%if temp in list.name %} <input style="font-weight: bold;display:inline-block;" type="checkbox" class="chkcvalues" name="ip" value="{{l.name}}" checked> {{l.name}}<br /> {%else%} <input style="font-weight: bold;display:inline-block;" type="checkbox" class="chkcvalues" name="ip" value="{{l.name}}"> {{l.name}}<br /> {%endif%} {% endfor %} <input type="text" name="checked_values" id="txtvalues" /> <button id="but1" type="submit" class="save"> Save</button> <a id="but2" type="submit" class="home" href="{% url 'fruit' %}"> Home</a> The problem with this code is it always goes into else … -
django form choicefield update after every query
i have created a webapp. this is how it works user inputs a number mapped with a product csv file corresponding to that product gets downloaded you are presented with a form which contains one property name along with choices available for that property issue i am facing is, this whole process works for first search only after that whenever user enters any different number for any other product ideally choicefield in the form should get updated, but it dont get updated, i have deployed this app on heroku,if i restart all dynos this fixes the problem but just for time being. i mean for only one search, again same problem happens link to the app: https://abcd4.herokuapp.com/ link to the code: https://drive.google.com/drive/folders/1zlKowvcpK5NOnmAZFstDPC1oWTH97WmX?usp=sharing problem is not about the deployed platform i.e heroku i faced same issue when i ran app on localhost on localhost also restarting app solved the problem forms2.py from django import forms from django.core import validators def mergefunction(s1,s2): merged = [] for i in range(0, len(s1)): tup = (s1[i],s2[i]) merged.append(tup) return merged class GeeksForm(forms.Form): import csv import pandas as pd filename = r"downloaded1.csv" data = open(filename, encoding = "utf8") csv_data = csv.reader(data) data_lines = list(csv_data) total_row = (len(data_lines)) … -
How to use reverse filtering and removing duplicates in annotate using Django ORM
Hello I am having flowing model structure class TestModelA(AuditFields, Model): id = models.AutoField(primary_key=True) modelb = models.ForeignKey( TestModelB, on_delete=models.SET_NULL, blank=True, null=True ) class TestModelB(AuditFields, Model): id = models.AutoField(primary_key=True) modelc = models.ForeignKey( TestModelC, on_delete=models.SET_NULL, blank=True, null=True ) class TestModelC(AuditFields, Model): id = models.AutoField(primary_key=True) value = models.charfield(max_length=255, blank=True) I'm making a query like this qs = TestModelA.objects.values('modelb__modelc__value').annotate( count=Count('modelb__modelc__value'), ).distinct() Later some other filters applied to this initial queryset "qs" For that I am having another model class TestModelD(AuditFields, Model): id = models.AutoField(primary_key=True) modela = models.ForeignKey( TestModelA, on_delete=models.SET_NULL, blank=True, null=True, related_name="associated_modela") rating = models.charfield(max_length=255, blank=True) Then this is out new qs qs = (TestModelA.objects.values('modelb__modelc__value').annotate( count=Count('modelb__modelc__value'), ).distinct()).filter(associated_modela__rating = 'Sample') But the issue is that if two TestModelD objects under a single TestModelA object , it duplicating In the above scenario (if two TestModelD objects under a single TestModelA object) Currently I am getting output like this <SoftDeletionQuerySet [{'modelb__modelc__value': 'Large', 'count': 2}]> But my expected output is <SoftDeletionQuerySet [{'modelb__modelc__value': 'Large', 'count': 1}]> -
Transfer Class-based view to another
I created a DetailView class that can receive links from categories or posts from a website. In the “get_object ()” method, I identify if it is Category or Post models (by url slug). The URLs for this class are listed below: /category/ /category/subcategory/ /category/post/ /category/subcategory/post/ The class got too long because the categories and posts have specific behaviors. I was wondering if it is possible to "transfer" one class to another to handle specific information? For example: GenericView redirect to CategoryView after identifying that it is the url: / category / or for PostView, if it is / category / post / NOTE: I am transferring the Wordpress site to Django, so I cannot change the url structure. Is there any way to do this? Do you suggest another better solution? -
how to overwrite dj_rest_auth registration package on django rest project
I'm creating a full stack app using django rest + react. (backend) config.urls sign up path path('accounts/signup/', include('dj_rest_auth.registration.urls')), i need to overwrite the package so i can sign up using: password + password_confirm instead of the built in password1 + password2 Hopefully someone will know how to do it -
How to pull a Serializer object into def create() function separately?
class ArticleCreateSerializer(serializers.ModelSerializer): images_set = ArticleImagesViewSerializer(source='images',required=False,many=True) tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('images_set','tags_set','id') def create(self,validated_data): images = self.context['request'].FILES.getlist('images_set') articleinit = Article.objects.create(**validated_data) tags = validated_data.pop('tags_set', None) for imageinit in list(images): m2 = ArticleImages(article=articleinit , image= imageinit ) m2.save() for taginit in list(tags): m3 = ArticleTags(article=articleinit , tag = taginit ) m3.save() return articleinit I am trying to post request array of tags and I have to pull them into create function separately for obvious reasons, I have to work them one by one in another serializer. My only request here is that how can U pull them correctly?This code does not work as intended(it pulls data as null value): tags = validated_data.pop('tags_set', None) Does anybody have a clue? -
How do set default values in django for an HttpRequest.POST?
how can i set a default value If the field is not sent?! for example my code: class SampleViewSet(ParentListAPIView): def post(self, request, *args, **kwargs): _email = self.request.data['email'] -
Issue with Paginiation
I am quite new to python/django and I am following CoreyMSchafer's youtube tutorials. However, when trying to get pagination to work it displays the elif command on the webpage itself and doesn't render it server side.elif code being displayed home.html {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add: '3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} {% endblock content %} -
count likes in ManyToManyField - django rest framework
in models.py: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] in serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() class Meta: model = Post fields = ('body','date','user') how to count likes of a single post? and also show which user liked the post. -
Digitalocean spaces too slow to upload even from the droplet of same region
I am using django-storages to upload my static and media files to digital-ocean spaces. Problem is it was really slow. All of the sudden, requests started becoming too slow. Then I started debugging with django-silk, and found that boto3 function was taking too much time. then inside the droplet itself, I tried to upload the s3cmd function. truncate -s 20M sample_file.txt #created a 20 mb file s3cmd put sample_file.txt s3://disbug-media The output was upload: 'sample_file.txt' -> 's3://disbug-media/sample_file.txt' [part 1 of 2, 15MB] [1 of 1] 15728640 of 15728640 100% in 26s 584.56 KB/s done upload: 'sample_file.txt' -> 's3://disbug-media/sample_file.txt' [part 2 of 2, 5MB] [1 of 1] 5242880 of 5242880 100% in 41s 123.58 KB/s done The 15mb part upload took 26 seconds and 5MB part took 41s 😱. My droplet and the spaces are in the same region. Is there anyway I could speedup the upload ? Or is this performance issue common in digitalocean spaces. I am really starting to regret for choosing DO as my infrastructure 😭. -
web developpement in python [closed]
I have a project where I need to build a website that keeps track of orders. The client just needs to enter the order number and it gives him the information that I want. I used python Django to build the website and request to get the data (API) I don't know how I can display the different orders. If you have an example of something similar or advice, please send it to me. Thanks -
Django Flask - Exception happened during processing of request
I'm getting this issue when I'm communicating with my app. At present I'm using flask and it is running on my local port. Here is the code which causes the first error: def _handle_request_noblock(self): """Handle one request, without blocking. I assume that selector.select() has returned that the socket is readable before this function was called, so there should be no risk of blocking in get_request(). """ try: request, client_address = self.get_request() except OSError: return if self.verify_request(request, client_address): try: self.process_request(request, client_address)(#error occuring at this line) except Exception: self.handle_error(request, client_address) self.shutdown_request(request) except: self.shutdown_request(request) raise else: self.shutdown_request(request) 2nd error: def process_request(self, request, client_address): """Call finish_request. Overridden by ForkingMixIn and ThreadingMixIn. """ self.finish_request(request, client_address)(#error occuring at this line) self.shutdown_request(request) 3rd error: def __init__(self, *args, directory=None, **kwargs): if directory is None: directory = os.getcwd() self.directory = directory super().__init__(*args, **kwargs) #error at this line when I start communicating with the app it is showing error 503 the following error in the console: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 316, in _handle_request_noblock self.process_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 347, in process_request self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/server.py", line 647, in __init__ super().__init__(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ … -
Django AllAuth does not extend 'base.html', despite base.html existing in templates
base.html works for all other url links, but as soon as I load localhost:8000/accounts/ (e.g. logout or login), the css template does not work at all. The functionality still works, it's just the css that isn't working. This is as per the tutorial (From 8:22 to 10:44): https://www.youtube.com/watch?v=bopkZBbIa7c. I have followed the tutorial step by step, yet it gives a different result than the tutorial. (Just want to reiterate the functionality is fine, just plain django css) My current settings.py is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', 'posts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] Urls: urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog, name='post_list'), path('post/<id>', post, name = 'post_detail'), path('search/', search, name = 'search'), path('tinymce/', include('tinymce.urls')), path('accounts/', include('allauth.urls')), path('accounts/profile/', blog, name='post_list') ] Any help would be appreciated. Thanks. Django version 3.1.4 Python 3 -
NoReverseMatch Error in Django when mapping items
I am trying to map different items using the pk(primary key). I have used it in my urls.py, views.py as well as the templates file. But I am a NoReverseMatch Error. I have also tried changing the str to int in the urls.py file but it still gave the same error. I hope I could get someone to kindly help. Thanks error log Environment: Request Method: GET Request URL: http://localhost:8000/update-reservation/1/ Django Version: 3.1.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'dashboard', 'widget_tweaks', 'phonenumber_field'] 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'] Template error: In template C:\Users\Habib\Documents\django\FIVERR\adam_mailk\templates\dashboard\super\admin\base.html, error at line 41 Reverse for 'updatebar' with keyword arguments '{'updatebar': ''}' not found. 1 pattern(s) tried: ['updatebar/(?P<pk>[^/]+)/$'] 31 : <aside class="left-panel"> 32 : <div class="logo"> 33 : <a href="{% url 'dashboard' %}" class="logo-expanded"> 34 : <img src="{% static 'logo.png' %}" style="background-color: white; width: 140px; height: 65px;" alt="logo"> 35 : </a> 36 : </div> 37 : <nav class="navigation"> 38 : <ul class="list-unstyled"> 39 : <li {% if request.path == '/dashboard/' %} class="active" {% endif %}><a href="{% url 'dashboard' %}"><i class="ion-home"></i> <span class="nav-label">Dashboard</span></a> 40 : </li> 41 : <li {% if request.path == '/updatebar/' %}class="active"{% endif %}><a href=" {% … -
.sql to ER diagram
i am trying to create a er diagram from a .sql file which was originally a sqlite file PLEASE HELP!!!! i tried to create an ER Diagram in mysql workbench but i got these errors PLEASE HELP!!!! PLEASE HELP!!!! PLEASE HELP!!!! ERROR: (1, 27) "django_migrations" is not valid at this position for this server version, expecting a new table name ERROR: (1, 1) "id" is not valid at this position for this server version, expecting an identifier ERROR: (1, 1) "app" is not valid at this position for this server version, expecting an identifier ERROR: (1, 20) "NOT" is not valid at this position, expecting EOF, ';' ERROR: (8, 27) "auth_group_permissions" is not valid at this position for this server version, expecting a new table name ERROR: (8, 1) "id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 1) "group_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 1) "permission_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 13) "permission_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 41) "auth_permission" is not … -
convert django url with '|' (or) regex to modern Django path
I have a question regarding conversion of pre - Django 2 urls to path If I have an url like this: url( r'^some_path/(?P<type>type_one|type_two)/', views.SomeViewHere.as_view(), name='important_name', ), Question is how to convert this url to modern Django path keeping same functionality and keeping same name? Important aspect: kwargs type_one and type_two should be passed into view. Name parameter can’t be changed or split. What I have done: path('some_path/', include( [ path('type_one/', views.SomeViewHere.as_view(), kwargs={'type': 'type_one'}), path('type_two/', views.SomeViewHere.as_view(), kwargs={'type': 'type_two'}), ] ), name='important_name', ), But reverce doesn’t work with this configuration Thank you. ps. type is a string -
Django_filters and apache2 500 internal server Error
I'm try to use Django_filters for filtering in my app and use apache2 , so after I install Django_filters using below documentation https://django-filter.readthedocs.io/en/stable/guide/install.html then add INSTALLED_APPS = [ 'django_filters', ] the app crash and return 500 internal server error ,then try to update ubuntu and apache2 , nothing is change so what is the solution for it ? -
DRF: How to define a custom error message for UnsupportedMediaType exception during parsing
Question: What's the easiest way to define a custom error message when an 'Unsupported media type' error is raised by a Django Rest Framework parser? Some context For a certain APIView-based POST call, I use the default MultiPartParser, which requires the Content-Type: multipart/form-data. If this is not set correctly, Django responds with a 415 status code with a message like "Unsupported media type "application/x-www-form-urlencoded" in request." However, I'd like to customize this message (i.e., including that multipart/form-data should be used). I know I can define custom serialization validation error messages in serializer classes using the error_messages property of a field (docs here). I couldn't find anything similar for the parser. (apart likely from creating a custom parser) The skeleton of my POST view looks like this: class UploadView(APIView): parser_classes = [MultiPartParser, ] def post(self, request): ... return Response(status=status.HTTP_204_NO_CONTENT) Triggering the 415 error described above is easy using e.g. curl -d "test=123" http://localhost:8000/my/upload/url -
How do you successfully get the id of any of your objects that you want in django?
One piece of functionality I'm trying to build for a fantasy football app is to have a page where any logged in user can see a list of all the other teams and their scores so that you can compare your score to teams of other users. Earlier today I got some interesting advice that suggested making a function in views.py that can show any team - not just your own. The function would obviously need to get the id of the team you want to display. It sounds logical, but I can't think of how to start/implement this though. This is the model object in question. class Team(models.Model): team_name = models.CharField(max_length=255, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) quarter_back = models.ForeignKey(Quarterback, on_delete=models.CASCADE, null=True) running_back = models.ForeignKey(Runningback, on_delete=models.CASCADE, null=True) wide_receiver = models.ForeignKey(Widereceiver, on_delete=models.CASCADE, null=True) tight_end = models.ForeignKey(Tightend, on_delete=models.CASCADE, null=True) kicker = models.ForeignKey(Kicker, on_delete=models.CASCADE, null=True) I've tried making a function but I get a 404 error because there's no id submitted to the url in the first place. How can you get the object's id if there is no id showing in the template's url? If I manually type the object's id integer at the end of the url, it does get … -
How to create a custom GET method that matches a certain URL patttern?
I am using a DefaultRouter and have a custom method in it. Right now I am passing values as POST but I want to pass as GET with the pattern like example.com/wallets/balance/<customerID>/. I am using ViewSet. My current urls.py looks like: router = routers.DefaultRouter() router.register('wallets', views.WalletView, basename='WalletModel') router.register('wallets/balance/1/', views.custom_balance,basename='CustomBalanceModel') # This crashes and models.py def custom_balance(id): return Response({'status': 'OK', 'data': 'success'}, status=status.HTTP_200_OK) class WalletView(viewsets.ModelViewSet): ..... -
MultipleObjectsReturned at /cart/ in Django
i'm a beginner and i am getting this error "Exception Value: get() returned more than one Order -- it returned 2!" views.py def cart(request): customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=False) items=order.orderitem_set.all() context={ 'items':items } return render(request, 'catalog/cart.html',context) models.py class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL, blank=True, null=True) date_orderd=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False, null=True, blank=False) transaction_id=models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product=models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order=models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity=models.IntegerField(default=0, null=True, blank=True) date_added=models.DateTimeField(auto_now_add=True) thanks. -
How to convert k8s resources into django models in real time?
How to convert K8S resources into Django models in real time and retain the mapping relationship between K8S resources, such as a cluster with multiple workloads. The K8S resource data I obtained through API is json data, which I converted into list data. I did not find a way to convert the list to Django's Queryset in real time, and it can also support ORM operations. I found a link to discuss how to convert list data into Django's QuerySet, but the solution can't solve my problem.I need help. -
I am getting object has no attribute update in my Django Website
I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks views.py def UpdateReservation(request, pk): table_exists = Reservation.objects.get(id=pk) form = ReservationForm(instance=table_exists) if request.method == "POST": if request.POST['table']: request.POST = request.POST.copy() table_exists = Reservation.objects.get(id=pk) try: if table_exists: time = form['time'] people = form['people'] comment = form['comment'] date_reserved = form['date_reserved'] email = form['email'] phone = form['phone'] first_name = form['first_name'] resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists) resrv.save() messages.success(request, "you have successfully edited.") return redirect(request.path) else: messages.error(request, "Unable to edit.") return redirect(request.path) except Exception as e: messages.error(request, "Unknown error" + str(e)) return redirect(request.path) context = {"form":form} return render(request, "dashboard/super/admin/update_reserve.html", context) After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update'