Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django Forbidden error with httpd and wsgi
I am using RH8, httpd, wsgi and django. When I attempt to browse to the web page, I get the following error in the web server log: [Wed Sep 21 13:35:09.382780 2022] [core:error] [pid 433487:tid 139782344644352] (13)Permission denied: [client x.x.x.x:28351] AH00035: access to /favicon.ico denied (filesystem path '/opt/django/dcn_automation/dcn_automation') because search permissions are missing on a component of the path, referer: http://xxxx/ This is configured using /etc/httpd/conf.d/django.conf. The contents of which are below. I have tried "Require all granted" inside the files wsgi.py part. This gives the same result. LoadModule wsgi_module "/opt/django/djangoenv/lib64/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so" #WSGIPythonHome "/opt/django/djangoenv" <VirtualHost *:80> <Directory /opt/django/dcn_automation/dcn_automation> <files wsgi.py> Order allow,deny Allow from all </files> </Directory> WSGIDaemonProcess dcn_automation WSGIProcessGroup dcn_automation WSGIScriptAlias / /opt/django/dcn_automation/dcn_automation/wsgi.py process-group=dcn_automation </VirtualHost> -
How to render an image in Django?
I am using the latest version of Django and I am having problems rendering my images. My img tag doesn't work so I googled it and the problem seems to be the static files. So I followed some tutorials online but none of them worked for me. It will be awesome if you could provide me with some guidance, thanks. My index.html is in landing/templates/landing and my static folder is in the root Do I need to move my static folder else where, do I need to add some line of code? -
Display values from a dictionary in python
I converted the python dictionary into a python object, but I can't display the values of the sub-array D Views.py def dictToObject(request): dictionnaire={'A': 1, 'B': {'C': 2},'D': ['E', {'F': 3}],'G':4} obj=json.loads(json.dumps(dictionnaire)) context={'obj':obj} return render(request,'cart/cart_detail.html',context) cart_detail.html {{ obj.D[0] }} {{ obj.D[1].F }} I get an error, I don't know why? -
How to update changes to Azure app service after it's deployed from CLI
IDE used is VSCode. Deployment is done using CLI The command I am using doesn't update it as I have checked the code files using ssh under development tools in azure portal az webapp update --name <name> --resource-group <resource group name> -
How to send nested dictionary as params in python requests.get?
import requests qp_args = {"query_params": {"list1": [], "list2": [], "list3": [], "data": "something"}} data = requests.get(url="Service URL", params = qp_args, timeout=2) # This doesn't work for me, since the client is receiving query_params in chunks, like, # url/?query_params=list1&query_params=list2&query_params=list3&query_params=data what is the correct way to send nested dictionary in the query_params in request.get? -
Django query fetch foreignkey association without N+1 queries in database
I have two models, Product and Price. I have used the ForeignKey association of the Django models to define the association between product and price. the scenario is, one product can have multiple prices according to size. On the home page, I have to fetch all the products with their prices and need to show their price(probably base price). Following is the code that I tried. class Product(BaseModel): name = models.CharField(max_length=50) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL, help_text='Please add new category if not given.') image = models.ImageField(upload_to='images/') tag = models.ManyToManyField(Tag, help_text='You can add multiple tags') slug = models.SlugField(unique=True, null=True) time = models.TimeField(verbose_name='Time Required') class Price(BaseModel): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.FloatField(validators=[MinValueValidator(0)]) amount = models.FloatField(validators=[MinValueValidator(0)]) Then in the view.py file class ProductListView(ListView): model = Product context_object_name = 'products' paginate_by = 32 def get_context_data(self,*args, **kwargs): object = super(ProductListView, self).get_context_data(*args, **kwargs) object['categories'] = Category.objects.order_by('name') return object def get_queryset(self): return Product.objects.order_by('name') In the template, I am able to get and loop through the categories and products but I am not able to access the related prices of each product. If I tried something in the get_context_data, will it cause N+1 queries to fetch prices for every product? In the template I tried to use … -
DJANGO - View/update; No TwitterModel matches the given query
I am having trouble updating/viewing my table with models and forms. I should be able to check my table objects when i go to /twitter/edit/PK but I'm getting error message that is telling me 'No TwitterModel matches the given query.' This is my models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class TwitterModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Twitter_API_key = models.CharField(max_length=110, default='default') Twitter_API_key_secret = models.CharField(max_length=110, default='default') Twitter_API_token = models.CharField(max_length=110, default='default') Twitter_API_token_secret = models.CharField(max_length=110, default='default') def __str__(self): return self.user.username This is my forms.py from django import forms from .models import TwitterModel class TwitterUpdateForm(forms.ModelForm): class Meta: model = TwitterModel fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"] Those are my views.py from dataclasses import fields from gc import get_objects from re import L from django.shortcuts import render, redirect from .models import TwitterModel from .forms import TwitterUpdateForm from django.contrib.auth.decorators import login_required from django.contrib import messages from django.views.generic import (ListView, DetailView, CreateView, UpdateView, DeleteView) from django.shortcuts import get_object_or_404 # Create your views here. @login_required def twitter(request): if request.method == 'POST': tw = TwitterUpdateForm(request.POST) if tw.is_valid: obj = tw.save(commit=False) obj.user = request.user obj.save() messages.success(request, f'NICE!') return redirect ('twitter') else: tw = TwitterUpdateForm() context = {'tw': tw} return render(request, 'twitter_container/twitter_container.html', context) def twitter_edit(request, pk=None): … -
How to turn off reverse relation within same model in django
I have the following django model class Course(models.Model): name = models.CharField(max_length=50) pre_req_courses = models.ManyToManyField('self', default=None) def __str__(self): return self.name when I create courses in following way: course1 = Course.objects.create(name='Course1') course1.save() course2 = Course.objects.create(name='Course2') course2.save() course2.pre_req_courses.set(course1) when I run the following command I get: course2.pre_req_courses.all() >>> <QuerySet [<Course: Course1>]> course1.pre_req_courses.all() >>> <QuerySet [<Course: Course2>]> Wht I want is: course2.pre_req_courses.all() >>> <QuerySet [<Course: Course1>]> course1.pre_req_courses.all() >>> <QuerySet []> How can I achieve this -
How to make more than one fields primary key and remove auto generated id in django models
Suppose in a relational database schema we have a student, a subject and a teacher which connect to each other with a relation teaches. Also, the relation has an attribute time that stores the time of the lesson. This is the most complete yet simplified example I can think to describe my case. Now, the most pythonic and django-wise way I can think of trying to reach a correct solution is, after creating a model class for student, subject and teacher, to create a new class Teaches, which has the foreign keys for the three other classes; also it has the property date field for time. This class would look something like this: class Teaches(models.Model): teachers = models.ForeignKey(Teacher, on_delete_models.CASCADE) subjects = models.ForeignKey(Subject, on_delete_models.CASCADE) students = models.ForeignKey(Student, on_delete_models.CASCADE) time = models.DateField class Meta: constraints = [ fields=['teachers', 'subjects', 'students'] name='teacher_subject_student_triplet' ] I added the Meta class because this is what this answer recommends as the correct approach. The problem is that that in the migrations file I can still see the id field. The only way I've seen there is to remove it is to set another field as Primary Key, but in my case I cannot do that, having more … -
Django wsgi file not configured correctly
I am attempting to get my django application working using wsgi and httpd on RH8. There seems to be a formatting issue pointing wsgi at the virtual environment. In the example I am following, there is an activate.py file. Am I missing something? I can see activate in other formats (activate.ps1 for example) in the bin directory. Here is my wsgi.py """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/ """ python_home = '/opt/django/djangoenv' activate_this = python_home + '/bin/activate' with open(activate_this) as f: code = compile(f.read(), activate_this, 'exec') exec(code, dict(__file__=activate_this)) import os import sys from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dcn_automation.settings') application = get_wsgi_application() Here is the path to my virtual environment: /opt/django/djangoenv/bin/ When I run the server manually, I get this error: $ python3 manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). September 21, 2022 - 11:01:02 Django version 4.1.1, using settings 'dcn_automation.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib64/python3.8/threading.py", line 870, in run … -
Django User Filtering and Pagination
I've built a filtering function to process user selected filtering on my Product model, however I'm having trouble making it work correctly with pagination. My view can process both a search bar query and product filtering. Currently I'm not sure how to allow the paginator to pass the next page of results. As you can see in the view / filtering function below this setup just processes a new request and returns all currently. View: @login_required @permission_required('products.view_product', raise_exception=True) def productQueryListView(request): context = { 'fascias': Fascia.objects.all() } if request.GET.get('page') == None: # Searchbar Query if request.GET.get('q') != None: queryResults = searchProducts(request) # Filter Query else: queryResults = processProductQuery(request) paginator = Paginator(queryResults, 50) page_number = request.GET.get('page') product_list = paginator.get_page(page_number) context.update({ 'product_list': product_list, 'product_count': paginator.count }) return render(request, 'products/product-query.html', context) Filter Function: def processProductQuery(request): fascias = request.GET.getlist('fascia') statuses = request.GET.getlist('status') initialDelivery = request.GET.get('initialdelivery') initialUpload = request.GET.get('initialupload') delivered = request.GET.get('delivered') uploaded = request.GET.get('uploaded') productQuery = Product.objects.all().distinct() if len(fascias) > 0: productQuery = productQuery.filter(fascia__in=fascias).distinct() if len(statuses) > 0: productQuery = productQuery.filter(status__in=statuses).distinct() if initialDelivery and len(initialDelivery) > 0: initialDelivery = datetime.datetime.strptime(initialDelivery, '%Y-%m-%d') productQuery = productQuery.filter(initial_delivery__date=initialDelivery).distinct() if initialUpload and len(initialUpload) > 0: initialUpload = datetime.datetime.strptime(initialUpload, '%Y-%m-%d') productQuery = productQuery.filter(initial_upload__date=initialUpload).distinct() if delivered and len(delivered) > 0: delivered = … -
Django Migrations - How can I migrate my own django models without any inbuild models like auth,sessions,sites,admin etc
I have a requirements so that its not possible to change given schema. I dont need any django inbuild models such as admin,auth,sessions,messages etc.. how can I migrate my models without the inbuild models. I will be gratefull if you can help me. Thank you. -
How to reuse a model-field's default automatically, when such field (its name) doesn't constitute the data fed to model-form constructor?
app.models.py: from django.db import models from main.custom_fields import HTTPURLField from main.function_validators import validate_md5 class Snapshot(models.Model): url = HTTPURLField(max_length=1999) content_hash = models.CharField(max_length=32, default='00000000000000000000000000000000', validators=[validate_md5]) timestamp = models.DateTimeField(auto_now=True) app.forms.py: from django import forms from .models import Snapshot class SnapshotModelForm(forms.ModelForm): class Meta: model = Snapshot fields = ('url', 'content_hash') app.views.py: from .forms import SnapshotModelForm def index(request): snapshot_form = SnapshotModelForm(data={'url': ' https://stackoverflow.com/ '}) if snapshot_form.is_valid(): model_instance = snapshot_form.save() I want my SnapshotModelForm instance (snapshot_form) to be populated also with a 'content_hash' and it' sdefault value (given in Snapshot class definition), when not fed via POST data or other kind (input) data used by ModelForm's constructor. -
Is it possible to change the inbuild validator Messages in Django Models
When ever i miss the email it should throw some other error message rather than Enter a valid email address models.py class Publisher(models.Model): email=models.EmailField(blank=True,null=True) serializer.py class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = '__all__' -
Unique validation error with base_field of a django array field during update
I want the phone numbers inside my phones field to be unique across all customers. it works fine during creating a new customer, But during update i got a unique validation error. def prevent_replicated_phone(phone): # Count all customers which own the same number phone_holders = Customer.objects.filter(phones__contains=[phone]).count() if phone_holders > 0 : raise ValidationError( f'The phone number: {phone} already exist', class Customer(models.Model): def __str__(self) : return self.customer_name id = models.BigAutoField(primary_key=True) customer_name = models.CharField(max_length=100, null=False, blank=False, unique=True) phones = ArrayField(models.CharField(max_length=10, validators=[validate_phone_number, prevent_replicated_phone]), default=list, null=True, blank=True) customer_type = models.CharField(max_length=10,default='patient', choices=CUSTOMER_TYPE) Let say i have a customer hold the phones ['0795364588']. I send a put request to update the customer phones with new array ['0795364588', '0668123544']. Updating the customer phones with postman How i can solve this. -
Django return custom HTTP message
I'm trying to be compatible with an app-side bug(). I want to return a response with custom HTTP message For example, I get HTTP/1.1 429 TOO_MANY_REQUESTS now, I want get HTTP/1.1 429 CUSTOM_MESSAGE Howerver, I can get only h2 200 -
I can store password when want to create a user in django
Model this is my extended model with one to one field class Etudiant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True) nom = models.CharField(max_length=50) prenom = models.CharField(max_length=50) username = models.CharField(max_length=50) num_cart = models.IntegerField(default=0) email = models.EmailField(max_length=254) date_naissance = models.DateField(auto_now=False, auto_now_add=False,blank=True,null=True) password = models.CharField(max_length=50,null=True,blank=True) groupe = models.ForeignKey("Group", on_delete=models.CASCADE,null=True,blank=True) this is the forms of user form and etudiant form forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('username','first_name', 'last_name', 'email','password') widgets = { 'username' : forms.TextInput(attrs={'class':'form-control'}), 'first_name' : forms.TextInput(attrs={'class':'form-control'}), 'last_name' : forms.TextInput(attrs={'class':'form-control'}), 'email' : forms.EmailInput(attrs={'class':'form-control'}), 'password' : forms.PasswordInput(attrs={'class':'form-control'}), } class EtudiantForm(forms.ModelForm): class Meta: model = Etudiant fields = ('num_cart','date_naissance','groupe') widgets = { 'num_cart' : forms.NumberInput(attrs={'class':'form-control'}), 'date_naissance' : forms.DateInput(attrs={'class':'form-control'}), 'groupe' : forms.Select(attrs={'class':'form-control'}), } this views for store data to db all the data stored just the password I see "Invalid password format or unknown hashing algorithm. " #views.py def ajouter_etudiant(request): user_form = UserForm() etudiant_form = EtudiantForm() if request.method == 'POST': user_form = UserForm(request.POST) if user_form.is_valid() : user_form.save() user = User.objects.get(username = request.POST['username']) groupe_name = Group.objects.get(id=request.POST.get('groupe')) Etudiant.objects.create( user = user, username = user.username, nom = user.last_name, prenom = user.first_name, num_cart = 123456789123456789, email = user.email, date_naissance = request.POST.get('date_naissance'), groupe = groupe_name ) return redirect('all_etudiant') return render(request,'etudiant/ajouter-etudiant.html',{'form' : user_form,'form2':etudiant_form}) -
How to use prefetch_related to retrieve multiple rows similar to SQL result
I’ve a question about the usage of prefetch_related. Based on my understanding I need to use prefetch_related for reverse foreign key relationships As an example I have a User(id, name) model and SchoolHistory(id, start_date, school_name, user_id[FK user.id]) model. A user can have multiple school history records. If I’m querying the database using the following SQL query: SELECT user.id, name, start_date, school_name FROM user INNER JOIN school_history ON school_history.user_id = user.id the expected result would be: | User ID | Name | Start Date | School | | 1 | Human | 1/1/2022 | Michigan | | 1 | Human | 1/1/2021 | Wisconsin | This is the current result that I’m getting instead with ORM and a serializer: | User ID | Name | school_history | 1 | Human | [{start_date:1/1/2022 , school:Michigan}, {start_date:1/1/2021 , school:Wisconsin}] | This is the ORM query that I’m using: User.objects.prefetch_related( Prefetch( ‘school_history’ query_set=SchoolHistory.objects.order_by(‘start_date’) ) ) Is there a way for the ORM query to have a similar result as SQL? I want multiple rows if there are multiple schools associated with that user -
DRF SlugRelatedField causes extra queries with the argument `queryset` when making get request
in debug tool bar, I can tell there are duplicate queries pointing to source and target and also workflow. So I decide to make those two fields read_only=True and remove the queryset argument. And things work perfectly. my code looks like: # model class Activity(models.Model): class Meta: db_table = "activity" uuid = serializers.UUIDField(read_only=True) some fields ... class Flow(models.Model): class Meta: db_table = "workflow_flow" objects = FlowManager() source = models.ForeignKey( "Activity", db_index=True, related_name="outgoing", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, null=True, blank=True, default="" ) target = models.ForeignKey( "Activity", db_index=True, related_name="incoming", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, null=True, blank=True, default="" ) workflow = models.ForeignKey( "WorkFlow", db_index=True, related_name="flows", to_field='uuid', db_constraint=False, on_delete=models.CASCADE, max_length=32, ) # serializer class FlowSerializer(ModelSerializer): class Meta: fields = "__all__" model = Flow condition = serializers.CharField( default="", required=False, allow_null=True, allow_blank=True, write_only=True ) # foreign key source = serializers.SlugRelatedField( queryset=api_models.Activity.objects.all(), slug_field="uuid", ) target = serializers.SlugRelatedField( slug_field="uuid", queryset=api_models.Activity.objects.all() ) workflow = serializers.SlugRelatedField(slug_field="uuid", queryset=api_models.WorkFlow.objects.all()) # viewset class FlowViewSet(ModelViewSet): queryset = api_models.Flow.objects.all().select_related("source", "target", "workflow").all() lookup_field = 'uuid' serializer_class = api_serializers.FlowSerializer But I need to create those two fields any idea? I know I can change them to CharField Instead But I want a correct way to handle this. By reading the source code of the SlugRelatedField queryset is used for … -
How to implement a HTTP API with django
I have read that HTTP APIs are faster and more light-weight than REST APIs. However I only find resources that explain how to build REST APIs in django. How do you build a HTTP API and not a REST API in django? -
access URL data in serializers class in Django Rest Framework
I'm getting None while accessing the data of the request. views.py def get(self, request, post_id, post_language_id, user_id): ... paginator = CustomPageNumberPagination() response = paginator.generate_response(language_liked_data, PostLanguageLikedSerializer, request) return response but I need user_id from the URL so I found a way to access data through context. so I can access the value in the serializer. views.py def get(self, request, post_id, post_language_id, user_id): ... language_liked_data = PostLanguageLike.objects.filter(post_language_id=post_in_lang.id) post_language_like_serializer = PostLanguageLikedSerializer(language_liked_data, context={'user_id': user_id}, many=True) return Response({"response": True, "return_code": "success", "result": {"liked_users": post_language_like_serializer.data}, "message": success["success"]}, status=200) serializers.py class PostLanguageLikedSerializer(serializers.ModelSerializer): is_following = serializers.SerializerMethodField() ... class Meta: model = PostLanguageLike fields = [...,'is_following'] def get_is_following(self, obj): # here I want to access URL data. user_id = self.context.get("user_id") user_followings = UserFollowing.objects.filter(user_id=user_id, following_user_id=obj.user.id) is_following = True if len(user_followings) > 0 else False return is_following the issue is I'm not able to use context={'user_id': user_id} with paginator.generate_response is there any better way to get URL data in the serializer? -
Django local variable 'context' referenced before assignment
where is my mistake? Can anyone see it? view.py error -
Swagger not responding when adding urls from another django app
I have a simple Django app and want to include urls to project urls. Project urls look like this: from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView, ) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/user/', include('user.urls')), #path('api/', include('LinkTaskApp.urls')), ] And LinkTaskApp urls look like this: from django.urls import path from .views import AccountListView urlpatterns = [ path('account/', AccountListView.as_view(), name='account-list'), ] As soon as I uncomment in the main urls: #path('api/', include('LinkTaskApp.urls')), I get following error when I start Swagger: Failed to load API definition. Errors Hide Fetch error Internal Server Error /api/schema/ In browser, it looks like this: Request URL: http://127.0.0.1:8000/api/schema/ Request Method: GET Status Code: 500 Internal Server Error Remote Address: 127.0.0.1:8000 Referrer Policy: same-origin Any Ideal how to successfully include this url and get swagger to work? -
how to run python manage.py migrate inside a docker container that runs Django with apache2
I'm running Django app inside Docker container with apache2, I need to add the command python manage.py migrate inside the Dockerfile or docker-compose but am unable to run it . Dockerfile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip #Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 WORKDIR /var/www/html/demo_app CMD ["apache2ctl", "-D", "FOREGROUND"] CMD ["python", "manage.py", "migrate", "--no-input"] docker-compose version: "2" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypasswordhere - PGDATA=/tmp django-apache2: build: . container_name: water_maps environment: - POSTGRES_DB=database_innvoentiq - POSTGRES_USER=database_user_innvoentiq - POSTGRES_PASSWORD=mypasswordhere - PGDATA=/tmp ports: - '80:80' volumes: - ./www/:/var/www/html depends_on: - db what happens here is that the container exists after running the last CMD in the Dockerfile -
Why am I getting a No Reverse Match error when submitting using UpdateView?
I'm currently using UpdateView to add edit functionality to my Django project. It's working correctly insofar as I can edit my data, however when I submit the new data, it returns a NoReverseMatch error: NoReverseMatch at /MyHealth/edit/8 Reverse for 'health_hub_history' not found. 'health_hub_history' is not a valid view function or pattern name. I've researched it and added a get_absolute_url to my model, but it isn't working. Any help would be appreciated! models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse class HealthStats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) run_distance = models.IntegerField(default=5) run_time = models.TimeField() class Meta: db_table = 'health_stats' ordering = ['-date'] def get_absolute_url(self): return reverse('health_hub_history') def __str__(self): return f"{self.user} | {self.date}" urls.py: from django.urls import path from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView from . import views app_name = 'HealthHub' urlpatterns = [ path('', views.home, name='home'), path('MyHealth/', views.health_hub, name='health_hub'), path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'), path('MyHealth/history', views.health_history, name='health_hub_history'), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))), path('MyHealth/delete/<item_id>', views.delete_entry, name='health_hub_delete'), path('MyHealth/edit/<int:pk>', views.EditHealth.as_view(), name='health_hub_edit'), ] Views.py: class EditHealth(UpdateView): model = HealthStats template_name = 'health_hub_edit.html' fields = ['weight', 'run_distance', 'run_time'] health_hub_edit.html: {% extends 'base.html' %} {% load static %} {%load crispy_forms_tags %} {% block content %} <div class="container-fluid"> <div class="row"> <div …