Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelMultipleChoiceField initial values
I'm struggling to include the right initial values for a ModelMultipleChoiceField (as checkbox widget). I generate the required initial selection in the view and pass it to the form as 'data' via **kwargs. Using print(...) I have verified that this information makes it to the forms.py but it then doesn't make it to the form itself. The two selected strengths (in the list [2,3]) are always shown... class StrengthsForInstanceForm(forms.ModelForm): strength = forms.ModelMultipleChoiceField(queryset=Strength.objects.all()) class Meta: model = Instance exclude = ['name','subject','observer'] def __init__(self, *args, **kwargs): selected_strengths = [2,3] if kwargs.get('data'): selected_strengths = kwargs.pop('data') super(StrengthsForInstanceForm, self).__init__(*args, **kwargs) self.fields["strength"].widget = CheckboxSelectMultiple() self.fields["strength"].queryset = Strength.objects.all() self.fields["strength"].initial = selected_strengths Any ideas on how to solve this? -
Can't save serialized object with django apiview
i'm creating a API which is a get,put,delete in django i've already created one api that works but when i'm trying to use the APIView it does not work for reasons i dont know! and actually makes no sense for me. what i want is to transform the api def todo_get_change_delete(request,pk): into the new APIview api TodoUpdate(APIView): from rest_framework.decorators import api_view from app.models import Todo from app.serializers import TodoSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.exceptions import NotFound from rest_framework.views import APIView class TodoListAndCreate(APIView): def get(self, request): todos =Todo.objects.all() serializer = TodoSerializer(todos,many=True) return Response(serializer.data) def post(self, request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status= status.HTTP_201_CREATED) return Response(serializer.errors,status = status.HTTP_400_BAD_REQUEST) @api_view(['GET','DELETE','PUT']) def todo_get_change_delete(request,pk): try: todo = Todo.objects.get(pk=pk) except Todo.DoesNotExist: return Response(status = status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TodoSerializer(todo) return Response(serializer.data) elif request.method == 'PUT': serializer = TodoSerializer(todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) elif request.method == 'DELETE': todo.delete() return Response(serializer.data,status = status.HTTP_204_NO_CONTENT) class TodoUpdate(APIView): def get_object(self, pk): try: todo = Todo.objects.get(pk=pk) return TodoSerializer(todo).data except Todo.DoesNotExist: raise NotFound def get(self, request,pk): todo = self.get_object(pk) return Response(TodoSerializer(todo).data) def put(self, request,pk): todo = self.get_object(pk) serializer = TodoSerializer(todo, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors,status= status.HTTP_400_BAD_REQUESTs) with thes … -
Problem in sending Dictionary object(converted JSON file) to template using render in DJANGO
I am fetching an external json file . Whenever I send the data in dictionary form to html page and reload it, The page doesn't opens instead that html file is downloaded. My views function: def index(req): data = urllib.request.urlopen("https://api.covid19india.org/states_daily.json").read() output = json.loads(data) print(output) return render(req,'india.html',{'countries':countries},{'states':output}) -
How to work with forloop and template model?
Here I am using simple a card snippet for all the post shown in post_list template. And I have added a template model so when i click on particular post it show me that model with the content of the post on which i clicked. With the following code, Almost everything is working okay but when i click on any post it show me the content of first post. I want to see content of the post in a model on which i clicked. {% for post in post_list%} <div class="cardbox"> <div class="cardbox-heading"> <div class="media m-0"> <div class="d-flex mr-3"> <a href="#"><img class="img-responsive img-circle" src="{{post.username.avatar.url}}" alt="User"></a> </div> <div class="media-body"> <p class="m-0">{{post.username}}</p> <small><span>{{post.create_date|timesince}}</span></small> </div> </div><!--/ media --> </div><!--/ cardbox-heading --> <div class="cardbox-item"> <a href="#myModal" data-toggle="modal"> <img class="img-responsive" src="{{post.image_data.url}}" alt="MaterialImg"> </a> </div><!--/ cardbox-item --> </div><!--/ cardbox --> Modal Section =============================================== --> <div id="myModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <div class="row"> <div class="col-md-8 modal-image"> <img class="img-responsive" src="{{post.image_data.url}}" alt="Image"/> </div><!--/ col-md-8 --> <div class="col-md-4 modal-meta"> <div class="modal-meta-top"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> <span aria-hidden="true">×</span><span class="sr-only">Close</span> </button><!--/ button --> <div class="img-poster clearfix"> <a href="#"><img class="img-responsive img-circle" src="{% static 'assets/img/users/18.jpg'%}" alt="Image"/></a> <strong><a href="#">Benjamin</a></strong> <span>12 minutes ago</span><br/> <a href="#" class="kafe kafe-btn-mint-small"><i class="fa fa-check-square"></i> Following</a> </div><!--/ … -
python django validate user input by decorator or extra function? Whats more pythonic?
Im working on a web application. The user can set some parameters to run some algorithms. So when I extract the parameters in the backend, I want to validate them before starting an algorithm, that could crash after a long execution time. Should I use a decorator around the algorithm function or should I pass the parameters to a function like def validate_parameters(), which raises an error if the parameter are incorrect? -
Python3.9 Django Docker Postgres
I'm trying to update my docker image switching from python:3.8.2-alpine3.10 to python:3.9.0-alpine3.12, but I'm getting an issue when running django commands SSL_check_private_key: symbol not found. I get the following error when running checks: bash -c "touch /var/donor_reporting_portal/.touch && django-admin check --deploy " /usr/local/lib/python3.9/site-packages/environ/environ.py:628: UserWarning: /usr/local/lib/python3.9/site-packages/donor_reporting_portal/config/.env doesn't exist - if you're not configuring your environment separately, create one. Traceback (most recent call last): File "/usr/local/bin/django-admin", line 8, in sys.exit(execute_from_command_line()) File "/usr/local/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line File "/usr/local/lib/python3.9/site-packages/django/core/management/init.py", line 377, in execute File "/usr/local/lib/python3.9/site-packages/django/init.py", line 24, in setup File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 116, in create File "/usr/local/lib/python3.9/importlib/init.py", line 127, in import_module File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 790, in exec_module File "", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/django/contrib/postgres/apps.py", line 1, in File "/usr/local/lib/python3.9/site-packages/psycopg2/init.py", line 51, in ImportError: Error relocating /usr/local/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-x86_64-linux-gnu.so: SSL_check_private_key: symbol not found make[2]: *** [.run] Error 1 make[1]: *** [test] Error 2 make: *** [build] Error 2 I don't get any issue when running this on my machine. -
Need Contrains for Foreign Key
I am creating a College Management App in Django. Here is my model. file: accounts/model.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): ROLE = {('student', 'student'), ('staff', 'staff'), ('account_manager', 'account_manager'), ('Admin', 'Admin')} role = models.CharField(choices=ROLE, default='student', max_length=20, blank=True, null=True) I am using the inbuilt user class for all the users (staff, student, HOD and principal). We can identify the user by the role. No, I want to create a course database, where the staff_id will be the foreign key of CustomeUser table. Is there any way to select the user with the role of the foreign key? class Course(models.Model): course = models.CharField(max_length=150) start_date = models.DateField() end_date = models.DateField() instructor = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='instructor_name') examinar = models.ForeignKey( CustomUser, on_delete=models.CASCADE, related_name='examinar_name') def __str__(self): return f'{self.course.name} Batch No: {self.batch_no}' Here both referring to the same CustomUser foreign key. That's why I have added the related name. (is this a right approach?) But in the admin page, if I want to add a new course, I am getting all the users. like this, [![enter image description here][1]][1] I want to display the users only if the role is staff. Is it possible? [1]: https://i.stack.imgur.com/pxn6S.png -
How can I connect a model instance to a user in django?
Im looking to make it so the logged in user that creates a profile is linked to their guestprofile model when they create their profile. When I create the guest profile while logged in, it successfully creates the guest profile, but in the guest profile admin screen there is no user connected to the guest profile model created. Instead there is a dropdown menu listing all users, which makes the connection process manual. Thanks. views.py class AddProfileView(CreateView): model = GuestProfile form_class = AddProfileForm template_name = 'profilemanip/addprofile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user Forms.py class AddProfileForm(forms.ModelForm): name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'class': 'form-control'})) location = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) summary = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'})) profile_pic = forms.ImageField() class Meta: model = GuestProfile fields = ('name', 'location', 'summary', 'profile_pic') Models.py class GuestProfile(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) location = models.CharField(max_length=100) summary = models.TextField(max_length=350) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/") def __str__(self): return str(self.user) -
i want to create a search in django which have order by istartswith first than icontains
def autocomplete(request): template_name='searchresults.html' if 'term' in request.GET: qs=Post.objects.filter(Q(title__istartswith=request.GET.get('term'))|Q(content__icontains=request.GET.get('term'))) titles=list() for post in qs: titles.append(post.title) return JsonResponse(titles, safe=False) return render(request, template_name) How can I can order them ins such a way that if it begins with term order it as first and the one that contains it but does not begin with it as second -
Search form only works on home page
I have a search form that works correctly on the home page but not on any other page. The search form is embedded in the nav bar which has its own html file. Also, the ul for the search results in nested right below the search form. I want it to work regardless of what page the user navigates to. Here is the main.html: <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2", type="text", name="search" placeholder="Search"> </form> <ul id="search-results"> </ul> Here is the views.py: def home(request): post = Pilot.objects.all().order_by('id') #Search Filter search = request.GET.get('search') if search != '' and search is not None: post = post.filter(Q(title__icontains=search) | Q(writer__icontains=search)).distinct() ... return render(request, 'home.html', context) Here is the urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home"), path('about/', views.about, name="about"), path('comment/', views.comment, name="comment"), path('comment_submit/', views.comment_submit, name="comment_submit"), -
404 in Django isn't working, I get a 500 error [closed]
My custom 404 page says "500 server error", instead of showing the custom 404 page. I also turned off debug in the settings. -
How to automatically mark a specific field either False or true after certain time has been elapsed?
I'm creating a Hotel table reservation web app in Django 3.x.x I have a Table Model with isBooked field that is set to either False or True depending on a table status. Code for this model: class Table(models.Model): title = models.CharField(max_length=50, null=True) t_id = models.IntegerField("Table ID", null=True, unique=True) isBooked = models.BooleanField('Is Booked', default=False) chairs_booked = models.IntegerField("Chairs Booked", default=0) max_chairs = models.IntegerField("Total Chairs", default=0) max_book = models.IntegerField("Least Bookable", default=0) chairs_left = models.IntegerField("empty chairs", default=0) Now, I have another Model called Reservation that stores data for booked Tables. Here is its code: class Reservation(models.Model): t_username = models.CharField("Booked By", max_length=100, null=True) t_email = models.EmailField("Email Address", null=True) t_phone = models.IntegerField("Phone Number", default=0, null=True) t_id = models.IntegerField("Table Id", null=True) booked_date = models.CharField("Check In Date", null=True, max_length=50) # '2020-10-27' booked_time = models.CharField("Check in Time", null=True, max_length=50) # '7:00' def _get_checkout_date(self): t = self.booked_date return t checkout_date = property(_get_checkout_date) def _get_checkout_time(self): the_time = dt.datetime.strptime(self.booked_time, '%H:%M') new_time = the_time + dt.timedelta(hours=3) return new_time.strftime('%H:%M') checkout_time = property(_get_checkout_time) at this point, I have a table with following information stored in variables: booked_time this holds a string for time showing when table was booked e.g. 7:00 checkout_time this holds a string for time showing when table should be vacated/checked-out e.g 10:00 … -
How can I link an input to an object's attribute and update that attribute as you click on it?
Given these model, view, and template files: models.py class Item(models.Model): class Included(models.IntegerChoices): YES = 1 NO = 0 included = models.IntegerField(choices=Included.choices, default=Included.YES) name = models.CharField() views.py def index(request): items = Item.objects.all() context = { 'items':item } return render(request, template.html, context( template.html {% for item in items %} {{ item.name }} <input type="checkbox"> {% endfor %} How can I do it such that the checkbox reflects if the Item it's with is included or not? How can I change if it's included or not by just ticking the checkbox? In general, how can I link an input to an object's attribute and update that attribute as you click on it? I don't think it would be feasible to use forms here, as it only changes a field. Plus if it's possible, do it realtime. Forms won't update a page unless you refresh it afaik, any ideas? -
Trying to create a cronjob in django using faust
I'm trying to create a cronjob in django using faust. If I create a simple cronjob printing somethin' on screen it works, but if I try to use some ORM thing it doesn't. @sync_to_async def get_products(): return Product.objects.filter(active=True) @app.crontab('* * * * *') async def run_very_minute(): product = await get_products() print(product) I also tried to do like this: @app.crontab('* * * * *') async def run_very_minute(): products = await sync_to_async(list)(Product.objects.filter(active=True)) print(product) -
how to accept all the answers from form?
this is my form in which i am conducting a quiz <form action="test" method="post"> {% csrf_token %} {% for question in questions %} {{question.question}} <input type="radio" id="1" name="{{question.qno}}" value="1">:{{question.option1}}<br> <input type="radio" id="2" name="{{question.qno}}" value="2">:{{question.option2}}<br> <input type="radio" id="3" name="{{question.qno}}" value="3">:{{question.option3}}<br> <input type="radio" id="4" name="{{question.qno}}" value="4">:{{question.option4}}<br> {% endfor %} <input type="submit" value="submit"> </form> there are multiple questions generated on the screen as per my database. I have to accept all the values and pass it to my views.py for further processing how to do so? -
Returning GraphQL object in Django Saleor
In Django Saleor, what is right way to get the GraphQL objects from the API. For example if I wanted to retrieve the shippingMethods, I am running: { shippingMethods { name } } The error I get is: Cannot query field "shippingMethods" on type "Query" Link to API Doc: https://docs.saleor.io/docs/api-reference#shippingmethod Any help is appreciated -
How do i specify a queryset to a django form widget in a generic UpdateView
My model : class TarifGe(models.Model): mise_a_disposition = models.ForeignKey(MiseADisposition) tarif_son = models.ForeignKey("TarifGe", on_delete=models.CASCADE, null=True, default=None, blank=True) My View : class TarifGeUpdate(LoginRequiredMixin, UpdateView): model = TarifGe template_name = "tarifs_form.html" fields = ['tarif_son',] tarif_fils is a TarifGe related object (father -> Son) I would like to filter the initial values of the widget of de tarif_son field, to only have TarifGe objects that have the same mise_a_disposition field, instead of all the TarifGe objects. Where and how can i specify the queryset for the "tarif_son" field's widget ? Thanks in advance for your help. -
Django can't search "method not allowed"
im new to django and im currently doing a website for my friend. he wants me to make a system where the users can search the database and the website gives the relevent items according to their serial number. i followed a tutorial from the following site: https://learndjango.com/tutorials/django-search-tutorial to figure out how to do db searchs which helped a lot, but im still having a problem: my search bar works, and the result page also works but it only works when i manually type the query on the searchbar myself (e.x. results/?q=number1). However when i search using the input bar and the submit button it sends me to /results/ page and the page gives this: This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405 -when i open up pycharm to see the error in terminal it says: Method Not Allowed (POST): /result/ Method Not Allowed: /result/ [27/Oct/2020 20:06:02] "POST /result/ HTTP/1.1" 405 0 here are my codes(python3.7,pycharm) websites/urls: from . import views from django.urls import path from django.contrib.auth import views as auth_views urlpatterns = [ path('register/',views.UserFormView.as_view(), name='register'), path('login/', auth_views.LoginView.as_view(), name='login'), path('', views.IndexViews.as_view(), name='index'), path('scan/', views.ScanView.as_view(), name='scan'), path('result/', views.SearchResultsView.as_view(), name='result'), ] websites/views: class IndexViews(generic.ListView): template_name … -
How to implemment Datatable server-sided smart searching
How do i use Datatable smart searching on a server-sided table. I'm using a server-sided Datatable table on my website with ~3500 entries, it loaded very slowly on mobile devices so i went server-sided processing on the table. Once i got the table to be server-sided using django-rest-framework i lost the datatable ability to smart search. I already did a search on datatable's forums but with no luck at all. JS code: <script> $(document).ready(function() { var table = $('#bibs').DataTable({ "serverSide": true, "ajax": "/api/livros/?format=datatables", "columnDefs": [ { "targets": [0,1,2,3,4,5], // "visible": false, "searchable": true, "orderable": true, } ], "columns": [ { "className": 'details-control', "orderable": false, "data": null, "defaultContent": '', "render": function () { return '<i class="fa fa-plus-square" aria-hidden="true"></i>'; }, width:"25px" }, {"data": "autor"}, {"data": "ano"}, {"data": "titulo"}, {"data": "referencia"}, {"data": "tema"}, {"data": "tipo"}, ], "dom":'<"toolbar">Brtip', }); </script> -
Django: generate pdf file from a formset view
I have a model formset where the user input input information. I am trying to make possible for the user to download a pdf file where the data inputed in being rendered. Here is what my formset view look like: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Date','Quantity', 'NetAmount', 'customer_name')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #blank_form = formset.empty_form if formset.is_valid(): request.session['sale'] = request.POST['sale'] for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/dash2.html') #else: #form = form(queryset= historical_recent_data.objects.none()) return render(request, 'new_sale.html', {'formset':formset}) and here is what my pdf_generator view looks like: def get_pdf_invoice(request): pdf = render_to_pdf('pdf/invoice_generator.html', request.session.get('sale')) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Melt_Invoice_{}.pdf".format(request.session.get('sale').get('customer_name')) content = "inline; filename={}".format(filename) content = "attachment; filename={}".format(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") and here is what i try to render as template with the pdf format: {% load static %} <!DOCTYPE html> <html> <head> <style> table { width:100%; } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: … -
Best way to integrate OpenId connect / (Keycloak) with Django and Django Rest framework
I'm looking for advice on the best way to integrate Django / Django Rest Framework with OpenId connect (we're using Keycloak but I think using the protocol is probably more flexible). There seems to be several option out there, but it would be good to have something that works as seamlessly as possible with Django and DRF – so session and API authentication working like the baked in Django version, and ideally access to external logon screens if using admin/DRF API endpoint. What is straightforward to set up and well supported? What I will ultimately be doing is trying to change an existing Django/React application, but for the purposes of this discussion let's assume it's a basic application something like the ones set up in the Django tutorial and Django Rest framework quickstart (https://docs.djangoproject.com/en/3.1/intro/tutorial01/ to tutorial01 and https://www.django-rest-framework.org/tutorial/quickstart/). I hope that's enough as I fairly new to this – I can create some sort of simple application in Github if this isn't a clear enough basis for a discussion. Any help would be much appreciated. Even better if you have an example (!). -
Customizing unit choices in a django-measurement form
I am quite new to Django and looking for a package that helps handling units in a Django app. Django-measurements seemed like a good starting point for me and I tried to modify the units displayed in the dropdown of a form as shown in the documentation: # my_app/forms.py from measurement.measures import Volume from django_measurement.models import MeasurementField class BeerForm(forms.Form): volume = MeasurementField( measurement=Volume, unit_choices=(("l","l"), ("oz","oz")), ) However when playing with this form in the django shell, it seems there are no fields: from my_app.forms import BeerForm b = BeerForm() b.fields >> {} b.as_table() >> '' Am I missing something here? Any advice welcome, thanks! django = "~=3.1.0" django-measurement = "==3.2.3" python_version = "3.8" -
Django: Trying to render and update a second formset within a view
I have one view, let's call it UpdateFruit. That view renders a formset which allows one to update a specific piece of fruits attributes. In the same view, there is a button to open a modal within which the piece of fruit has a list of fruit Observations that iterates out as a list of observations and can theoretically be added to via a form. I have inherited code that built the observations form using Django formsets and I want to be able to make a POST to the view to update the database. I have never used django forms before, and I'm trying to understand how I can make this post without ajax and differentiate it from the post to the UpdateFruit view that already exists from the other formset. To start, this is how I intend to post the form... <form id="form-container" action="{% url 'update-fruit' fruit.id %}" method="POST"> How do I post it to a specific method other than post? Can I do this something akin to: path('update-fruit/<pk>', views.UpdateFruit.as_view(), name='update-fruit'), -
Django app with potentially very long task run-time
I have a Django app which lets the user execute (potentially very) time consuming computations. This is not an issue per se as the user is aware of the long runtime. How can I have the user execute tasks and then log out (or terminate the web app) while keeping the task running on the server? i.e. The Django app should execute regardless of whether the website is still open or the user is still logged on. Full disclosure, I am a beginner in web dev so my question may require refinement. -
Create form to update user info and its extended fields - DJANGO
I'm working on a django project. I extended the User model with extra fields by implementing this other model: class Profilo(models.Model): TYPE_CHOICES = ( ('marketing', 'Marketing'), ('web', 'Web'), ('contabilita', 'Contabilita'), ) ROLE_CHOICES = ( ('lavoratore', 'Lavoratore'), ('responsabile', 'Responsabile'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) type = models.CharField(max_length=50, choices=TYPE_CHOICES, null=False, default=None) role1 = models.CharField(max_length=50, choices=ROLE_CHOICES, null=False, default=None) role2 = models.CharField(max_length=50, choices=ROLE_CHOICES, blank=True, default=None) profile_pic = models.ImageField(upload_to='media/immagini_profilo', blank=True) color = ColorField() def __str__(self): return self.user.username I want to create a view (NOT in the admin panel) where the user can modify the following information: username, first_name, last_name, email, profile_pic, color. So I implemented this form in the forms.py: from django import forms from .models import Profilo from colorfield.widgets import ColorWidget class ProfiloForm(forms.ModelForm): class Meta: model = Profilo fields = ('username','first_name','last_name','email','profile_pic', 'color',) 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'}), 'profile_pic': forms.FileField(), 'color': ColorWidget(), } In views.py: class ModificaProfiloUtente(UpdateView): model = Profilo template_name = 'modifica-profilo-utente.html' form_class = ProfiloForm success_url = reverse_lazy('tutti-progetti-view') But i get this error: raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (first_name, email, username, last_name) specified for Profilo So i tried several thigs: profilo__user__username (and so for the other fields as well) user__username user.username buti still get …