Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django caches user object
Our websites sometimes has around 600 authenticated users trying to register for an event in a timeframe of 5 min. We have a VPS with 1 CPU and 1GB ram. On these moments the site slows down and gives a 502 error. For that reason I'm using per-site cache with FileBasedCache. This works excellent and stress tests work fine. But, when people login, they're redirect to their profile. This is the code: class UserRedirectView(LoginRequiredMixin, RedirectView): permanent = False def get_redirect_url(self): return reverse("users:detail", kwargs={"membership_number": self.request.user.membership_number}) the user is redirect to an url with their membership_number class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "membership_number" slug_url_kwarg = "membership_number" Some users are reporting that they are redirected to someone else his/her profile after logging in. How does this work? How to prevent user specific parts of the website to be cached? e.g. users also see a list of events that are specific to the groups they are in. In other words, every user should see a different list. Any ideas? Best practices? -
Django Change 3rd Party Model Name
I know that I can change the name of model created by myself using verbose_name="Updated Model name". Is there any way of changing name of 3rd party model in Django? I also tried changing the attribute of parent class using child class but that didn't work for me. -
Overrided Multi Select BooleanField request response django
The information are here: This is print(request.POST) in views.py <QueryDict: {'csrfmiddlewaretoken': ['token'], 'agree_2': ['19', '22'], 'submit_multiple': ['']}> My views.py return JsonResponse(request.POST) {"csrfmiddlewaretoken": "token", "agree_2": "22", "submit_multiple": ""} enter image description here enter image description here What i want to do is take post id to be value in boolean field and I want to take all "agree_2":["19","22"] This is my views.py files def index(request): AVM_Form = AVMForm() post = PostAVM.objects.all() context = { 'form':AVM_Form, 'post':post, } if request.method=='POST': if 'submit_single' in request.POST: submitPost(request) return HttpResponseRedirect('result/') elif 'submit_multiple' in request.POST: dump = request.POST print(dump) return JsonResponse(dump) return render(request, 'index.html', context) Could anyone help me? Thanks for help! -
Make REST Framework require authentication for GET method
I'm working on an Django app that uses REST Framework together with Swagger. Also added some models, and one of them is called Example. Added some views based on mixins in views.py for the model previously mentioned. In views.py, I've created two classes: ExampleList (that uses GET to get all the objects made out from that model and POST to add a new model) and ExampleIndividual, that uses methods such as individual GET, PUT and DELETE. Anyways, this is how my ExampleList class looks like: class ExampleList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): permission_classes = [IsAuthenticated] queryset = ExampleModel.objects.all() serializer_class = ExampleSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) In the settings.py file, in the REST_FRAMEWORK configuration, I've set: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] Everything works fine at this moment. What I want to do, is, whenever I want to get the list of all objects from the Example model (access the get() method from the ExampleList() class, I want it to work only if I am authenticated (using the Authorize option from Swagger). If not, a status code like "FORBIDDEN" should be returned. I tried using permission_classes = [IsAuthenticated] at the beginning … -
Field 'id' expected a number but got 'product_id' django
In my ecommerce app when I click on add to cart the product goes to the cart but when I click on the cart it gives me the error that 'Field 'id' expected a number but got 'product_id''. Basically I use context_processor to pass the cart.py information to the template. Link to the cart from base.html is: <div class="navbar-item"> <a href="{% url 'cart' %}" class="button is-dark">Cart {% if cart %}({{cart|length}}){% endif %}</a> </div> When I click on cart this error is generated: Field 'id' expected a number but got 'product_id' my project/urls.py is path('cart/',include("cart.urls")), my cart/urls.py is urlpatterns = [ path('',views.cart_detail, name='cart') ] my cart/cart.py is from django.conf import settings from product.models import Product class Cart(object): 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 def __iter__(self): for p in self.cart.keys(): self.cart[(p)]['product'] = Product.objects.get(pk=p) for item in self.cart.values(): item['total_price'] = item['product'].price * item['quantity'] yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def add(self, product_id, quantity=1, update_quantity=False): product_id = str(product_id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 1, 'id': product_id} if update_quantity: self.cart[product_id]['quantity'] += int(quantity) if self.cart[product_id]['quantity'] == 0: self.remove(product_id) self.save() print(self.cart) def remove(self, product_id): if product_id … -
CSRF token error for django app when deploying to AWS server
I have a django site that runs fine locally but when trying to deploy with AWS elastic beanstalk I get the following error when I try to login (using django allauth) Forbidden (403) CSRF verification failed. Request aborted. The logs state: Forbidden (CSRF cookie not set.): /accounts/login/ My settings.py middleware has: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.BrokenLinkEmailsMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] The form has a csrf_token: <form class="login" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {{ form|crispy }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a> <button class="primaryAction btn btn-primary" type="submit">{% trans "Sign In" %}</button> </form> Any advice as to how to fix and why it runs ok locally but not when deployed appreciated -
How to set charset header in Django 1.11
we are using Django1.11 and we are having some problems because our header Content-Type does not contain the charset part set to UTF-8. Something like this: Content-Type: application/json; charset=UTF-8 I want to fix that for all endpoints, so I have thought to include a middleware to run after all midlewares have been run. The problem is that I do not know if that's possible. Any ideas? Or alternative solutions? -
Difference between creating a field vs model Django model
I have a small uml association diagram. It goes as follows... PetOwner first_name:CharField last_name:CharField email:EmailField address:CharField phone_number:CharField pet:Pet[0..*] and Pet first_name:CharField last_name:CharField breed:CharField weight:FloatField date_of_birth:DateField date_of_death:DateField owner:PetOwner[1..*] The idea is a PetOwner may own 0 - many pets and a Pet can have 1 - many owners. You can see that the Pet has a field breed. However, I have an understanding that you want to use models to represent selection-list options. This is recommended when all the options aren't known up front or may change. The breed of my pet won't change but I might not know the breed at first? I was thinking about creating a table for Breed and so in my Pet the breed field would be of type Breed, where a Pet can be only of one breed and there could be 0 or many pets of a certain breed. If I did this what exactly is the advantage of this over just having it as a String field in my database without creating a new table for Breed. -
decoding b64 data uri django
The user fills out a form and provides a signature. The signature becomes an encoded data image URI and sent via AJAX to the view, it is then decoded and saved as a png in the database. When the string is passed to the server it is different to what I console.log() on the client side. Usually it converts '+' to whitespace - which I thought I corrected, but it sometimes still throws the error incorrect padding. This is my first time working with base64 and file uploads in Django. Could somebody please tell me if there is an error in the code I'm using or if there is a better way to send data URI to django views? Views.py def certify_logbook_ajax(request): if request.method == 'POST': if request.is_ajax: encoded_sig = request.POST.get('signature').split(',') encoded_sig[1] = re.sub(r"\s+", '+', encoded_sig[1]) decoded_sig = base64.b64decode(encoded_sig[1]) file = {'signature': SimpleUploadedFile('signature.png', decoded_sig)} form = CertifyLogbookForm(request.POST, file) form.instance.user = request.user if form.is_valid(): form.save() return JsonResponse(....) else: return JsonResponse(form.errors.as_json(escape_html=False), safe=False) return Http404() Javascript Sent via XMLHttpRequest for (let i = 0; i < formFields.length; i++) { ajaxStr += formFields[i].getAttribute('name') + '=' + formFields[i].value + '&'; } ajaxStr += 'signature=' + signaturePad.toDataURL("image/png") + '&csrfmiddlewaretoken={{ csrf_token }}'; Error log Traceback (most recent … -
Geodjango saving shapefile to postgis (Geopandas, geoalchemy2)
hi I'm trying to store a shp in postgis, creating an additional column where I insert the geometry, but trying to convert gdf ['geom'] = gdf ['geometry']. apply (lambda x: WKTElement (x. wkt, srid = epsg)), The server overflows, I have no errors but I imagine it is because we have empty data, I work in a mac environment my model.py # extract zipfile with zipfile.ZipFile(file, 'r') as zip_ref: zip_ref.extractall(file_path) os.remove(file) # remove zip file shp = glob.glob(r'{}/**/*.shp'.format(file_path), recursive=True) # to get shp try: req_shp = shp[0] gdf = gpd.read_file(req_shp) # make geodataframe crs_name = gdf.crs epsg = crs_name.to_epsg() if epsg is None: epsg = 4326 # wgs 84 coordinate system #geom_type = gdf.geom_type[1] engine = create_engine(conn_str) # create the SQLAlchemy's engine to use print('-----', name, '-----') gdf['geom'] = gdf['geometry'].apply( lambda x:WKTElement(x.wkt, srid=epsg)) print('-----', name, '-----') # Drop the geometry column (since we already backup this column with geom) gdf.drop('geometry', 1, inplace=True) gdf.to_sql(name, engine, 'data', if_exists='replace', index=False, dtype={'geom': Geometry('Geometry', srid=epsg)}) # post gdf to the postgresql gdf.to_postgis( con=engine, name=name, if_exist="replace") for s in shp: os.remove(s) except Exception as e: for s in shp: os.remove(s) instance.delete() print("There is problem during shp upload: ", e) geo.create_featurestore(store_name='xxxxxxxx', workspace='xxxxxxxxx', db='xxxxxxxx', host='localhost', pg_user='postgres', pg_password='xxxxxxxx', schema='xxxx') … -
How do I use `@transaction` to rollback the registered user in case Email fails to generate?
I am building a simple django-rest-framework backend that uses dj-rest-auth authentication system with the following settings ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' I want to ensure that in case of failure in email-generation the registered user is rolled back. This is my serializer.py class CustomRegisterSerializer(RegisterSerializer): first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) @transaction.atomic def save(self, request): try: user = super().save(request) user.first_name = self.data.get('first_name') user.last_name = self.data.get('last_name') user.save() return user except <...What exception has to be caught?...>: transaction.set_rollback(True) return What exception do i have to catch and am I doing this right? How do I achieve this? For reference, this is the error generated in case of wrong values in settings.py file Exception Type: ConnectionRefusedError at /api/auth/register/ Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it Also is it possible to rollback in case of user submitting a wrong email and email fails to deliver? -
Context overrides context_object_name
I am new to Django and pretty lost on how to approach this problem. Views.py: class UserProfileDetailView(DetailView): model = CustomUser context_object_name = 'profile_detail' template_name = 'user_profile_templates/profile_detail.html' def get(self, request, pk, *args, **kwargs): followers_var = request.user.motivators.all() if len(followers_var) == 0: is_following = False for follower in followers_var: if follower == request.user: is_following = True break else: is_following = False number_of_followers = len(followers_var) context = { 'number_of_followers': number_of_followers, 'is_following': is_following, } return render(request, 'user_profile_templates/profile_detail.html', context,) So the problem is that I can't use context_object_name or 'object.var_name' in my template I guess that context that I defined in my get method is responsible for that. I've read somewhere that we should not use get() method in DetailView class, but I don't know what to do instead, should I use View and go from there? RequestContext? How would you refactor this whole class? -
Get 'str' into Djano forms.FileField()
I'm uploading without a form. My user has a FileField if I'm uploading via <input type...> i have no problem. But this is not that handy for my purpose. views.py def uploadaction2(request): f = forms.FileField() # this is my idea data = json.loads(request.body) # f.clean("data['data']") # error: file_name = data.name AttributeError: 'str' object has no attribute 'name' logger.error(type(data['data'])) #gives <class 'str'> and without the type the string that i want to save with open('newfile', 'w') as file: file.write(data['data']) request.user.file = file request.user.save() # i get no error until this part Error Internal Server Error: .... in pre_save if file and not file._committed: AttributeError: '_io.TextIOWrapper' object has no attribute '_committed' I think i have to convert the json string to a forms.FileField() by i've no idea how this could be done. -
Django Rest Framework - Passing 'user' from ModelViewSet to Serializer
I've been stumped by this for a couple of hours now, and have read through a bunch of documentation and different tutorials, but I still do not know what I'm doing wrong. I'm trying to make a POST request to create a Comment (my model, views, etc. defined below) and make an association with the User that is making the POST request, but I keep getting the error {"user":["This field is required."]} I thought that adding def perform_create(self, serializer): serializer.save(user=self.request.user) to my viewset would make this easy, but that doesn't appear to be working... My models.py looks like: import uuid from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) text = models.TextField(blank=False, null=False) created = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.CharField(max_length=256) content_object = GenericForeignKey('content_type', 'object_id') serializer.py from rest_framework import serializers from .models import Comment from organization.serializers import UserSerializer from django.contrib.auth import get_user_model User = get_user_model() class CommentSerializer(serializers.ModelSerializer): id = serializers.CharField(read_only=True, required=False) user = UserSerializer(required=True) text = serializers.CharField(required=True) created = serializers.DateTimeField(read_only=True) object_id = serializers.CharField(required=False) class Meta: model = Comment fields = ('id', 'user', 'text', 'created', 'object_id') read_only_fields = … -
Create multiple entries for one model in a Django modelform
Sorry if the title is confusing, I can't really think of how else to word it. I am creating a site where there are many quizzes. Each Quiz model class Quiz(models.Model): name = models.CharField(max_length = 80) description = models.CharField(max_length = 300) num_questions = models.IntegerField(default = 10) slug = models.SlugField(max_length = 20) img = models.URLField(blank = True) # allow it to be none def __str__(self): return self.name def get_questions(self): return self.question_set.all() looks like this... and it has some attributes like name, description, etc. There are many Question models that have ForeignKey to one Quiz: class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete = models.CASCADE) img = models.URLField(blank = True) # allow none` content = models.CharField(max_length = 200) def __str__(self): return self.content def get_answers(self): return self.answer_set.all() and then there are some Choice models that have ForeignKey to one Question: class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) content = models.CharField(max_length = 200) correct = models.BooleanField(default = False) Now. I want to create one single ModelForm from which I can create 1 quiz record, and then 10 question records with 4 choice records per question. It would be very nice if they could automatically set their foreignkey to the Question that is being created. How … -
How can I have separate trigger and filter conditions in a Django UniqueConstraint?
Given the following models: class Customer(models.Model): pass class User(models.Model): email = models.EmailFIeld(blank=True, default="") customer = models.ForeignKey(Customer, ...) I want to enforce the following: IF user has email IF user has customer email must be globally unique IF user has no customer email must be unique within the user's customer I attempted to implement this with two UniqueConstraints: UniqueConstraint( name="customer_scoped_unique_email", fields=["customer", "email"], condition=( Q(customer__isnull=False) & ~Q(email=None) ), ), UniqueConstraint( name="unscoped_unique_email", fields=["email"], condition=( Q(customer=None) & ~Q(email=None) ), ), Testing has revealed that this still allows a user without a customer to be created with an email identical to an existing user (with a customer). My understanding is that this is because UniqueConstraint.condition determines both when the unique constraint should be triggered and what other records are included in the uniqueness check. Is there any way to achieve my desired logic in the database, ideally in a Django ORM-supported way, and ideally with a UniqueConstraint or CheckConstraint? This must occur in the database. It's obviously possible in Python, but I want the extra reliability of a database constraint. -
Should i use Django DRF or Flask RESTful to write a backend for NextJS frontend and firebase database
Hi Guys i'm developing a website for real-state agent the website would have login functionality for users to login and leave reviews for the listings and also has an admin page for him to add listings from xml files. i decided to do the frontend in nextjs but i'm not sure which framework to choose to develop the backend with firebase database -
Django - "The MEDIA_URL setting must end with a slash." error causes issues for setting file path in Windows
So if you set MEDIA_URL under settings.py without a forward slash (this thing /, you can't do backward slashes I've tried) at the end you get ERRORS: ?: (urls.E006) The MEDIA_URL setting must end with a slash. The issue with this is if I want to store files locally for tests and have the front-end retrieve it for testing locally. If you're on Windows specifically if you set MEDIA_URL=os.path.join(BASE_DIR, 'media/') you get double backwards slashes between directories like so: '/C:\\Users\\Blah\\Documents\\media/videos\\user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960\\2de754bd-644e-466b-8dbb-e4d47a90aaee.mp4' As you can see there's that one forward slash in after media amongst all the double backward slashes, that might cause issues when looking for that address, but if you're running on mac it'll use forward slashes instead which is fine. How can you circumvent this so that you get consistently slashed paths that can be rendered by an image or video components in React Native, when developing on Windows? -
How many separate apps should I have with my Django app
How many apps should I have in my Django project. For instance, I am building a pet application where there can be owners, pets, veterinarians, etc. For now sticking to only the 3 I mentioned should I have these as separate apps within my Django project or should I just create one app to handle everything. I will be adding more features as time goes on. The idea I had was to create a project django-admin startproject mypets Then create an application for each: python manage.py startapp pet and python manage.py startapp pet_owner and python manage.py startapp veterianarian As I mentioned before, there are other features I will be adding to my application like photos todo like feature and so on. My concern is that my project is going to get big which is why I want to separate pet_owner and pet each as their own apps. I was thinking this is exactly what I should do but then realized that when I went to mypets.urls.py file and I was thinking about forwarding some requests to a path I quickly realized that I want my route to always have mypets/. urlpatterns = [ path('admin/', admin.site.urls), path('mypets/petowner/', include('petowner.urls')), path('mypets/pet/', include('pet.urls')), ] … -
How to retrieve the data from the database and display it in a textbox for users to update it
I have a webpage where it is supposed to allow users to update the data from the database but the data is unable to display in the textbox, how do I make it able to display it in the textbox? This is my current webpage where the users need to manually type in all the data they want to update inside the text box. What I wanted is like this, the data is already retrieve from the database for the users to see, and let say they want to update the customer name, they just need to chnage the customer name and click on the submit button to update it, how do I make it able to retrieve the data? views.py @login_required() def updatedata(request, id): photo = Photo.objects.get(id=id) if request.method == 'POST': Photo.mcoNum = request.POST.get('mcoNum') Photo.reception = request.POST.get('reception') form = UpdateForm(request.POST) if form.is_valid(): form.save() return redirect('logdata') else: form = UpdateForm return render(request, 'updatedata.html', {'form': form}) updatedata.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <br><br> <h2 class="text-center">Edit Log Data</h2> <hr> <div class="col-md-6 offset-md-3"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update" class="btn btn-secondary"> </form> </div> {% endblock %} forms.py class UpdateForm(forms.ModelForm): … -
Django 3 tier architecture [duplicate]
I'm working on a project and i'm not sure if Django is a 3 tier (Not same as MVC), so Does Django follow the three-tier architectural design pattern? -
DRF: How to set a correct view_name with the action decoration in a viewset
I have the next action decorator method, I pretend to filter the teachers on the model: @action(detail=True, methods=(['GET'])) def get_teachers_by_area(self, request, pk=None): teachers = self.get_serializer().Meta.model.objects.get_teachers_by_area(pk=pk) if teachers: teacher_serializer = TeacherByAreaListSerializer(teachers, many=True) return Response( { 'ok': True, 'conon_data': teacher_serializer.data }, status=status.HTTP_200_OK ) else: return Response( { 'ok': False, 'detail': 'No se encontró el Área de Conocimiento.' }, status=status.HTTP_400_BAD_REQUEST ) The files of the urls are next: Router.py router = routers.DefaultRouter() router.register( r'school-period', SchoolPeriodViewSet, basename='school_period' ) router.register( r'knowledge-area', KnowledgeAreaViewSet, basename='knowledge_area') urlpatterns = router.urls Urls.py path('user/api/', include('applications.users.routers')), path('school/api/', include('applications.school.routers')), And the Serializers.py of the model is next: class KnowledgeAreaSerializer(serializers.HyperlinkedModelSerializer): teachers = serializers.HyperlinkedRelatedField( view_name='knowledge_area-detail', read_only=True, ) I just pretend return the data (teachers) like an url with the action decorator mentioned before: def to_representation(self, instance): data = super().to_representation(instance) return { 'id': instance.id, 'name': instance.name, 'coordinator': { 'id': instance.coordinator.person.id, 'name': instance.coordinator.person.full_name() }, 'sub_coordinator': { 'id': instance.sub_coordinator.person.id, 'name': instance.sub_coordinator.person.full_name() }, 'objective': instance.objective, 'observations': instance.observations, 'teachers': instance.teachers, 'created_at': instance.created_at } But the problem is that I could not indicate the correct URL of the action method, I did a lot of research but did not find anything about it or with the same requirements. Thanks for helping me by the way. -
django DoesNotExist admin panel good
I have an issue that the try except block. So the admin panel shows entry into the tables but when I run the following piece of code, it goes in the exception handling part try: visitors = Owner.objects.exclude(user=request.user).filter(checked_in=True).count() current = Owner.objects.get(user=u) friends = Friendship.objects.filter(Q(from_friend = u) | Q(to_friend = u)) except Owner.DoesNotExist: print(visitors) visitors = None The code hits the except part and prints the value of visitors as if it exists but then why it calculates that the Owner does not exist , I do not understand. -
How to convert this function to make it function?
I am using this function in upload_to= in models.py: def uuid_profilepicture(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) now = datetime.now() return os.path.join(f'profilepicture/{now.year}/{now.month}/{now.day}/', filename) How can I make it generic function, so I can pass different param for the folder name? -
Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P<id>[0-9]+)/$']
I have a web page where it allows the users to update the existing data from the database, but when i click on the update button, it suppose to redirect the users to the next page but instead I got this error: Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P[0-9]+)/$'], any idea on how to fix this issues? traceback error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/updatedata/5/ Django Version: 3.1.4 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'crispy_forms', 'channels'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', '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 E:\Role_based_login_system-master\templates\home.html, error at line 0 Reverse for 'updatedata' with no arguments not found. 1 pattern(s) tried: ['updatedata/(?P&lt;id&gt;[0-9]+)/$'] 1 : &lt;!doctype html&gt; 2 : &lt;html lang="en"&gt; 3 : &lt;head&gt; 4 : &lt;!-- Required meta tags --&gt; 5 : &lt;meta charset="utf-8"&gt; 6 : &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt; 7 : 8 : &lt;!-- CSS --&gt; 9 : {% load static %} 10 : &lt;link rel="stylesheet" href="{% static 'style.css' %}"&gt; Traceback (most recent call last): File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\TAY\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view …