Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best way to develop an Elastic Beanstalk Django application locally?
I have recently deployed my Django application on Elastic Beanstalk. I have everything working now, but I'm curious what the best way to develop locally is. Currently, after I make a change locally, I have to commit the changes via git and then run eb deploy. This process takes 1-3 minutes which is not ideal for making changes. The Django application will not run on my local machine, as it is configured for EB. -
Prevent Django health check endpoint logs from being sent to Sentry
I have a Django application with a health check endpoint that's using this repo. In the url_patterns I have added the following line: url(r'^ht/', include('health_check.urls')), The issue is that the health check is filling all the Sentry transaction limits. How can I exclude the health check endpoint in Sentry? -
How to save stripe webhook data to session variables in Django?
I am currently working on a 'success' page for my Django project (which uses Stripe to take payments). I would like to show their order total, with tax, on this page. My Stripe webhook is running and posting data, but for the life of me I can't use this data outside of the webhook's veiw. Normally, when I want to inform one view with data from another, I take advantage of Django's session variables. When I save the session variable, however, attempting to use it in my SuccessView returns 'None' rather than the value saved to it. Any help would be appreciated. Here is my relavent code: views.py def stripe_webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] customer_email = session["customer_details"]["email"] line_items = stripe.checkout.Session.list_line_items(session["id"]) print(line_items) stripe_price_id = line_items["data"][0]["price"]["id"] price = Price.objects.get(stripe_price_id=stripe_price_id) total_paid_cents = line_items["data"][0]["amount_total"] total_paid_dollars = total_paid_cents / 100 request.session['total_paid'] = total_paid_dollars return HttpResponse(status=200) class SuccessView(TemplateView): template_name = "musicstudios/success.html" extra_context = sidebar_context def get_context_data(self, **kwargs): context = super(SuccessView, self).get_context_data(**kwargs) order_id = … -
Error running migration after changing to spatialite db
I want to use geographical point in my django app therefor i changed the database engine to spatialite settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 4.1.2. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-+r-63iiele&p+irgsm2ojoayyrk2^6($no8%x+^(32s3wvpk7b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.gis', 'hiketracking.apps.HiketrackingConfig', 'rest_framework', ] 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', ] ROOT_URLCONF = 'server.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'server.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { "ENGINE": "django.contrib.gis.db.backends.spatialite", 'NAME': BASE_DIR / 'db.sqlite3', }, } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S'
I am getting this error time data '2020–04–29 00:00:00' does not match format '%Y-%m-%d %H:%M:%S' input for start date is '2020–04–29' I am trying to srap tweets using twint and I am geting this error ` config = twint.Config() config.Pandas = True payload = json.dumps(request.GET) payload = json.loads(payload) config.Search = payload.get('keyword') config.Lang = payload.get('language','en') config.Limit = int(payload.get('limit',100)) startDate = payload.get("startDate",None) if startDate: config.Since = startDate endDate = payload.get("endDate",None) print(startDate,endDate) if endDate: config.Until = endDate twint.run.Search(config) ` -
django-filter how to add attribute to html tag under form
I'm using Django-filter,I tried to add attributes by using widget and attrs: filter.py: class MyFilter(django_filters.FilterSet): messageText = django_filters.CharFilter(widget=(attrs={'style':'width: 20px', 'class':'form-select form-select-sm'})) class Meta: model = Mymodel fields = ['messageText '] Then I got: SyntaxError: invalid syntax at here 'attrs={' Any friend can help ? -
Self-hosting multiple sites via one Django project + apache - Django Sites framework
I have a self-hosted (raspberry pi) website running on Django - one project with several apps all serving on one domain name. I'm more of a programmer than a server admin, but it works! Now, I'd like to break one of those apps out onto a second domain name, but still hosting from my pi. --I've looked into a lot of tutorials on how to do this as well as checked out answers like this one but the server-related instructions on everything I've found so far all go a bit over my head or don't seem to match up with my setup. --I've tried the Django Sites framework and I've also followed this tutorial. While I was able to get my site objects in the db, all requests seem just to go to SITE_ID=1, regardless of domain name. I've seen conflicting information here about whether or not SITE_ID should be present in settings.py, but whenever I remove it, I just get errors about it (even though I do have the CurrentSiteMiddleware installed as well as a custom middleware like indicated in that tutorial). Here's what I've got for Django (3.2.14, and py3.7.3), essentially: DjangoApps -mysite --settings.py (allowed_hosts includes mydomain) --urls.py … -
"Create a web library application.”
"Create a web library application. A library has books and for each book store id, the name and description, and the image. Each book has one author and many categories. For author store name and bio, for category store only name. Create an admin panel to add books, authors, and categories. The admin panel should require a login.bbjjnj -
SecretManagerServiceClient raises 403 Permission denied CONSUMER_INVALID in Google App Engine but `gcloud secrets versions access` works
Background: I'm trying to deploy a Django app to the Google App Engine (GAE) standard environment in the python39 runtime The database configuration is stored in a Secret Manager secret version, similar to Google's GAE Django tutorial (link) The app is run as a user-managed service account server@myproject.iam.gserviceaccount.com, which has the appropriate permissions to access the secret, as can be confirmed using gcloud secret versions access Problem: In the Django settings.py module, when I try to access the secret using google.cloud.secretmanager.SecretManagerServiceClient.access_secret_version(...), I get the following CONSUMER_INVALID error: google.api_core.exceptions.PermissionDenied: 403 Permission denied on resource project myproject. [links { description: "Google developer console API key" url: "https://console.developers.google.com/project/myproject/apiui/credential" } , reason: "CONSUMER_INVALID" domain: "googleapis.com" metadata { key: "service" value: "secretmanager.googleapis.com" } metadata { key: "consumer" value: "projects/myproject" } My Debugging I cannot reproduce the error above outside of GAE; I can confirm that the SA can access the secret: gcloud secrets versions access latest --secret=server_env --project myproject \ --impersonate-service-account=server@myproject.iam.gserviceaccount.com WARNING: This command is using service account impersonation. All API calls will be executed as [server@myproject.iam.gserviceaccount.com]. DATABASE_URL='postgres://django:...' SECRET_KEY='...' I've also confirmed I run the django app locally with service account impersonation and make the above access_secret_version(...) calls In desperation I even created an API … -
jango.db.utils.ProgrammingError: relation <relation_name> already exists
I am starting a project that is based on some already existing relational data. One problem is the data is not in the exact form I would want it. For example boolean fields are integers etc. What I though would be a good idea to start my project is the following: Download the data in the form they're provided (.csv). Create a database from the csv data, using pandas' dataframe.to_sql method. Create the django app and load the models from the database into models.py using manage.py inspectdb. Change all fields to whatever I want and remove the managed = False in each class Meta subclass of my models class. That's it. Now my project would turn to a normal project like all others. It would keep the data from the tables, but it would allow me to alter the schema however I want (*). The fact that I used dataframe.to_sql method made the data's form even more problematic, for example there are not foreign keys but just varchars or integers. So I had to turn this fields to ForeignKeys manually. The issue I am facing is that whenever I try to apply the migrations I get this error: django.db.utils.ProgrammingError: relation … -
How to handle multiple of multiple [[ids], [ids], [ids]] in django?
We have a use case where the django backend api endpoint has to take a [[ids], [ids], [ids]] as the GET endpoint input, any idea how to handle this in Django rest framework? -
How to add multiply photos to one website page with django?
I'm writing django project for Internet Shop. On the page which describes product I have several photos for this product and I cannot add it to the template. I use 2 models with Many to many relationship - for product and for photos, and added they to template.html. But I don't see any photo in the page. My code is below: models.py: class ProductPhoto(models.Model): def get_file_name(self, filename: str) -> str: ext_file = filename.strip().split('.')[-1] new_filename = f'{uuid.uuid4()}.{ext_file}' return os.path.join('product_photo/', new_filename) # product = models.ForeignKey(Product, on_delete=models.CASCADE) photo = models.ImageField(upload_to=get_file_name) description = models.CharField(max_length=20, blank=True) def __str__(self): return f'{self.description}' class Product(models.Model): slug = models.SlugField(max_length=200, db_index=True) title = models.CharField(unique=True, max_length=100, db_index=True) description_short = models.CharField(max_length=200) description = models.CharField(max_length=500) color = models.CharField(max_length=20) price = models.DecimalField(max_digits=8, decimal_places=2) sale = models.SmallIntegerField(max_length=2, blank=True) new_arrival = models.BooleanField(default=True) is_visible = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) photo = models.ManyToManyField(ProductPhoto) def __str__(self): return f'{self.title}' class Meta: index_together = (('id', 'slug'), ) def get_absolute_url(self): return reverse("shop:products", args=[self.id, self.slug]) views.py: def product_details(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, is_visible=True) cart = Cart(request) return render(request, 'single-product.html', {'product': product, 'cart': cart, }) template.html: <div class="product-details-left"> <div class="product-details-images"> {% for item in product.photo.all %} <div class="lg-image"> <img src="{{ item }}" alt=""> <a href="{{ item }}" class="popup-img venobox" data-gall="myGallery"><i … -
Forward slash "/" vs. os.path.join() for MEDIA_ROOT
I have a form (model form) that sends data(such as images, title, etc.) with POST request. In setting.py file, for MEDIA_ROOT, I tried 2 approach: 1- Forward slash "/" : MEDIA_ROOT = [ BASE_DIR / 'static/images' ] 2- os.path.join(): MEDIA_ROOT =os.path.join(BASE_DIR, 'static/images') When I use the first one(forward slash), I get the below error: TypeError at admin/projects/project/... _getfullpathname: path should be string, bytes or os.PathLike, not list Do you know why I can't use the forward slash "/" for MEDIA_ROOT while this way it completely works for STATIC_ROOT? -
Filter view based on the users Group
I am trying to filter the query further to only show records where the Groups matches the logged in users group. I am new to Python and not sure how to add an additional filter into the below view. View @login_required(login_url='login') def home(request): q= request.GET.get('q') if request.GET.get('q') != None else '' infs= Infringement.objects.filter(Q(name__icontains=q) | Q(infringer__name__icontains=q) ) Model class Infringement (models.Model): name = models.CharField(max_length=200) link = models.CharField(null=True, blank=True, max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) infringer = models.ForeignKey(Infringer, on_delete=models.SET_NULL,null=True) player = models.ForeignKey(Player, on_delete=models.SET_NULL,null=True) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL,null=True) status = models.ForeignKey(Status, on_delete=models.SET_NULL,null=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) class Meta: ordering = ['-updated', '-created']` I tried adding the below but it doesn't work. infs= Infringement.objects.filter(Q(name__icontains=q) | Q(infringer__name__icontains=q|) (groups=request.user.groups) ) -
django.core.exceptions.ImproperlyConfigured: PASSWORD_RESET_TIMEOUT_DAYS/PASSWORD_RESET_TIMEOUT are mutually exclusive
I'm upgrading a django code and I faced this error when I runserver, I tryied already to ALLOWED_HOSTS = ["*"] and it doesn't work -
Edit data in the database that was recorded without a form
In my project, there is a form and a table with checkboxes, based on the data entered in the form and the checkboxes, I fill 2 databases and redirect the user to a page where information from one table is displayed, it all worked very well until I got to editing the records, I decided I do it with UpdateView, passing in template_name the same template as before adding records: here is the add function and the edit class: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def add_campaign(request): if request.method == 'POST': addCampaignDataToDB(request.POST) data = list(Emails.objects.values()) data = MailsTableWithoutPass(data) form = CampaignsForm() data_ = { 'form': form, 'data': data } return render(request, 'mailsinfo/add_campaign.html', data_) But when calling the url to change my data table is empty and there are no selected checkboxes there, all processing of the form works fine Here is the template I use, and the function that writes the data into the tables: <div> <div class="container-campaign"> <div class="campaign-form"> <form method="post" id="newCampaign"> {% csrf_token %} {{ form.name }}<br> {{ form.subject }}<br> {{ form.body }}<br> {{ form.user_guid }}<br> </form> </div> <div class="campaign-table"> <table id="table" data-height="480" class="table table-dark"> <thead> <tr name="mails-info"> <th data-field="state" data-checkbox="true"></th> <th data-field="id">ID</th> … -
How to properly config a django application on cpanel
Before now, the main domain was serving a WordPress website but I needed to replace that with a new django application. I was able to successfully deploy the Django application to cPanel, and the application was served on a subdomain without any problems. But when I edit the application url to point to the main domain, the homepage renders without the static files. Initially, I thought it was a static file issue until I tried to access other pages, but all I keep getting is a 404 page that is being served by the old WordPress. Somehow the old wordpress website is conflicting with the django app. I'm not sure why the old wordpress is still trying to serve the new django pages except the homepage, even though static files are also missing on the homepage. -
How to handle Response when the I'm a expecting a url to download a file?
So I'm using a third party API to make my own, I'm expecting a download url back. But here the response is what I don't know how to handle. Any Help ? class ListUserSearchView(ListAPIView): queryset = UserSearch.objects.all() serializer_class = UserSearchSerializer permission_classes = [IsAdminUser] def get(self, request, data=None, *args, **kwargs): url = "base_url" querystring = {"track_url": request.data.get('track_url')} headers = { "X-RapidAPI-Key": "API key", "X-RapidAPI-Host": "API host" } response = requests.request("GET", url, headers=headers, params=querystring) Response(response.text) -
Django two different URLs map to same view function
New to Django! I want to move some of my URLs to new ones but keep serving old ones for a while. Is there a standard practice in Django for this? I have referred to older posts (How to map two urls to one view?) that have /<person> /<name> mapped to same function. Can I use the same approach for /<person> /company/<company-id>/<person>? Is it just better to add this into query parameter and version bump the API? I like versioning API when new parameters are added into target object, for instance, person having a new field but not for this. Reason: all the new URLs coming after this are guaranteed to have /company// I am still exploring ways. -
Getting error json.decoder.JSONDecodeError
Here's the full traceback of the error I am getting: ERROR 2022-11-08 13:29:54,926: Internal Server Error: /voice_chat/rooms Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 451, in thread_handler raise exc_info[1] File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 38, in inner response = await get_response(request) File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 233, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 414, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "C:\Users\15512\anaconda3\lib\asyncio\tasks.py", line 455, in wait_for return await fut File "C:\Users\15512\anaconda3\lib\concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\asgiref\sync.py", line 455, in thread_handler return func(*args, **kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) request_body = json.loads(decode_request) File "C:\Users\15512\anaconda3\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\15512\anaconda3\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\15512\anaconda3\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ERROR 2022-11-08 13:29:54,959: HTTP POST /voice_chat/rooms 500 [0.32, 127.0.0.1:54258] This is my code: def post(self, request, *args, **kwargs): decode_request = request.body.decode("utf-8") print('decoded request body', decode_request) request_body = json.loads(decode_request) # print('request body', request_body) room_name = request_body.get("roomName") participant_label = request_body["participantLabel"] # print('username', curr_username) response = VoiceResponse() dial = Dial() dial.conference( name=room_name, participant_label=participant_label, start_conference_on_enter=True, ) response.append(dial) return … -
How to add 3 or more Model attributes sitting in one ManytoManyField in Django Models ? Need to display a certain total in frontend
Problem Statement: I want to add up the Activity.models attribute net_cost from within Trip.models i.e. connected via ManytoManyField. I have 3 or more choices per instance, so add: from the template language is inadequate (https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#add) More Context: Activity is connected to Trip via ManytoManyField. Accessing and adding up via save method in models.py is causing id needs to be assigned first error, I believe since ManytoMany can only be assigned once an instance of the model is saved. Even if I access them all in the views.py before rendering, the context passed even after iterating over each object in list, can onlt render a singular grand total for all entries rendered in the template, making it redundant. Models: Activity -> class Activity(models.Model): activity_location = [ ... ] acitivity_duration = [ ... ] activity_title = models.CharField(max_length=20, unique=True) ... net_cost = models.PositiveIntegerField(validators=[MaxValueValidator(100000), MinValueValidator(0)], default=0) class Meta: ordering = ['-margin'] def __repr__(self): return f"{self.activity_title} - {self.activity_location} - {self.net_cost}" def __str__(self): return f"Activity {self.activity_title}, Location {self.activity_location}, Duration {self.acitivity_duration}, Cost {self.net_cost}" def get_absolute_url(self): return reverse('activitys-list') Trip -> class Trip(models.Model): transfer_choices = [ ... ] transfers = models.CharField(max_length=11, choices=transfer_choices, blank=True, null=True) activity = models.ManyToManyField(Activity, related_name="activities", blank=True, verbose_name='Activities', help_text='select multiple, note location tags') .... class Meta: ordering … -
Unable to get (user) as mysite.com/user in right way
I'm using twitter API for authentication process and it works fine. But I want something like mysite.com/user where (user: twitter user name). And I'm able to get this too but the only when I hit the logout button why so? I mean my twitter_callback function running when I hit twitter_logout. As it should be running at the login time! urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), path('<str:username>/', views.user_profile, name='user_profile'), ] views.py from django.contrib import messages from django.contrib.auth import login, logout from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from .decorators import twitter_login_required from .models import TwitterAuthToken, TwitterUser from .authorization import create_update_user_from_twitter, check_token_still_valid from twitter_api.twitter_api import TwitterAPI from django.contrib.auth import logout # Create your views here. def twitter_login(request): twitter_api = TwitterAPI() url, oauth_token, oauth_token_secret = twitter_api.twitter_login() if url is None or url == '': messages.add_message(request, messages.ERROR, 'Unable to login. Please try again.') return render(request, 'authorization/error_page.html') else: twitter_auth_token = TwitterAuthToken.objects.filter(oauth_token=oauth_token).first() if twitter_auth_token is None: twitter_auth_token = TwitterAuthToken(oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) twitter_auth_token.save() else: twitter_auth_token.oauth_token_secret = oauth_token_secret twitter_auth_token.save() return redirect(url) def twitter_callback(request): print("Running twitter_callback") if 'denied' in request.GET: messages.add_message(request, messages.ERROR, 'Unable to login or login canceled. Please try again.') return render(request, 'authorization/error_page.html') twitter_api = TwitterAPI() oauth_verifier … -
How to use the same database on two separate machines (copies)?
I have a web application project that I would like to create with a friend of mine. We are planning to have a simple frontend with JavaScript, a backend with Django, and a PostgreSQL database. We're planning to use apache for the web server. The application would be a simple website showing statistical data from the data in our database. The data in the database would be loaded from CSV files which are stored locally (would not be uploaded through the website, but rather by us). We don't need "live" data, so it would be ok to create the whole database with tables and everything on one machine and then copy that to the other machine. - only problem is that we don't really know how one could do that Now the question I have is: How should we set up our environments so that we can use the same database and the same code? We would use git for code versioning of course, but I am not sure how one would do versioning with a database. I have found online that docker would be a good option, but I have unfortunately very little experience with it so would really … -
Django, How to queue tasks to control the flow of queries?
I'm working on a Django middleware to store all requests/responses in my main database (Postgres / SQLite). But it's not hard to guess that the overhead will be crazy, so I'm thinking to use Redis to queue the requests for an amount of time and then send them slowly to my database. e.g. receiving 100 requests, storing them in database, waiting to receive another 100 requests and doing the same, or something like this. My questions are "is it a good approach? and how we can implement it? do you have any example that does such a thing?" And the other question is that "is there any better solution"? -
Django : Recalculating mean value in the database after creating a new instance
I have informations about companies presented in a table. One of the field of this table is the mean value of each note the company received ('note_moyenne' in models.FicheIdentification). By clicking on a button, people are able to submit a new note for the company ('note' in models.EvaluationGenerale). I want the mean value of the notes to update in the database each time someone submit a new note. Here is my models.py : class FicheIdentification(models.Model): entreprise=models.ForeignKey(Entreprise, on_delete=models.CASCADE) note_moyenne=models.IntegerField() def __str__(self): return self.entreprise.nom_entreprise class EvaluationGenerale(models.Model): entreprise=models.ForeignKey(Entreprise, on_delete=models.CASCADE) note=models.IntegerField() commentaires=models.CharField(max_length=1000) date_evaluation=models.DateField(auto_now_add=True) def __str__(self): return self.commentaires views.py : class CreerEvaluationGenerale(CreateView): form_class = FormulaireEvaluationGenerale model = EvaluationGenerale def form_valid(self, form): form.instance.entreprise=Entreprise.objects.filter(siret=self.kwargs['siret']).first() return super(CreerEvaluationGenerale, self).form_valid(form) def get_success_url(self): return reverse('details-evaluations') Currently I just display the mean value in my table using this def render_evaluation(self, record): return (EvaluationGenerale.objects.filter(entreprise=record.entreprise.siret).aggregate(Avg('note'))['note__avg']) but I really don't like this solution as I want the value to be stored in the database, in FicheIdentification.note_moyenne. I thought about creating a UpdateView class but couldn't manage to link it with my CreateView. Any help or documentation would be really appreciated, I'm a bit lost right know...