Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
We want to create the Live Streaming Video
I want to create the Live Video Streaming Video in python django for website. if any one have any idea please share you response with me. -
Pycharm Django Project using Vagrant Server: Error Package requirement is not satisfies
I am trying to start a Django Project using Vagrant and PyCharm Professional edition. I am using a Windows computer and my Vagrant file looks like this https://gist.github.com/LondonAppDev/d990ab5354673582c35df1ee277d6c24 Below is my project just in case (not really required to answer this question ) https://github.com/samirtendulkar/profiles-rest-api Now through Pycharm Terminal I added vagrant init vagrant up vagrant ssh vagrant@ubuntu-xenial:/$ mkvirtualenv profiles_app_venv --python=python3 (profiles_app_venv) vagrant@ubuntu-xenial:/$ pip install django==1.11 (profiles_app_venv) vagrant@ubuntu-xenial:/$ pip install djangorestframework==3.6.2 Then I added a src folder in my root project and started making another app Then I created a requirements.txt (name_of_env) vagrant@ubuntu-xenial:/vagrant/$ pip freeze > requirements.txt See Image below. I know that this is because my project in running on my Vagrant server and my Pycharm is running on my host server. But I am losing out on all of Pycharm's best features. How can I override this -
Creating ranges of values form single numbers in django-filters from using 'method='
I am trying to create a value range filter in my application using django-filters. In my database are invidual vields with age (that were created using models.IntegerField). I want to add now check box like this below: Everything is almost ready but I do not know how to reach the database. I read documentation about 'Customize filtering with Filter.method' and how use RangeFilter but I still do not know how to create the right condition. How can I do this in my stytuation (how create condition for my 'requirements=?') which returns a value, for example, between 20-30 ? We have a view in the documentation: f = F({'price_min': '5', 'price_max': '15'}, queryset=qs) What is 'f'? where in this situation the condition reaching the database? My filters.py from .models import Promoters import django_filters class PromotersFilter(django_filters.FilterSet): CHOICES = ( ('age_option1', '0-20'), ('age_option2', '21-30'), ('age_option3', '31-40'), ('age_option4', '41-50'), ('age_option5', '50+'), ) age_list = django_filters.ChoiceFilter(label='Age list', choices=CHOICES, method='filter_by_order') class Meta: model = Promoters fields = ['age', 'profession', 'sex', 'city'] def filter_by_order(self, queryset, name, value): requirements = **??** return queryset.order_by(requirements) -
Django 2: How to add choices to ChoiceField dynamically in a formset, based on the instance, and still validate
I have a form in a formset which I want to be able to dynamically add choices to a choicefield. This is possible, and I have done this either in my init(self): method, or in the view. However it does not appear in my cleaned_data dictionary, and the choicefield does not get validated. How can I achieve this: forms.py: BASE_CHOICES = ( ('1', 'choice 1'), ('2', 'choice 2'), ) class CRVForm(forms.ModelForm): class Meta: model = CRV fields = ('evidence', 'annotation', 'report',) report_annotation = forms.ChoiceField( choices=(BASE_CHOICES), required=True, ) report = forms.ChoiceField( choices=( (None, '-'), ('report', 'Report'), ('to_confirm', 'To confirm'), ) ) def __init__(self, *args, **kwargs): super(CRVForm, self).__init__(*args, **kwargs) obj = self.instance if obj.field: addn_choices = ((str(va_obj.field), str(va_obj.field)), ) else: addn_choices = () choices = addn_choices + self.fields['report_annotation'].choices self.fields['report_annotation'].choices = choices Views.py get(self, *args, **kwargs): self.crvform = CRVForm formset = modelformset_factory( CRV, form=self.crvform, formset=BaseCRVFormSet, extra=0, ) formset = formset(queryset=obj) * Have also tried this in views: * for form in formset: id = form['id'].value() obj = Model.objects.get(id=id) # if obj.field: # addn_choices = ((str(va_obj.field), str(va_obj.field)),) # # else: # addn_choices = () # # # # choices = addn_choices + form.fields['report_annotation'].choices # form.fields['report_annotation'].choices = choices However when I do either of these, … -
Flag as Deleted (Django) (flag in all tables) or (in one)
I am working on a project where there is a lot of use of foreign keys Table A has two or more than two foreign keys say(B and c) and B have two other foreign keys (D,E) similary C also have several foreign keys in DB I am using Django.and want a soft delete. Since when I use on cascade delete it will delete all the other records in the table linked to foreign keys. So what is the best way to deal with such things. What I did was tried to mimic cascading feature by making flag field in all table and as soon as record in D,E is deleted(or flag is set to False) , record in B also get flag=False and thus finally A should i Prefer this approach or do I have to set flag = False in one db and have to check each anf every time whetther tha flag is false or not for all the foreign keys linked to it. I think I didn't explain the problem well but I hope you get the idea what I was trying to say How I implemented former using recursive approach def deleteObject(a): print("deleting", a, a._meta.model) … -
Django - How can I override required on form fields?
I have a form from a model and fields must be filled depending on one dropdown, however I want a way to override the required of the forms depending on the field chosen. -
Django password_reset url and password_reset_confirm
accounts/urls.py password_reset_dict = { 'template_name': 'registration/reset_password.html', 'email_template_name': 'registration/password_reset_email.hmtl', 'html_email_template_name': 'registration/password_reset_email.html', 'subject_template_name': 'registration/password_reset_subject.txt', 'password_reset_form': EmailValidationOnForgotPassword, } and so... path('sifre-sifirla/', PasswordResetView.as_view(), password_reset_dict, name='password_reset'), re_path('sifre-sifirla/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/',PasswordResetConfirmView.as_view(), name='password_reset_confirm'), password_reset_email.html {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} returns url as: http://localhost:8000/uye/yeni-sifre/MTU/**set-password**/ The question is, how to change **set-password** to my native language? Thank you in advance. -
Django list_per_page for all models in admin
Good day! I'm trying to find the solution to add list_per_page as a global parameter for all models in admin. I found out, that ModelAdmin has this parameter through ChangeList object and it has default value 100. But what if I want to set it 20 and it will be true for all models? I mean, if I need to change list_per_page for current model in admin, I need to add: class CurrentModelAdmin(models.ModelAdmin): list_per_page = 20 ... Is there any way to redefine ChangeList object to rewrite default value? For example as a LIST_PER_PAGE = 20 in a settings.py And even better, how I can recieve it from frontend and work with that dynamicly? -
Django: Upload and process large file via admin
I upload text files containing data to the Django Admin daily. Each text file includes about 100,000 records that Django reads and writes to a database. However, uploading results in interrupting the server for all other requests. What could be a good strategy to place the processing to on a subthread which doesn't hinder other traffic? Perhaps any other strategy that is useful for server side processing of large files? -
How can I filter distinct values from one column in a Django queryset without PostgreSQL?
So I have a database tracking certain Wikipedia edits. Under certain, desired, circumstances, the database may save the same edit multiple times to the db, with one column having different values. I want to be able to make a queryset that removes duplicate rows based on the rc_id column, which is the same for duplicate edits. I don't care which of the duplicate rows is discarded because I only need the non-unique information. If I were using a PostgreSQL database I could use the DISTINCT ON feature via queryset.objects.filter(field=filter).distinct('rc_id'). In MySQL, however, this feature is not available. Other SO questions on this topic have been answered by telling people to use .values_list('rc_id').distinct(), however I want the result to still be a queryset for further filtering, not a values list. How can I do this at the queryset level, or if necessary, with a raw SQL query? -
Debugging REST API request in Django REST Framework with PyCharm
I'm developing API Views with Django REST Framework. I'm using PyCharm Community edition. I set brakepoint on POST method inside class-based view: Then I run "debug views.py". I'm using Postman for API development. After sending request in Postman to post method inside the view, it won't stop on brakepoint. Although I get the response from server with 200 code and I can see new employee. How can I make this happen to stop on breakpoint. Where I'm wrong? -
Annotate query for calculate sum of 3rd level deep table value with Django ORM
I have 2 tables Class Billing(models.Model): id=models.AutoField(primary_key=True) ..... #Some more fields .... Class BillInfo(models.Model): id=models.AutoField(primary_key=True) billing=models.ForeignKey(Billing) testId=models.ForeignKey(AllTests) costOfTest=models.IntegerField(default=0) concession=models.IntegerField(default=0) Here BillInfo is verticle table i.e one Billing has multiple BillInfo. Here I want to calculate the Sum(costOfTest - concession) for a single Billing. Can I achieve this using single query? Need help, Thanks in advance. -
Apache and mod_wsgi
I am working with apache 2.4.27, python 3.7 I need to install mod_wsgi. I tried to install it via pip install mod_wsgi it gives me this error: running build_ext building 'mod_wsgi.server.mod_wsgi' extension creating build\temp.win-amd64-3.6 creating build\temp.win-amd64-3.6\Release creating build\temp.win-amd64-3.6\Release\src creating build\temp.win-amd64-3.6\Release\src\server cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\Apache24/include "-Ic:\program files (x86)\microsoft visual studio\shared\python36_64\include" "-Ic:\program files (x86)\microsoft visual studio\shared\python36_64\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17134.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" /Tcsrc/server\mod_wsgi.c /Fobuild\temp.win-amd64-3.6\Release\src/server\mod_wsgi.obj error: command 'cl.exe' failed: No such file or directory -
Misconfigured custom HTTP error templates in Django project (404,500)
I am in Django HTTP error codes hell. Would be great if an expert can help me out of my misconfiguration. My Django project runs with nginx as a reverse proxy coupled to a gunicorn application server. Requirement: I want a custom Page not found template to render (i.e. 404) when a url pattern is entered that doesn't exist in my urls.py. Sounds simple enough, and is well documented. I have already gone ahead and implemented this. The Problem: Assume example.com is my live project. 1) If I try to access https://example.com/asdfasdf (i.e. unmatched, random gibberish) on my production server, it displays the 500 template instead of 404. 2) Next, if I try to curl the said url pattern via curl -I https://example.com/asdfasdf/, I see 200 OK instead of 404 or 500. Wth? 3) Moreover, if I try the same behavior with Debug = True on localhost, 404 is returned correctly (both template and HTTP error code are in consonance). These 3 behaviors are quite perplexing. My configuration: I created error_views.py and inserted it in the folder where I keep my regular views.py. This error file contains: from django.shortcuts import render def server_error(request): return render(request, '500.html') def not_found(request): return render(request, … -
django static file isn't recognized
I'm on Django version 2.0 and, my static file insn't printing. The thing is: In my static repertory wich is located the admin static files too, if I call http://PROJECT/admin/css/some.css this works but I'v put a test.css file to test the repertory and this file isn't call; for exemple with my new test file: http://PROJECT/admin/css/test.css this new file gets a 404... Everything is ok with my settings.py conf file so where could this problem comes to ? -
Error in DetailView while trying to Post form
I'm running out of ideas, and tried with different solutions. I'm building for my thesis a Job Offering Page with Django 1.9. So far I built most of it, but I'm struggling trying to build the method to apply to the job. I've ListView for the offers, Offer Page for the DetailView, but I've added a form in this one, and am getting Error 405, even when the url is redirecting to different page. Method Not Allowed (POST): /anuncios/display_anuncio/2/ [22/Oct/2018 09:59:00] "POST /anuncios/display_anuncio/2/ HTTP/1.1" 405 0 In the urls.py: urlpatterns = [ url(r'^$', crear_anuncio, name="crear_anuncio"), url(r'^postulante_lista_anuncio/', AnuncioPostulanteList.as_view(), name="postulante_lista_anuncio"), url(r'^postular/', postular, name='postular'),] In the views.py class AnuncioPostulanteList(ListView): model = Anuncio template_name = 'anuncios/postulante_lista_anuncio.html' class DetailAnuncio(DetailView): model = Anuncio template_name = 'anuncios/pagina_anuncio.html' success_url = reverse_lazy('anuncios:pagina_anuncio') def postular(request): if request.method == 'POST': form = PostularForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.fecha_postulacion = timezone.now() instance.id_usuario_postulante = request.request.user.pk instance.id_anuncio = request.id_anuncio instance.fecha_cambio_postulacion = timezone.now() instance.save() return redirect('anuncios:postulante_lista_anuncio') else: form = PostularForm() return render(request, 'anuncios/postulante_lista_anuncio.html', {'form': form}) In the forms.py (Just in Case) class PostularForm(forms.ModelForm): class Meta: model = models.Postulacion fields = [ 'id_postulacion', 'fecha_postulacion', 'id_usuario_postulante', 'id_anuncio', 'id_estado_postulacion', 'fecha_cambio_postulacion', ] And finally in the pagina_anuncio.html {% extends 'anuncios/base_anuncio_postulante.html' %} {% load staticfiles %} {% block content … -
django select dropdown value and save it in views.py
i am trying to save dropdown select value from javascript template in views.py and save the value in backend. i am new to django and ajax. thank you for your help. in products app model: class Sauce(models.Model): title = models.CharField(max_length=120) active = models.BooleanField(default=True) def __str__(self): return self.title class Meta: ordering = ('title',) in forms.py i have: from django import forms from .models import Sauce class SauceDropForm(forms.Form): saucedata = forms.ModelChoiceField(queryset=Sauce.objects.all(), empty_label=None) class Meta: model = Sauce fields = ('title',) in sauce.html template i have: <form class="form-sauce-ajax" method='POST' action="" onchange="getSelectedValue();">{% csrf_token %} <a href="javascript:getSelectedValue()">retrieve</a> {{ form.as_p }} <input type="submit" id="submit" name="submit" value="Submit"/> </form> <script type="text/javascript"> function getSelectedValue() { var selectedValue = document.getElementById("list").value; <!--alert(selectedValue)--> return selectedValue } <!--getSelectedValue();--> </script> How do i get selected sauce title and add it to the database in views.py -
Apache2 reverse proxy strips my custom header
For my REST API, I am trying to pass a custom header X-APP-ID through and apache2 reverse proxy to the application hosting the API, however, it seems like apache2 is stripping away the header. It doesn't arrive at the application. Why is that? Here is my apache2 config <VirtualHost *:443> ServerName $SERVER_NAME ServerAlias $SERVER_ALIASES # Make sure requests are rewritten to use https:// RewriteEngine on RewriteCond %{HTTP_HOST} !^$SERVER_ALIASES [NC] RewriteCond %{HTTP_HOST} !^$SERVER_NAME RewriteRule ^/?(.*) https://$SERVER_NAME/$1 [L,R,NE] SSLEngine on SSLOptions +StrictRequire <Directory /> Require all granted SSLRequireSSL </Directory> SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256 # Enable SSL (disabling weak/vulnerable protocols) SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLHonorCipherOrder On SSLCertificateFile /etc/letsencrypt/live/$SERVER_NAME/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/$SERVER_NAME/privkey.pem # Logging LogLevel warn CustomLog /var/log/apache2/access.log combined # Static files Alias /static/ [redacted] Alias favicon.ico [redacted] # If the URL mentions favicon, but is not acutally pointing to a file # location, rewrite the url to point to the favicon file RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f RewriteRule .*favicon\.ico$ [redacted] [L] ProxyPass /static/ ! ProxyPass /media/ ! ProxyPass / http://localhost:8000/ ProxyPassReverse / http://localhost:8000/ </VirtualHost> <VirtualHost *:80> # Rewrite request to use SSL RewriteEngine on ReWriteCond %{SERVER_PORT} !^443$ RewriteCond %{REQUEST_URI} !/.well-known RewriteRule ^/(.*) https://$SERVER_NAME/$1 [NC,R,L] ServerName $SERVER_NAME ServerAlias $SERVER_ALIASES # Logging ErrorLog /var/log/apache2/error.log LogLevel warn CustomLog /var/log/apache2/access.log … -
Comparing SQL database with Django schema using sqldiff
I am using sqldiff for comparing my django and SQL database and it seem to be giving ALTER TABLE inventory_country MODIFY id integer AUTO_INCREMENT; for all the models present in an app. Running the above command on the SQL database results in 0 modifications- because this is already the state of the table. Why is sqldiff telling me to modify id for all the models? (this is an automatic 'id' primary key that django inserts) -
Can't get javascript to work on my website; Django Polls
For an assessment at UNI i need to make a webpage list the contents of an object dynamically. Sorry I am very new to this and need to complete this assessment. The code below is what I need to change to get the website to display the contents of an object below the link when it is clicked, as of now, when i click the link nothing happens. I have probably explained this very wrong. The assessment is based on the Django webpage tutorials. Please ask me to explain further if required, as I don't really understand how to explain my issue. The attached image is what the outcome needs to be.. {%load staticfiles%} <script src="(% static "polls/jquery-3.3.1.js" %)"></script> {% if latest_question_list %} <ul id="question-list"> {% for question in latest_question_list %} <li id=" {{ question.id }}"><a href="#">{{ question.question_text }}</a></li> <ul style="display: none"> <li></li> </ul> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} <script> $(document).ready(function() ( $("#question-list li").click(fuction(){ var question_id = string($(this).attr('id')); var detail.id = "#detail-" + question_id; if ($(detail_id).is("visible")) { $(detail_id).hide(); } else { var url = "/polls/" + question_id + "/"; $.getJSON(url, function(data) { $.each(data, function(i, details) { $(detail_id + " li").text(details); $(detail_id).show(); … -
Serving protected files NGINX and Django
I am trying to serve protected media files with Nginx sendfile and X-Accel-Redirect using Django 2.0. This is my Nginx configuration: server { listen 8000; server_name localhost; charset utf-8; sendfile on; # Protected media location /protected { internal; alias /Users/username/Documents/sat23/venv/media/; } # Django static location /static { alias /Users/niketao8/Documents/sat23/venv/static/; } # All other requests. location / { uwsgi_pass django; include /Users/niketao8/Documents/RADON/FLIP-Project/FLIP-API/venv/uwsgi_params; } } Then in my urls.py I added a simple view that should serve my media files (I'll configure permissions later): def serveMedia(request): url = request.path.replace('media', 'protected') response = HttpResponse('') response['X-Accel-Redirect'] = url response['Content-Type'] = '' return response urlpatterns += [ path('/media/', serveMedia) ] However whenever I call localhost:8000/media/users/user35.jpg, I just get a Django (not nginx) 404 page, saying that Django tried all the configured paths and it couldn't find the requested one. So I had a suspicion that my view just doesn't work. I then rewrote it like this: def serveMedia(request): return HttpResponse(content=b'Hello there') And sure enough it doesn't get called. But I have no idea why. Could someone help me out? P.S. Any recommendations on configuring nginx conf are also very welcome! -
How to Delete the Digital Ocean Space Image from Python Django
Please let me know any reference or sample code to how to delete the Digital Ocean Space Image from Python Django, There is example for list and upload the image in Space Image. Please help me to find the way for my solution Getting Error like: 'S3' object has no attribute 'delete_file' Please refer sample code like this session = boto3.session.Session() client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id='********', aws_secret_access_key='********') client.delete_file('inspxotestspace', # Name of Space imagename1) # Name for remote file Thanks in advance, Regards, Kishore -
ElasticSearch and Python : Issue with search function
I'm trying to use for the first time ElasticSearch 6.4 with an existing web application wrote in Python/Django. I have some issues and I would like to understand why and how I can solve these issues. ########### # Existing : # ########### In my application, it's possible to upload document files (.pdf or .doc for example). Then, I have a search function in my application which let to search over documents indexed by ElasticSearch when they are uploaded. Document title is always written through the same way : YEAR - DOC_TYPE - ORGANISATION - document_title.extension For example : 1970_ANNUAL_REPORT_OMCL-TEST_1342 - loremipsum.pdf The search function is always done among doc_type = ANNUAL_REPORT. because there are several doc_types (ANNUAL_REPORT, OTHERS, ....). ################## # My environment : # ################## This is some data according to my ElasticSearch part. I'm learning ES commands too. $ curl -XGET http://127.0.0.1:9200/_cat/indices?v health status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open omcl 5T0HZTbmQU2-ZNJXlNb-zg 5 1 742 2 396.4kb 396.4kb So my index is omcl For the above example, if I search this document : 1970_ANNUAL_REPORT_OMCL-TEST_1342 - loremipsum.pdf, I have : $ curl -XGET http://127.0.0.1:9200/omcl/annual-report/1343?pretty { "_index" : "omcl", "_type" : "annual-report", "_id" : "1343", "_version" … -
Live Stream from camera in Django and display result in template
I have built a django application which reads the inputs from web camera. I then run the input through face detection algorithm. I want to return the value True or False (i.e. face detected or not) to the template. Can someone please let me know what changes I would need to do in the code below? class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame ret, jpeg = cv2.imencode('.jpg', image) # face detection method call here. Gets me true or false. return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() cam = VideoCamera() def gen(camera): while True: frame = cam.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livefe(request): try: return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") except: # This is bad! replace it with proper handling pass -
Cannot update the form containing file field.
I am having trouble to update a model through form having file field. I use the initial=model_to_dict(instance) to pre populate the form. Here is my form:- class UpdateTrainerProfileForm(forms.Form): city = forms.CharField(max_length=30, required=True) state = forms.CharField(max_length=30, required=True) country = forms.CharField(max_length=30, required=True) profile_picture = forms.ImageField(required=True) describe_yourself = forms.CharField(required=True, widget=forms.Textarea) linked_in_url = forms.URLField(required=True) skills = forms.CharField(required=True, widget=forms.Textarea) cv = forms.FileField(required=True) And here is the model that i am trying to save to:- class Trainer_Model(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) city = models.CharField(max_length=30) state = models.CharField(max_length=30) country = models.CharField(max_length=30) profile_picture = models.ImageField(upload_to='profile_pics/%Y/%m/%d/', blank=True) courses_tutoring = models.TextField() describe_yourself = models.TextField() linked_in_url = models.URLField() skills = models.TextField(blank=True) cv = models.FileField(upload_to='cvs/%Y/%m/%d/', blank=True) def __str__(self): return self.user.user.email As you can see that I dont want to update all the model fields I am not using model form. The View that is used to save the form content is as below:- @login_required(login_url='/login/', redirect_field_name='next') def trainer_update_profile(request): user = request.user trainer = Trainer_Model.objects.get(user=user) if request.method == 'POST': form = UpdateTrainerProfileForm(request.POST, request.FILES or None) if form.is_valid(): instance = form trainer.city = instance.cleaned_data.get('city') trainer.state = instance.cleaned_data.get('state') trainer.country = instance.cleaned_data.get('country') trainer.profile_picture = instance.cleaned_data.get('profile_picture') trainer.describe_yourself = instance.cleaned_data.get('describe_yourself') trainer.linked_in_url = instance.cleaned_data.get('linked_in_url') trainer.skills = instance.cleaned_data.get('skills') trainer.cv = instance.cleaned_data.get('cv') trainer.save() messages.success(request, 'Your profile was updated successfully!') else: form = …