Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access editing profile only by profile owner using UserPassesTestMixin showing error?
i have managed to create profile pages for each user and every user should edit their own profile. in model, i have used AbstractUser model. and for the editing access i have imported UserPassesTestMixin. here is my models.py: class Profile(AbstractUser): name=models.CharField(max_length=30, blank=True) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) here is my views.py: class ProfileDetailView(DetailView): template_name='profile.html' model=Profile def get_user_profile(self,pk): return get_object_or_404(Profile,pk=pk) class ProfileEditView(LoginRequiredMixin,UserPassesTestMixin,UpdateView): model=Profile template_name='profile_edit.html' fields=['name','bio','birthdate','location','gender',] login_url='login' success_url = reverse_lazy('home') def get_user_profile_edit(self,pk): return get_object_or_404(Profile,pk=pk) def test_func(self): obj = self.get_object() return obj.username == self.request.user the problem is when the logged in user wants to edit it's profile it is showing 403 forbidden. no user can edit their profile. in test function what should is use to fix that? -
no data found issue while running selenium on DJango
I have made a crawler which extracts data from a website I have used selenium in headless mode with chrome webdrivers. I am trying to integrate the same with the Django as an api, it is not fetching the data returning NoDatafound exception. But the same code is woking fine on my jupyter notebook. I have tried with both selenium and splinter both are not working. -
Django -> Registering New User -> Check if the user is already authenticated by email and username
I have the following code in my register_view function. When I register a new user it updates in the database, but I want to check whether a user has already been authenticated by email or user. I have tried request.user.is_authenticated but this always returns true, and the request body is always saving when I fire a new POST call. @csrf_exempt def register_view(request): if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) return JsonResponse(f'User {email} : {username} has been registered.', status=200, safe=False) else: form = RegistrationForm() return JsonResponse('You are missing some fields.', status=422, safe=False) --> User Model class User(AbstractBaseUser): firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=30) email = models.EmailField(verbose_name="email address", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'firstname', 'lastname'] class Meta: db_table = "users" def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True --> Registration Form class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=255, help_text="Email address required.") firstname = forms.CharField(max_length=30, help_text="First name required.") lastname = … -
How do I make POST form-data request with Alamofire? - Swift
I am trying to imitate this in Xcode using Alamofire: Here is what I created on Swift/Xcode according to Alamofire docs : let url = "http://127.0.0.1:8000/" /* your API url */ AF.upload(multipartFormData: { multipartFormData in multipartFormData.append(Data("one".utf8), withName: "file") }, to: url, method: .post) .responseJSON { response in debugPrint(response) } The response I get from the server is. "Number of Files: " = 0; Meaning the server is not receiving the file, however it works when I do it from Postman, so what am I missing? Also here is my django server which is taking the request, if this is needed: @csrf_exempt def test(request): length = 0 try: length = len(request.FILES) except Exception as e: print(e) return JsonResponse({'Number of Files: ': length}) -
Filtering between two models to get aggregates in Django
I have these two models Transactions and bank statement. I am trying to reconcile transactions that have been paid based on the bank statement entry. The assumption is that from the BankTransaction model Naration we can be linked to invoices from transaction model. How do I filter the BankTransaction based on the transaction model to generate the following results Total invoice paid by each customer (credited to the bank) total amount due by each customer class Transactions(models.Model): customer_name= models.ForiegnKey(Customer, on_delete= Model.CASCADE) ..... Invoice_Number= models.CharField(max_length=20) Invoice_date = models.DateField() Date_Due = models.DateField() Invoice_status =models.CharField(max_length=20) def __str__(self): return 'Invoice Number: {}'.format(self.Invoice_Number) def save(self,*args,**kwargs): .... if self.Invoice_date < self.Date_Due: self.Invoice_status = 'Not Due' else: self.Invoice_status = 'Due' super().save(*args, **kwargs) class BankTransaction(models.Model): Bank_name= models.CharField(max_length= 50) .... Narration= models.CharField(max_length=100, blank=False, null=False)// this contains details of the invoice def __str__(self): return self.Bank_name -
How do I use the Google Calendars API on my Django project hosted on Heroku?
In my project, a user can input details into a form, and the information is used to create an event with Google calendars. This works fine locally, however when I put the site up on Heroku, it does not work (according to the logs, it tries to get the server to open a window and sign in/authenticate). However, I'm still struggling to figure out how to get the API working on a server-side application. I'm already using oauth to allow users to sign in with their Google accounts, so I'm thinking that I need to use those same credentials. Here is some of the code from my views.py that is used to create the calendar event: SCOPES = ['https://www.googleapis.com/auth/calendar'] flow = InstalledAppFlow.from_client_secrets_file(os.path.dirname(os.path.realpath(__file__)) + '/credentials.json', SCOPES) service = build('calendar', 'v3', credentials=creds) event = { ... } service.events().insert(calendarId='primary', body=event).execute() service.close() Where credentials.json is the file I got from the Python Quickstart tutorial. as I understand it I need to use the json from the oauth settings used for Google login, but I'm not really sure where to go from there. I found this tutorial from Google for server-side apps, but the code seems a little verbose and I'm feeling like I shouldn't … -
Django - How to change form field based on database variable?
I'm making a survey app. There's a question class that specifies what type of input it would like (text, dropdown, checkbox, radio). My questions is: How can I change a form field from a text field to a dropdown, or a series of checkboxes, or radio buttons etc. programatically based on the variable in the question class? I currently have this code for my form_class for answers to the questions: forms.py class AnswerCreationForm(forms.ModelForm): answer = forms.CharField(widget=forms.TextInput(attrs={'class':'text_input', 'placeholder': 'enter your answer here...'})) class Meta: model = Answer fields = ('answer',) This works fine when the question expects a TEXT response, but I'm wondering if theres a way for me to change "answer" to a "choiceField" when the question is looking for a multi choice repsonse with the relevant choices programatically? This is my code for my question model: models.py class Question(TimeStampMixin): class AnswerType(models.TextChoices): TEXT = 'TEXT', "Text" DROPDOWN = 'DROPDOWN', "Drop Down" CHECKBOX = 'CHECKBOX', "Checkbox" RADIO = 'RADIO', "Radio Buttons" survey = models.ForeignKey('surveys.Survey', db_index=True, related_name="questions", on_delete=models.PROTECT) question = models.TextField() order = models.IntegerField() answer_type = models.CharField(max_length=8, choices=AnswerType.choices) def __str__(self): return self.question and when answer_type isn't TEXT, the choices for the answer are stored in this class: models.py (continued) class AnswerChoice(TimeStampMixin): question … -
Django application: the directory_name to which an image has to be uploaded, should be auto populated
I want to upload images to the django server using my application and the folder/directory_name to which the image has to be uploaded, should be auto populated using the foreignkey relationship that my models are sharing My models classes are as follows, class Event(models.Model): event_name = models.CharField(max_length=200) event_desc = models.CharField(max_length=5000) def __str__(self): return self.event_name class Image(models.Model): event_id = models.ForeignKey(Event, on_delete=models.CASCADE) image_name = models.CharField(max_length=200) image = models.ImageField(upload_to='events/{}'.format("something")) def __str__(self): return self.image_name the something in the models.ImageField function has to be replaced by the event_name dynamically and the value for event_name should be populated dynamically. -
views.edit didn't return an HttpResponse object. It returned None instead
I'm trying to edit items on a form on a page called 'website/edit1,2,3,4,...' When I click 'edit' after editing the form items, I get the error above. None of the errors on the site resembles a solution. The tutorial I was following (and now trying to add my own edit function) says to import HttpResponseRedirect and not HttpResponse as in the solutions on S/O. Anyways, here's the views.py file from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages from django.http import HttpResponseRedirect def home(request): all_items = List.objects.all return render(request, 'home.html', {'all_items': all_items}) def about(request): return render(request, 'about.html', {}) def edit(request, item_id): if request.method == 'POST': item = List.objects.get(pk=item_id) form = ListForm(request.POST or None, instance=item) if form.is_valid(): form.save() messages.success(request, ('Item Had Been Edited')) return redirect('home') else: item = List.objects.get(pk=item_id) return render(request, 'edit.html', {'item': item}) def delete(request, item_id): item = List.objects.get(pk=item_id) item.delete() return redirect('home') Here's the urls.py file from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about', views.about, name='about'), path('delete/<item_id>', views.delete, name='delete'), path('edit/<item_id>', views.edit, name='edit') ] .. . and the forms.py file from django import forms from .models import List class ListForm(forms.ModelForm): class Meta: model = List fields … -
Code optimization in a Django when populating field based by a foreign key
I'm searching for some advice on the optimization problem. In this case, I'll use a simple example, I've got these classes: class Genere(models.Model): genere_name = models.CharField(max_length=100) short = models.CharField(max_length=2) class Book(models.Model): name = models.CharField(max_length=100) genere_name = models.ForeignKey(Genere, on_delete=models.SET_NULL, null=True) book_system_id = models.CharField(max_length=100) My field book_system_id describe id number based on genre, for example (in a simplified way): id|name |genere_name|book_system_id 1|Dune |sci-fi |sf001 2|Invisible Man |novel |n001 3|Kindred |sci-fi |sf002 4|Neuromancer |sci-fi |sf003 5|IThings Fall Apart|novel |n002 Now, to populate the field book_system_id in views I use queryset to count elements based by genre, and I'm updating this object (genere_id I'm passing in URL to view function when I create new book object), bellow this is the code snippet: book.save() book.book_system_id = genere.short + str(Book.objects.filter(book_system_id=genere_id).count()) book.save() I'm knowing that this is probably the worst way to do this. That will be really slow when I have a big amount of objects stored in this table. I am wondering how to improvise to do this in the best way; I can add an extra field to store number current order, and when a new object is saved we can get the last number from DB. The second idea was that I can … -
Django Rest Framework - Write for Relational nested Serializers
I am quite new DRF so I am sorry beforehand for any mistake. For example, I have Post model which has Author as foreign key to NewUser model. When I list posts, instead of getting primary key of author, I wanted to get nested object with author details and that is why I created my serializer like this. class PostAuthorSerializer(serializers.ModelSerializer): class Meta: model = NewUser fields = ["id", "email", "user_name"] class PostSerializer(serializers.ModelSerializer): author = PostAuthorSerializer() class Meta: model = Post read_only_fields = ("slug",) fields = ( "id", "title", "author", "excerpt", "content", "status", "slug", ) lookup_field = "slug" However, now I don`t how to /POST a post back. I searched for 2 days but cannot find a proper guide for understand how to do. My main goal is to learn/understand rather than solve the issue so a little bit explanation also would be great! I was really motivated to learn DRF, but I think it lacks a detailed documentation and examples in internet or at least I could not find answer to my question. So, I want to learn 2 ways of posting: Representation is staying this way but I still /POST a post with showing "author":id Representation is staying this … -
Django global/thread objects
Often in Django I want to create and configure some object at startup, and have it available everywhere. For example a third-party API client. So when django starts I want to do this: from some.thirdparty import ThirdPartyClient from django.conf import settings ... my_thirdparty_client = ThirdPartyClient(configstring=settings.SOME_CONFIG_ITEM) And then in a view somewhere I want to do this: from somewhere import my_thirdparty_client def whatever(request): my_thirdparty_client.do_stuff() my_thirdparty_client.do_even_more_stuff() Obviously I understand that I can instantiate the client at the start of the view, but if initalizing the instance is expensive I don't want to do it on every request. What is the idiomatic Django way of creating these kinds of objects that I want to share between views? -
Exception has occurred: ImportError using Django on lines 13 and 23
When I try to rune the [ python manage.py runserver ] to run the server I get an "Exception has occurred: ImportError" and then it will states "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "/Users/tarikzukic/Desktop/DJwebsite/manage.py", line 13, in main raise ImportError( File "/Users/tarikzukic/Desktop/DJwebsite/manage.py", line 22, in main()" Down bellow is the code snippet to be examined. #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DJwebsite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
__str__ returned non-string (type datetime.date)
In Django I have 2 models: in inventory/models.py: class Transaction(models.Model): date = models.DateField() product = models.ForeignKey( Product, on_delete=models.PROTECT) type = models.ForeignKey(TransactionType, on_delete=models.PROTECT) quantity = models.IntegerField() location = models.ForeignKey(Location, on_delete=models.PROTECT) note = models.TextField(null=True, blank=True) def __str__(self) -> str: return f'{self.date}, {self.product.name}, {self.type.name}' And it's working normal. On the other hand. This model in sales/models.py: class Sale(models.Model): date = models.DateField() sale_id = models.IntegerField() sku = models.CharField(max_length=10) product = models.CharField(max_length=100) quantity = models.IntegerField() price = models.FloatField() channel = models.CharField(max_length=100) nooks_payout_schedule = models.ForeignKey( NooksPayoutSchedule, on_delete=models.RESTRICT, blank=True, null=True) def __str__(self) -> str: return f'{self.date}, {self.product}' give me error: __str__ returned non-string (type datetime.date) when trying to see it in admin dashboard. What Ive tried Ive tried to use str(self.date), but it's same error. I can't see the difference between those 2 models yet they are working differently. Do you know why? Full trace: Environment: Request Method: GET Request URL: http://localhost:8000/admin/sales/sale/160/change/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'sales', 'inventory', 'graphene_django', 'corsheaders', 'django_pivot', 'drf_spectacular', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/tomo/anaconda3/envs/vdora/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 __str__ returned non-string (type datetime.date) 9 : {% for field in line %} 10 … -
Zero-length delimiter error using python psycopg2 to parse a gzip and insert it into a postgres database
I am attempting to load the contents of a gzip file I created into my postgres database using psycopg2. When I run the script, I get the following error: psycopg2.errors.SyntaxError: zero-length delimited identifier at or near """" (photo of traceback here) I understand that the error is most likely due to the single quotes around the empty string value of 'example', but I don't know the reason this would cause an issue. df = pandas.read_csv(cip_location, header=0, encoding='ISO-8859-1', dtype=str) number_loaded_rows += len(df.index) for index, row in df.iterrows(): row = row.squeeze() cip_code = row['CIPCode'] cip_code = cip_code[cip_code.find('"') + 1:cip_code.rfind('"')] if cip_code.startswith('0'): cip_code = cip_code[1:] cip_title = row['CIPTitle'] cip_def = row['CIPDefinition'] exam_string = row['Examples'] exam_string = exam_string.replace('Examples:', '').replace(' - ', '').replace(' -', '') examples = exam_string cip_codes[cip_code] = { 'code': cip_code, 'title': cip_title, 'definition': cip_def, 'examples': examples } with gzip.GzipFile(ending_location, 'r') as f: bytes = f.read() string = bytes.decode('utf-8') loaded_unis = jsonpickle.decode(string) print('Finished loading in ' + str(time.time() - start_load)) import psycopg2 cnx = psycopg2.connect('host=localhost dbname=postgres user=postgres password=password') count = 0 cursor = cnx.cursor() for d in cip_codes.values(): print('Inserted: %s' % count) print('Trying to insert (%s, "%s", "%s", "%s");' % (d['code'], d['title'], d['definition'], d['examples'])) cursor.execute('CALL InsertCIP(%s, "%s", "%s", "%s");' % (str(d['code']), d['title'].replace('"', "'"), … -
Django custom admin messages
I would like to know how to change the link that appears in the Django admin panel success message and redirect it somewhere else The underlined red part is where the link appears -
Best option for Django Logging accross multiple processes
What is the best option for Django logging if I have info.log and error.log which are being shared across multiple processes? One option would be Multiprocessing, another option would be SocketHandler. Here is the link: https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes -
Setting a field in django admin that is unchangeable
I'm currently developing a Django app that is used by multiple gas stations. I have a station model with every station having it's own object. Each station will have its own account and can only modify values for their own station. I am making a report to be submitted via Django admin, but I want to set the "station" field to their station name, where they can't view other station names nor change the selection to the other stations. In the admin.py, this is what I have (the report is called Shipment), the field in question is called station. class ShipmentAdmin(admin.ModelAdmin): #readonly_fields = ['station'] <- I thought this would work but it removes the value I set if user = manager def get_form(self, request, obj=None, **kwargs): form = super(ShipmentAdmin, self).get_form(request, obj, **kwargs) if str(request.user) == 'manager': form.base_fields['station'].initial = 'Texaco' else: form.base_fields['station'].initial = 'Exxon' Please let me know if you guys know how to fix this. Basically if the user is manager, set the station value to "Texaco", else set it to "Exxon", and don't allow that field to be changed. Thanks! -
Django grouping and filter, ordering
I am creating small project for our cinema web I have models class Movies(models.Model): name = models.CharField(max_length=100) ... class Projections(models.Model): movie = models.ForeignKey(Movies, on_delete=models.DELETE) startshow = models.DateTimeField() Each Movies have several Projections with different startshow. How can I get Movies grouped by name and ordered by first startshow with all projections for that movie ordered by startshow The list is looking like this: Trools: World Tour 2020-11-10 17:00 2020-11-11 17:00 2020-11-12 17:00 Frozen 2020-11-10 19:00 2020-11-11 19:00 2020-11-12 19:00 Tennet 2020-11-10 21:00 2020-11-11 21:00 2020-11-12 21:00 Please help -
django user defined fields and answer model
Similar to this: User defined fields model in django I am creating a COVID Prescreening system for a school project. Event creators will be able to create forms, which consist of basic questions such as temperature, contact with covid in the last 14 days, etc. as well as provide custom questions for the attendee to answer which I cannot predict. For example, the event creator could ask 2 questions: How are you feeling today? Have you been to a party in the last week? And every attendee for that event would have to fill out these 2 questions in addition to the standard questions. The model for this is: class Event(models.Model): ''' model for an event ''' creator = models.ForeignKey("Account", on_delete=models.CASCADE) title = models.CharField(max_length=200, help_text="Enter a title for this event") start_time = models.DateTimeField() uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) custom_questions = models.ManyToManyField(CustomQuestion) def __str__(self): return f'{self.title} {self.uuid}' Each custom question is essentially a key/value model: class CustomQuestion(models.Model): question = models.CharField(max_length=200) response = models.CharField(max_length=200, blank=True) The user will fill out the COVID Form, which will create an object as such: class CovidScreenData(models.Model): custom_responses = models.ManyToManyField(CustomQuestion) temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6) contact_with_covid = models.BooleanField(default=False) This data is embedded in the larger response, which ties … -
Problems trying to save data to a set of online forms
I am developing an application which saves the projects that the administrator assign to the developers, for that I have a project model and a task model, because a project can have multiple tasks, in order to save multiple tasks in a project what I am doing is using a inline formset, but I am having a problem and it is that the data is not saved correctly. This is my view. class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = 'users:login' template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = ProjectFormSet(self.request.POST) else: data['formset'] = ProjectFormSet() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super().form_valid(form) This is my inline formset: ProjectFormSet = inlineformset_factory( Project, Task, form=TaskForm, fields=['type_task', 'task'], extra=1, can_delete=True, ) This is my template,To use the inline formset I was investigating and they told me that the easiest way is with a jquery library to carry out this process: {% extends "base.html" %} {% load static %} {% block content %} <div class="container"> <div class="card"> <div class="card-content"> <h2>Agregar Proyecto</h2> <div class="col-md-4"> <form method="post"> {% csrf_token %} <div class="input-field … -
Loading Template in Admin Form for Custom Fields
I learned that I can add a custom button in my Admin form by adding it to fields = ["connect"] readonly_fields = ('connect',) def connect(self, obj): return format_html("<button></button>") connect.allow_tags=True connect.short_description = '' However, the html I want to add to the connect is getting out of control. I was wondering if there's a proper (Django-nic) way to move that to a template and load and return the content of the template in the connect function. I can think of reading the content of the template file (open('file.html', 'r')) to read the content, however, I am looking for a suggestion that aligns Django standards (if any). P.S. I also tried creating a view for getting the HTML content of the connect file, but that for some reason doesn't seem to work and feels unnatural to do. -
Can't correctly receive data in Django from Ajax
I wand to receive array data in Django view from jquery/Ajax request but in some reason I cannot correctly do it. This is the piece of js code: var arr = [1, 2]; $.ajax({ type: 'POST', url: '/go/', data: {arr: arr}, success: function (data) { console.log('Success!'); }, }); And this is from Django view: def go(request): if request.method == 'POST': arr = request.POST['arr'] It gives me KeyError: 'arr' If I do print(request.POST) in Django it prints it like this: <QueryDict: {'arr[]': ['1', '2']}>. Some square brackets appear after 'arr' key. Then if I do arr = request.POST['arr[]'] using the key with square brackets it assings arr value 2, so only the last value of the array. Can someone please explain to me why this is happening? -
can i do process with form django python
there is a input and select with options in form tag. i want to get input value and option that entered. and i will do somethings on backend with python that value and option than i will return a result to website. but i dont use to forms.py. how can i do? is it possible? <form action="" method="post"> {% csrf_token %} <input type="text" name="getinputValue"> <select name=""> <option value="1"></option> <option value="2"></option> <option value="3"></option> </select> <button type=""class=""></button> <p>{{result}}</p> </form> -
Why this django formset has stopped saving the content all of a sudden?
I had this view that rendered a form and a formset in the same template: class LearnerUpdateView(LearnerProfileMixin, UpdateView): model = User form_class = UserForm formset_class = LearnerFormSet template_name = "formset_edit_learner.html" success_url = reverse_lazy('pages:home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) learner = User.objects.get(learner=self.request.user.learner) formset = LearnerFormSet(instance=learner) context["learner_formset"] = formset return context def get_object(self, queryset=None): user = self.request.user return user def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) user = User.objects.get(learner=self.get_object().learner) formsets = LearnerFormSet(self.request.POST, request.FILES, instance=user) if form.is_valid(): for fs in formsets: if fs.is_valid(): # Messages test start messages.success(request, "Profile updated successfully!") # Messages test end fs.save() else: messages.error(request, "It didn't save!") return self.form_valid(form) return self.form_invalid(form) Then i wanted to make it prettier and i added the select2 multicheckbox widget and the django-bootstrap-datepicker-plus Nothing has changed elsewhere, yet when i submit the post it only saves the data relative to User and not to Learner (which relies on the formset) According to the messages, the formset data is not validated, I don't understand why since i didn't touch the substance at all but just the appearance. Being a beginner im probably missing something big, I thank in advance whoever can help me find out the problem. …