Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ValidationError not being raised when trying to login using an email address that does't exist
I am trying to create a simple login page where the user will input the email address and password, and django will log him/her. If not, then show "Email not found" Validation error above the form. The problem I am experiencing is that if the email address is found in the database then the user will be logged in but, if then user is not then it wont show the validation error and ultimately move to 'autheticate' function statement where since the user is 'None' will show error. I have put print statements both in my View class and clean_email function, and it can be seen from the output that the clean_email function is called and it also executes the statement in the ValidationError part. LoginView: class LoginView(View): template_name = None # gets overriden in urls.py def get(self, request, ut): form = LoginForm() ctx = { 'form' : form, 'ut' : ut, } return render(request, self.template_name, context=ctx) def post(self, request, ut): form = LoginForm(request.POST) print("the errors are", form.errors") print("the form is valid:",form.is_valid()) if not form.is_valid() : ctx = { 'form' : form, 'ut': ut, } return render(request, self.template_name, ctx) user = authenticate(request, email=form.cleaned_data['email'], password=form.cleaned_data['password'], user_type=ut) login(request, user) return redirect(reverse('home:index')) LoginForm: … -
How to check if email and password for user exists in the database and then login with these credentials?
I made CRUD operations for user in Django. Only admin can add new user with unique email and password, also can edit and delete. My question is after this how can I login them with these credentials? I was thinking to check if user exists in the database, then login him, but I can't find how to implement this. This is my basic login function, but how to improve it to check in the database? def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'Username OR Password is incorrect') context = {} return render(request, 'login.html', context -
Django query to filter all records between date plus boolean till date boolean changes
I have a model equivalent to this: class SomeModel(models.Model): reference = models.CharField(max_length=24, db_index=True) start_date = models.DateTimeField() is_active = models.BooleanField() I would like to return a queryset of all references between each reference's start-date closest to yyyy-mm-dd (i.e. specified) and is_active = True, and the date for when is_active changed to False. e.g. If I had a list: | reference | start_date | is_active | |-----------|------------|-----------| | j39djkj | 2010-12-01 | True | | dkh39d9 | 2010-11-01 | True | | j39djkj | 2010-09-01 | True | | dkh39d9 | 2010-08-01 | False | | j39djkj | 2010-05-01 | False | | dkh39d9 | 2010-03-01 | True | | j39djkj | 2010-02-01 | True | | j39djkj | 2010-01-01 | True | I want to filter by is_active = True when start_date__lte=2010-12-31 and limit the queryset response to this: | reference | start_date | is_active | |-----------|------------|-----------| | j39djkj | 2010-12-01 | True | | dkh39d9 | 2010-11-01 | True | | dkh39d9 | 2010-08-01 | False | | j39djkj | 2010-05-01 | False | I don't know the date at which the boolean changes, and the number of records is in the tens of millions with about 1 million individual … -
Hourly updated (and on table_update) view in Django/postgresql
I am looking to populate a page with active items in Django. item_active = DateTimeRangeField() Any smarter way to compare the current time: Theoretical "views.py": def time_now(): return timezone.now() def index(request): item_list = item.objects.raw('''SELECT col1, col2 FROM item_table WHERE upper(item_active) >= %s AND lower(item_active) <= %s''', [time_now]) An efficient implementation of the time comparison would be helpful, but my intuition tells me that a SQL-view updated hourly (using Django and Celery or on the PostgreSQL updated hourly and on_table_update) only containing active objects is the smartest. So for the preferred way, how do I implement the view through Django/Celery or the Datebase side? (Hourly and on_table_update) -
Unable to create list of model instances (Experiences)
I am trying to create multiple instances i.e experience for the same user but unable to do. Instead I have to hit the url twice in order to add multiple data. serialzers.py class WorkExperienceSerialzer(BaseModelSerializer): hidden_fields_to_add = {"created_by": None, "user": None} class Meta(BaseModelSerializer.Meta): model = WorkExperienceData fields = [ "company", "designation", "description", "from_date", "to_date", "reference_name", "reference_mailid", "user", "id", ] extra_kwargs = { "user": {"read_only": True}, } def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(WorkExperienceSerialzer, self).__init__(many=many, *args, **kwargs) def create(self, validated_data, **kwargs): instance = super(WorkExperienceSerialzer, self).create(validated_data) return instance def update(self, instance, validated_data): instance = super(WorkExperienceSerialzer, self).update( instance, validated_data ) return instance def get_default_value_for_field(self, field): value = super(WorkExperienceSerialzer, self).get_default_value_for_field( field ) if not value: if field == "user": value = self.context["request"].user return value views.py class WorkExperienceViewSet(ViewListUpdateDeleteViewSet, BaseModelViewSet): queryset = WorkExperienceData.objects.all() serializer_class = WorkExperienceSerialzer def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return super(WorkExperienceViewSet, self).get_serializer(*args, **kwargs) But when I am trying to pass data like below [ { "company": "something", "designation": "something", "description": "something", "from_date": "2020-10-15", "to_date": "2020-11-14", "reference_name": "something", "reference_mailid": "something@gmail.com", }, { "company": "nothing", "designation": "nothing", "description": "nothing", "from_date": "2020-10-25", "to_date": "2020-10-27", "reference_name": "nothing", "reference_mailid": "nothing@gmail.com", … -
List of items, form, response on the same page. What am I missing?
I have general.html page... In the general.html page included query_page.html... The purpose of the query_page.html is to return the list of objects, which are the buttons to detailed descriptions of themselves. It does it... Now, I'm trying to include the form into this same page with the reference to the same query_page (so on itself, so the action="" or action="{% url 'for_queries' %}")... So the result of the search will be shown on the very same page. The form searches through the list of the objects by query_id, and should return one item which matches query id of items... The form and response are easy and by the book, but I don't see the result of the search... The view function itself, it seems, doesn't react on the action... I tried to include print statements into the function, none returned in the command prompt... I see the q object in the search line and in the command prompt though... So it should be posted into the view function, but somehow it doesn't(?most likely) or the function doesn't return the result to the page... I also tried to change the view function from using request and sitting in views.py by itself … -
AttributeError after I added Select2 as a widget in one of my forms - how to fix?
I installed Django-Select2, I applied it to my project, but I'm having an error that I can't wrap my head around. Here is my forms.py file: from django.forms import modelform_factory from django_select2 import forms as s2forms from .models import Employer, JobListing, Category_JobListing class LocationWidget(s2forms.ModelSelect2Widget): search_fields = [ "location__icontains", ] def get_queryset(self): return Employer._meta.get_field("location").choices EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"], widgets={"location": LocationWidget}) JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "due_date", "job_application_url"]) Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"]) views.py file (only the relevant code parts): def submitJobListing(request): if request.method == "POST": employer_form = EmployerForm(request.POST, request.FILES) job_listing_form = JobListingForm(request.POST, request.FILES) category_job_listing_form = Category_JobListingForm(request.POST, request.FILES) #check if employer with that name already exists employer_name = str(request.POST.get("name", "")) #print("Employer name is \"" + employer_name + "\"") employer_with_the_same_name = Employer.objects.get(name=employer_name) #print("Length of the employer with the same name is " + str(len(employer_with_the_same_name))) employer = None if (employer_with_the_same_name != None): employer = employer_with_the_same_name if employer == None and employer_form.is_valid() and job_listing_form.is_valid(): employer = employer_form.save() job_listing = job_listing_form.save(commit=False) job_listing.employer = employer job_listing.save() category_job_listing = category_job_listing_form.save(commit=False) category_job_listing.job_listing = job_listing category_job_listing.save() #return HttpResponseRedirect(reverse("employers:thank_you")) # TODO: Add this URL and template return HttpResponse("Your form has been successfully submitted.") else: employer_form = EmployerForm() job_listing_form = JobListingForm() category_job_listing_form = Category_JobListingForm() context = { … -
django queryset union not working with only
I have 2 querysets and I am applying union on them but the strange thing is when I use only, it is selecting all fields from DB, and when I use values, it is selecting only given fields. This is selecting all fields from the Physician table doctors_models.Physician.objects.filter( appointments__member=self.context['member'] ).union(doctors_models.Physician.objects.filter( appointments__booked_by=self.context['member'] )).only('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix') BUT This is selecting only specified fields from the Physician table doctors_models.Physician.objects.filter( appointments__member=self.context['member'] ).union(doctors_models.Physician.objects.filter( appointments__booked_by=self.context['member'] )).values('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix') However, this is also selecting only specified fields but why should I define fields 2 times. doctors_models.Physician.objects.filter( appointments__member=self.context['member'] ).only('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix').union( doctors_models.Physician.objects.filter( appointments__booked_by=self.context['member'] ).only('id', 'name_prefix', 'first_name', 'middle_name', 'last_name', 'name_suffix')) -
how to load default values at initial and dynamically change value in highchart column?
Hey guys here I successfully made by passing dynamic value in High chart, how ever I want to render some default value first then for every submit I will pass dynamic values. Below I share my code, Please suggest guys? Let me explain this code when the page is loaded successfully, there will be form which is having three drop down box based on the value I am selecting and submitting, I will write sql query to get data from table and pass it to high chart, But I want to know how it will render before submit and after submit pass the value dyanmically. <form id ="new_form" name="new_form" method="POST"> {% csrf_token %} <label for="Question_type">Question Types:</label> <select id="qt_id" name = "select_question_type"> <option value=4>ALL</option> {% for qt in question %} <option value={{qt.id}}>{{qt.question_type}}</option> {% endfor %} </select> <label for="Certificate">Certificate:</label> <select id="Certificate" name = "select_certificate"> <option value = 0> -- Select certificate -- </option> {% for certificate in certifi %} <option value={{certificate.id}}>{{certificate.certification_name}} {{certificate.certification_year}}</option> {% endfor %} </select> <label for="state">State:</label> <select id="state_id" data-district-url="{% url 'Dashboard:load_district' %}" name = "select_state"> <option value = 0> -- Select State -- </option> {% for state in states %} <option value="{{state.id}}" >{{state.state_name}}</option> {% endfor %} </select> <input type="submit" name="submit" … -
Django rest framework [closed]
Need to know the advantages and dis-advantages of using Django rest framework. also I need open source projects examples. also examples of real platforms or projects that uses Django rest framework on production. -
Spark DataFrame.toPandas() failing on inexistent datetimes
My database source has datetimes in UTF. I'm based in CET. Loading data in a Spark dataframe and then converting the dataframe to a Pandas', results in errors due to inexistent datetimes for datetimes during change to summer time (ej: 2013-03-31 02:01:00). Ie, Pandas takes the source Spark dates as in the local timezone. Setting "timezone" to "UTC" in the Spark reader options is ignored, as setting "spark.sql.session.timeZone" to "UTC" for the application. Debugging further I've found that setting in the environment "TZ" to "UTC" manages dates correctly. However, I worry about that setting interferring in other parts of Python or my Django application. Are there other solutions I haven't found yet? If not, what other side-effects should I be aware of? Like other libraries that depend on that setting? I'm using a Windows system, with Python 3 and Django 3. -
Where the Http404 are handled exactly in django?
Where and how do the Http404 or PermissionDenied are handled exactly in django? I could not find functions or methods to catch these exceptions. -
Why 4 == 4 return false? [closed]
I don't understand why my if test failed. {% widthratio instance.child_plugin_instances|length 2 1 as forloop_half %} {% for plugin in instance.child_plugin_instances %} {% if forloop.first %} <div class="col-6"> {% endif %} {% if forloop.counter0 == forloop_half %} </div> <div class="col-6"> {% else %} "{{ forloop_half }}" "{{ forloop.counter }}" {% endif %} {% render_plugin plugin %} {% if forloop.last %} </div> {% endif %} {% endfor %} the test {% if forloop.counter0 == forloop_half %} always return False. But when I display "{{ forloop_half }}" "{{ forloop.counter }}", I got "4" "4". -
Your branch is ahead of 'origin/master' by 4 commits
I have the following error : Your branch is ahead of 'origin/master' by 4 commits. (use "git push" to publish your local commits) nothing to commit, working tree clean I have seen multiple posts on StackOverflow, but none of them work. I am trying to upload a Django Web App to Heroku for the first time. Is there a SOP for these GIT issues please ? -
Custom 500 error page does not take the correct number of arguments - Django
I'm trying to prepare custom 404 and 500 error pages for a production. The 404 works fine, but I'm not able to run the 500. In my urls.py file: from client_interface.views.errors.server_error_view import ServerErrorView handler500 = ServerErrorView.as_view() views/errors/server_error_view.py: from django.shortcuts import render from django.views import View class ServerErrorView(View): def get(self, request): return render(request, "client_interface/errors/500.html") I'm getting ?: (urls.E007) The custom handler500 view 'client_interface.views.errors.server_error_view.ServerErrorView' does not take the correct number of arguments (request). error all the time. I tried to change the arguments of the get method to get(request) but it didn't help. -
Return QuerySet based on User group/permissions
I'm trying to figure out what's the "best practice" to limit QuerySets based on Users permissions. For example, there is a table of invoices on the dashboard. User that has Group called Admin can see all invoices but User that has group Broker can see only their own invoices. That means only invoices that have user = .... My idea is to create two permissions can_see_all_invoices and can_see_own_invoices. Now when I call the QuerySet using Django Rest Framework, I'll check for the permissions and return the filtered QuerySet. Or should I filter the QuerySet on the frontend and if Broker asks for all invoices I would raise PermissionError? Which of these approaches are being used or is there a different approach? -
why django default search gives error when we put in search box *?
DataError at invalid regular expression quantifier operand invalid I'm trying to create a very simple search function which would filter by a key word given into search form.why django default search gives error when we put in search box *? -
SAVE MULTIPLE CHECKBOX STATE AFTER RELOAD
I'm working on a django project that manages projects. Each project (bootstrap card) has a button that opens a modal with the project's detail. The modal contains a list of checkboxes. I want to store the state of the checkbox after the page reload. This is the code of the list of checkboxes: <p class="bold-elements">TASKS:</p> <ul class="list-group list-group-flush lista-tasks"> <div id="checkbox-container"> <div class="form-check"> <input name="dett1" store="checkbox1" class="form-check-input box" type="checkbox" value="" id="flexCheckDefault"> <label class="form-check-label" for="flexCheckDefault"> {{progetto.descrizione}} </label> <br><br> {% if progetto.task1 != "" %} <input name="dett2" store="checkbox2" class="form-check-input box" type="checkbox" value="" id="check1"> <label class="form-check-label" for="check1"> {{progetto.task1}} </label> <br><br> {% endif%} {% if progetto.task2 != "" %} <input name="dett3" store="checkbox3" class="form-check-input box" type="checkbox" value="" id="check2"> <label class="form-check-label" for="check2"> {{progetto.task2}} </label> <br><br> {% endif%} {% if progetto.task3 != "" %} <input name="dett4" store="checkbox4" class="form-check-input box" type="checkbox" value="" id="check3"> <label class="form-check-label" for="check3"> {{progetto.task3}} </label> <br><br> {% endif%} {% if progetto.task4 != "" %} <input name="dett5" store="checkbox5" class="form-check-input box" type="checkbox" value="" id="check4"> <label class="form-check-label" for="check4"> {{progetto.task4}} </label> </div> </div> </ul> I've found this javascript code to store the state: var boxes = document.querySelectorAll("input[type='checkbox']"); for (var i = 0; i < boxes.length; i++) { var box = boxes[i]; if (box.hasAttribute("store")) { setupBox(box); } } function setupBox(box) … -
how to make a comment post api in django related to the single blogpost detail?
I have a page where a blog post detail is displayed. Under the post, there is a section where user can comment after inputing thier name subject and text in a comment box. Now i have to make an api for this. I want to make a post api such that that comment is stored/associated to that particular blogpost detail. That means i need blogpost id to pass while posting comment. How to do that?? class BlogPost(models.Model): CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) image = models.ImageField(blank=True, null=True) categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news') description = models.CharField(max_length=255) content = RichTextUploadingField() # todo support for tags tags = models.CharField(max_length=255, default='#travel') #todo date_created = models.DateField() @property def html_stripped(self): from django.utils.html import strip_tags return strip_tags(self.content) @property def comments(self): return self.comments_set.all() Here are my serializers: class CommentPostSerializer(serializers.ModelSerializer): class Meta: model = Comment # fields = '__all__' fields = ['name', 'email', 'subject', 'comment',] class BlogPostSerializer(serializers.ModelSerializer): comments = CommentListSerializer(many=True) class Meta: model = BlogPost fields = ['image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' Here is my view: class CommentCreateAPIView(APIView): queryset = Comment.objects.all() serializer_class = CommentPostSerializer -
Why does my Django form not work on submit?
So I'm using modelformset_factory, and my template renders it perfectly but submit button won't work. Let me show you my code:forms.py class AnswerForm(forms.ModelForm): answer = forms.CharField(required=False) share_to_others = forms.BooleanField(required=False) views.py from .models import Answer from .forms import AnswerForm def createAnswer(request, pk): AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, extra=1) formset = AnswerFormSet( queryset=Answer.objects.filter(authuser=request.user.id, question_number=pk) ) if request.method == "POST": formset = AnswerFormSet(request.POST) if formset.is_valid(): instance = formset.save(commit=False) instance[0].authuser = request.user instance[0].question_number = thisQuestion instance[0].save() return redirect('/main') context = { 'formset':formset, } return render(request, '/answerPage.html', context) and my template ... <form method="POST" class="form-group">{% csrf_token %} <div class="row"> <div class="col"> {% crispy formset %} </div> </div> <div class="row"> <div class="col"> <button type="submit" class="btn">SUBMIT</button> </div> </div> </form> I don't see what I have done wrong. When I click the submit button, nothing happens and the page stays still. Any help is very much appreciated! :) -
Django preexisting tables not showing on shell
My database has few mysql tables which were prexixting i.e before django app migration.Ex: class Testesing(models.Model): users_id = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'test' Here this line says that don't create table because it is preexisting. managed = False Now the database to which my django app is connected has all tables, but in django shell it's only showing few tables which are not prexisting. When i run this command it only shows tables which were migrated using django app i.e newly created tables or tables created from app and not prexisting db tables.: from django.db import models I could see my prexisting db tables using this command in shell. [ m._meta.db_table for c in apps.get_app_configs() for m in c.get_models() ] I want to do crud operations with my tables but how can i fetch those tables: i.e want to do sometihing like this: Data = test.objects.all() -
Hit the database in loop make my site (how avoid it ?)
in the first this is my models: class MediaSecParnt(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE) withsecondray = models.ForeignKey(Secondary, on_delete=models.CASCADE) nomberesteda = models.PositiveIntegerField(null=1, blank=1) nomberhodor = models.PositiveIntegerField(null=1, blank=1) date = models.DateField(null=1, blank=1) class Degrey(models.Model): name = models.CharField(max_length=200) class DegreyCompany(models.Model): withdegrey = models.ForeignKey(Degrey, on_delete=models.CASCADE, null=True, blank=True) company = models.ForeignKey(Secondary, on_delete=models.CASCADE, null=True, blank=True) spesial = models.ForeignKey('Spesial', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, default=withdegrey.name, null=True, blank=True) nomberetud = models.PositiveSmallIntegerField(null=True, blank=True) nomberexist = models.PositiveSmallIntegerField(null=True, blank=True) femail = models.PositiveSmallIntegerField(null=True, blank=True) reatrap = models.PositiveSmallIntegerField(null=True, blank=True) this for school when degree is the level studing DegreyCompany is the level of studing in every company mostally all have 3 level MediaSecParnt is Number of interviews with parents i use this queryset : mediasecparnt = MediaSecParnt.objects.select_related('withsecondray','withdegrey').filter(date__range=[primary1, primary2]).values('id', 'withdegrey__name', 'withdegrey__id', 'withsecondray__id', 'withsecondray__name', 'date','nomberesteda','nomberhodor') mediasecparnt = list(mediasecparnt) print(mediasecparnt) result come : [{'id': 2, 'withdegrey__name': 'level one', 'withdegrey__id': 1, 'withsecondray__id': 1, 'withsecondray__name': 'company one', 'date': datetime.date(2020, 9, 17), 'nomberesteda': 100, 'nomberhodor': 20}, {'id': 3, 'withdegrey__name': 'level one', 'withdegrey__id': 2, 'withsecondray__id': 1, 'withsecondray__name': 'company two', 'date': datetime.date(2020, 9, 30), 'nomberesteda': 10, 'nomberhodor': 2}] till now everything is good i want to accses to the 'nomberetud' with is colmune in table 'DegreyCompany' i use this request : mediasecparnt = MediaSecParnt.objects.select_related('withsecondray','withdegrey').filter(date__range=[primary1, primary2]).values('id', 'withdegrey__name', 'withdegrey__id', 'withsecondray__id', 'withsecondray__name', 'date','nomberesteda','nomberhodor') just … -
How can i filter before render page?
I want to filter some objects through sector. Here is my model: class Videos(models.Model): brand = models.CharField(max_length=255, verbose_name="Brand Name", blank=False, null=True) sector = models.CharField(max_length=255, verbose_name="Sector Name", blank=False, null=True) video = models.FileField(upload_to="videos/") And this is my view where i want to filter it: def automotive(request): videos = Videos.objects.filter() The thing is in my navbar i've few sector names. When user clicks one, it should render video with sector name that user clicked. For example, one of my sector name is Automotive. So when i click that, i should see videos that only sector is Automotive. So sorry for my broken English, i tried my best... -
Tiny MCE and Django
I was trying to build a blogging website. I used Tiny MCE and Django for the purpose. I could add/upload photos to my blogs. But the problem is the images uploaded via Tiny MCE are not responsive for smaller screens like a mobile phone screen. The texts are well responsive but the images are overflown. I went through Tiny MCE documentation but didn't find the answer. Here's my set of code: tinyinject.js: (I am not so good with JS) var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload = function () { tinymce.init({ selector: '#id_content', plugins: [ 'advlist autolink link image imagetools lists charmap print preview hr anchor pagebreak', 'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking', 'table emoticons template paste help' ], toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | ' + 'bullist numlist outdent indent | link image | print preview media fullpage | ' + 'forecolor backcolor emoticons | help | image', imagetools_toolbar: "rotateleft rotateright | flipv fliph | editimage imageoptions", image_title: true, automatic_upload: true, file_picker_types: 'image', file_picker_callback: function(cb, value, meta) { var input = document.createElement('input'); input.setAttribute('type', 'file'); input.setAttribute('accept', 'image/*'); input.onchange = function() { var file … -
Django , adding images to the same object
i have this two models with a relationship 1-N: def get_image(instance, filename): return os.path.join('intervencao/fotografias', str(instance.intervencao), filename) class Intervencao(models.Model): ...... class Imagem(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='intervencaoObjectsImagem', on_delete=models.CASCADE) imagem = models.ImageField(upload_to=get_image, blank=True, null=True, verbose_name="Fotografia") def __str__(self, ): return str(self.intervencao) So i have one form for each model , and i want to add some images for the same object My form class TabletForm2(forms.ModelForm): class Meta: model=Intervencao ..... class TabletFormImagem(forms.ModelForm): class Meta: model=Imagem fields = ['imagem'] imagem = forms.ImageField(required=True) My view def project_detail_chefe(request, pk): form = TabletForm2(request.POST or None, instance=instance) form2 = TabletFormImagem(request.POST, request.FILES) if request.method == "POST": if form.is_valid() and form2.is_valid(): instance_form1 = form.save() instance_form2 = form2.save(commit=False) instance_form2.intervencao = instance_form1 instance_form2.save() return redirect('project_detail_chefe',pk) else: form = TabletForm2(request.POST) form2 = TabletFormImagem() context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) tablet/info_chefes.html <form method="post" enctype="multipart/form-data" id="gravar"> {% csrf_token %} <!--First image--> <div class="row"> <div class="col-md-12"> {% for fotografia in intervencao.intervencaoObjectsImagem.all %} <div class='form-group'> <label id='titulo'>Fotografia:</label> <em><a href ="/media/{{fotografia.imagem|default_if_none:''}}" target="_blank" > {{fotografia.imagem|default_if_none:''}}</a></em> <img src="/media/{{fotografia.imagem|default_if_none:''}}" alt="..." class="img-thumbnail"> </div> <hr> {% endfor %} {{ form2.as_p }} </div> <div class="row"> <div class="col-md-12"> <hr> {% endfor %} {{ form.as_p }} </div> </div> <!--Seconde image--> <div class="row"> <div class="col-md-12"> {% for fotografia in intervencao.intervencaoObjectsImagem.all %} <div class='form-group'> <label id='titulo'>Fotografia:</label> …