Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how do I add the contents of two fields and display the results in a third field?
I'm trying to learn Django and am finding it frustratingly difficult to do fairly basic things. I have the following form classes: from django import forms class InputForm(forms.Form): field1 = forms.FloatField(label="First field: ") field2 = forms.FloatField(label="Second field: ") class OutputForm(forms.Form): outfield = forms.FloatField(label="Result: ") And the following template: <form> {{ input_form.as_ul }} </form> <form action="#" method="get"> <input type="submit" class="btn" value="Submit" name="submit_button"> </form> <form> {{ output_form.as_ul }} </form> And finally, the following view: from django.shortcuts import render from .forms import InputForm, OutputForm def index(request): if request.GET.get('submit_button'): # ????? else: input_form = InputForm() output_form = OutputForm() return render(request, 'index.html', {'input_form': input_form, 'output_form': output_form}) All I want to happen is that when I hit the submit button, the values in first field and second field get added and displayed in the result field. I know from debug outputs that the ????? commented block is run when I press the button, but I have so far not been able to figure out what to do to actually access or alter the data in my fields. I don't care about keeping a record of these transactions so it feels like storing these in a database is tremendous overkill. What is the correct way to approach … -
Django migrations: how to conditionally switch between migration statements according to current DB backend?
I use Django with SQLite in my dev environment and postgreSQL in production. I know that having different DB backends for dev and prod is a tech debt, but this is the current state of affairs for now (not for long, hopefully). I would like to take advantage of the postgres JSONField in production while in dev keep using django-jsonfield. Is there a way to write a migration so that it can conditionally switch between the two types of field depending on which backend is currently being used? -
Integrate Django Oauth Toolkit urls correctly
I followed the instructions from the official django-oauth toolkit doc (https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_02.html) and included all oauth-toolkit urls manually to prevent users from creating applications. In my root urls.py i added the following line to the url patterns, as showed in the tutorial: url(r'^o/', include(oauth2_endpoint_views, namespace="oauth2_provider")), I used the include from django.conf.url package. Now when i start the server, it says "Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead." when i add a name attribute to the url-command like this: url(r'^o/', include(oauth2_endpoint_views, namespace="oauth2_provider"), name="oauth2_provider"), the server starts up, but when i try to visit "localhost/o/applications" it says "NoReverseMatch: 'oauth2_provider' is not a registered namespace" What am i doing wrong? -
django-admin dbshell CommandError: You appear not to have the 'sqlite3' program installed or on your path
I use two sqlite databases in my django project . One for default and another for customer_data. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'customers': { 'NAME': 'customer_data', 'ENGINE': 'django.db.backends.sqlite3', 'USER': 'db2', 'PASSWORD': 'db2password' } } DATABASE_ROUTERS = ['theapp.routers.CustomerRouter',] This is my routers.py class CustomerRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'customer': return 'customer_data' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'customer': return 'customer_data' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ if obj1._meta.app_label == 'customer' or \ obj2._meta.app_label == 'customer': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'customer': return db == 'customer_data' return None -
Change the database of the app Django
I am making a project using python 3.5 and Django 1.8 ,there is a feature for login and signup, so login and signup are two different apps THIS image shows my directory structure of apps Now in login app's form , I import from signup.models allusers1 (a class in signup.models) Using view I pass the form and when I enter the credentials in the database eg checkit and 12345 (username and password) ,I get this error user not found THE ERROR= I have two databases in my project ,Users and allusers1 (see image) . The users database has records of superusers ,etc where as allusers database has users registered on my website.See image allusers1 has a record called checkit and 12345 as password where as users(database) doesn't have it,so what is happening is that the app is selecting records from the users database instead of allusers1 database How do I change the database ? This is login/forms.py from django import forms from signup.models import allusers1 from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) User=get_user_model() class UserLoginForm(forms.ModelForm): class Meta: model = allusers1 fields=['username','password'] widgets = { 'password': forms.PasswordInput(), } def clean(self ,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == … -
Django IntegrityError: UNIQUE constraint failed on a mapping table
I am getting the error below after creating a mapping table and adding some data to my table: return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: config_sitesubnets.site_id, config_sitesubnets.subnet_id my models is as such: class SiteSubnets(models.Model): site = models.ForeignKey(SiteData, on_delete=models.CASCADE) subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE) class Meta: verbose_name = "Site Subnets" verbose_name_plural = "Site Subnets" unique_together = ('site', 'subnet',) I believe the unique_together attribute would mean that I shouldn't be able to have for example site_id = 1 and circuit_id = 1 more than once? I added all my data and then I started to get the error. I run the below sql query against the sqlite db to try identify if this has happened somehow by accident. which I believe this has show that there isn't any. 0 rows returned in 1ms from: SELECT site_id, subnet_id, COUNT(*) FROM config_sitesubnets GROUP BY site_id, subnet_id HAVING COUNT(*) > 1 Now im not sure why im getting this error or how to fix it? -
Suggest me Video tutorials for Django
Please suggest me video tutorials for Django for now I am watching THE TREE HOUSE videos for free, let me know what more should I watch! -
Url parameter to model field
I have a view that takes a parameter and returns a csv file based on a queryset: def rfidi_list(request, id=None): if id == None: raise Http404 rfid_list = Rfid.objects.filter(----).values_list('rfid_st',flat=True) import csv response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="rfidi_list.csv"' writer = csv.writer(response, delimiter=';') writer.writerow(rfid_list) return response I have a model called Rfid that has boolean fields named: vrata1, vrata2, vrata3 I want to filter queryset based on the id that came in url. If the id was 1, I would return objects with vrata1 = True, if it was 2 I'd like to get qs with objects with vrata2 = True. Thank you -
Redirect from one Modal to another modal on Ajax success
I have been trying to open a Modal from another Modal. In first Modal I make an Ajax call to verify the code variable. If success I would like Ajax call to redirect the user to the actual signup form. It does redirect but I would like it to open as a Modal not as normal page. Here is Ajax in my first Modal: $(function() { $("#verify").click(function () { var code = $("#code").val(); var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var link = "{% url 'health:add_doctor' %}" $.ajax({ type: "POST", url: '/verify_code/', data: { 'code': code, 'csrfmiddlewaretoken': csrf }, dataType: 'json', success: function (data) { alert(link) if (data.verified == 1) { $(location).attr('href', link); } } }); }); }); Second Modal code: <form action="{% url 'health:add_doctor'%}" method="post" accept-charset="utf-8" class="form" role="form"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="title-doc">Add a Doctor</h4> </div> <div class="modal-body"> {% csrf_token %} <div class="row"> Fields here </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <button class="btn btn-success" type="submit">Add</button> </div> </form> The second Modal opens fine on a button's click another page on. But I am not getting how to do it from a Modal. I tried few answers on SO but it doesn't work in my … -
Django-Attributes of model displayed in admin differ from what I got in other method.
I used 'update_or_create' method to change model attribute but I noticed that change were not reflected. While examining what is wrong, I noticed that, oddly, the value of attribute seen in admin page was changed correctly. I tried to get object and check attributes by many other method, but obviously change weren't refrected. e.g.) obj = SomeModel(pk=x)=>obj.some_field obj = get_object_or_404=>obj.__dict__ In both methods, an obj with the same pk exist certainly, but all field is None. What is going on? Please help me... -
Django filewrapper memory error
I have code like this: @login_required def download_file(request): content_type = "application/octet-stream" download_name = os.path.join(DATA_ROOT, "video.avi") with open(download_name, "rb") as f: wrapper = FileWrapper(f, 8192) response = HttpResponse(wrapper, content_type=content_type) response['Content-Disposition'] = 'attachment; filename=blabla.avi' response['Content-Length'] = os.path.getsize(download_name) # response['Content-Length'] = _file.size return response It seems that it works. However, If I download bigger file (~600MB for example) my memory consumption increase by this 600MB. After few such a downloads my server throws: Internal Server Error: /download/ Traceback (most recent call last): File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/matous/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/matous/.local/lib/python3.5/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/media/matous/89104d3d-fa52-4b14-9c5d-9ec54ceebebb/home/matous/phd/emoapp/emoapp/mainapp/views.py", line 118, in download_file response = HttpResponse(wrapper, content_type=content_type) File "/home/matous/.local/lib/python3.5/site-packages/django/http/response.py", line 285, in init self.content = content File "/home/matous/.local/lib/python3.5/site-packages/django/http/response.py", line 308, in content content = b''.join(self.make_bytes(chunk) for chunk in value) MemoryError What I am doing wrong? Is it possible to configure it somehow to stream it the piece by piece from hard-drive without this insane memory storage? Note: I know that big files should not be served by Django, but I am looking for simple approach that allows to … -
Django2.0 and dynamic formsets jquery
In a Django 2.0 project, I am trying to implement a view using an inline formset to create/edit/delete three metric values belonging to an item. Items and their values are in two different models related by a Foreignkey. I copied the inline_formset view as can be found here and it works fine. I am able to delete, update and create new entries. However, I would like the possibility to add/edit/delete values dynamically and to this end I tried to use the django-dynamic-formset jquery.. When I refer to it in the template, and go to the view, I am able to add, and edit existing entires, yet I am not able to delete entires any more. It seems that although the 'remove' function appears to work well, that is, it removes the lines from the html page, replaces the delete checkbox with a hidden input, sets the value for it to 'on' for lines removed, still, when to form is submitted, Django does not recognize any deleted items upon validation and saving. If I leave the checkboxes in, remove the jquery, everything works fine, except its not dynamic. See below my template code: <tbody> {{formset.management_form}} {% for szett_form in formset %} … -
Error import m2m widget django import-export
I'm using a django-import-export Django library, but it's not working for m2m relationships. I have the following models.py: class Writer(models.Model): name = models.CharField(verbose_name='Nome', max_length=20) last_name = models.CharField(verbose_name='Sobrenome', max_length=50, default='') def __str__(self): return '%s (%s)' % (self.last_name,self.name) class Book(models.Model): book = models.CharField(verbose_name='Título', max_length=200) isbn = models.CharField(verbose_name='ISBN:',max_length=13,help_text='13 Caracteres') writer = models.ManyToManyField('Writer', verbose_name='Escritor(es)') def __str__(self): return self.book # Cria uma string a partir dos 3 primeiros nomes de autores (se existe) def display_writer(self): """ Creates a string for the Genre. This is required to display genre in Admin. """ return ', '.join([ writer.name for writer in self.writer.all()[:3] ]) display_writer.short_description = 'Writer' O arquivo de resources.py: from import_export import resources from import_export.fields import Field from import_export.widgets import ManyToManyWidget from .models import Book, Writer class BookResource(resources.ModelResource): writer = Field(column_name='writer', attribute='writer', widget=ManyToManyWidget(Writer,separator=',', field='name')) class Meta: model = Book skip_unchanged = True report_skipped = False import_id_fields = ( 'isbn' ,) fields = ('isbn', 'book', 'writer', ) When importing a csv file, it does not give errors, but it does not matter the data of the m2m field. -
Django translation
I am using django rosetta to translate my site in 2 different languages and it is working correctly. So if I want to translate from english to indonesian i type 127.0.0.1:8000/en/ to 127.0.0.1:8000/id/ But the problem is when i want to add a select option in template I get a no reverse argument error. and in the url am passing in rosetta which i configured in the urls. <form action="{% url "rosetta" %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="/" /> <select name="language"> {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" {% if lang.0 == SELECTEDLANG %} selected {% endif %}> {% if lang.1 == 'Indonesian' %} Indonesian {% else %}{{ lang.1 }} {% endif %} </option> {% endfor %} </select> <input type="submit" value="Go" /> Could I be doing something wrong, please help. -
Django many-to-many modelling
In my current project I have two tables, Certifications and Users. There are many types of Certifications. Multiple Users can have the same Certification. However I need to store data about how each Certification is related to each of its Users, or rather, how each User is related to their Certifications. For example, I need to store the time at which a User received a Cert. In a normal relational database, I would probable have another table, users_certs or something, which would contain two foreign keys on the tables described, plus a third column as a timestamp. In Django, we have the Many-To-Many relationships, but we can't store extra data about these relationships. How should I go about modelling this system, the Django way? -
Encode field from Ajax in Django
I have some trouble with my Ajax form in Django. It does not accept characters like æ, ø, å. This is the error I get when trying to submit a form with Ajax with å: Exception Value: 'ascii' codec can't encode character '\xe5' in position 72: ordinal not in range(128) I need to encode the post value of the field, before it is saved to the model. But how do I "intercept" and encode before save? Here is my View: class PollForm(FormView): form_class = PollForm template_name = 'ajax-form.html' success_url = '/success/' def form_invalid(self, form): response = super(PollForm, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(PollForm, self).form_valid(form) #Trying to encode the field before save: form.instance.answer = form.cleaned_data.get('answer').encode("utf8") form.save() if self.request.is_ajax(): print(form.cleaned_data) data = { 'message': "Success" } return JsonResponse(data) else: return response -
Celery 4.1 periodic tasks error
I am trying to setup a task to run every ten seconds.Using Celery Beat. I am using: Django==1.11.3 celery==4.1.0 django-celery-beat==1.1.1 django-celery-results==1.0.1 It is giving me the following error: Received unregistered task of type 'operations.tasks.message' I am new to Celery, I have tried numerous solutions and cannot seem to find a solution,would appreciate the help settings.py CELERY_BROKER_URL = 'pyamqp://guest@localhost//' CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Johannesburg' CELERY_BEAT_SCHEDULE = { 'message': { 'task': 'operations.tasks.message', 'schedule': 10.0 } } celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nodiso.settings') app = Celery('nodiso') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) __init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] task.py … -
How to Implement querying objects foreign key relationships across multiple databases in Django
I am using django 1.11 how do I query objects foreign key relationships across multiple databases via routing. -
How to modify files uploaded using django ModelForm?
Here I have a ModelForm, which (I was hoping) should replace any uploaded image with /some/other/image.png: class MyModel(models.Model): image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True, null=True) class MyModelForm(ModelForm): def __init__(self, *a, **kw): super().__init__(*a, **kw) self.fields['image'].validators = [] def clean_image(self): img = self.cleaned_data.get('image') if not img: return img from PIL import Image i = Image.open('/some/other/image.png') fmt = i.format.lower() i.save(img.file, fmt) return img class Meta: model = models.MyModel I had expectations that whatever file object can be found in the img.file, later (when the model is saved) it will be flushed to HDD. However it didn't work as I expected as the original (uploaded) image is always flushed to HDD. How can I make it work as expected? -
Django: Adding a non-model field into serializers.serialize
I have following code: pending_invoices=invoice.objects.filter(user=request.user,customer=pk).annotate(sum_invoices=Sum('invoicereceipt__amount')) pending_invoice=pending_invoices.filter(~Q(sum_invoices=0)) invoices=serializers.serialize('json', pending_invoice,fields=("number","sum_invoices")) return HttpResponse(invoices,content_type='application/json') I am trying to get JSON data through ajax. I can successfully get number field in my output. But I have annotated sum_invoices and do not get this value in json output. My question is whether my above code is correct if not then how do I add annotated field and result to my json output? Edit: invoices=serializers.serialize('json', pending_invoice,fields=("number","sum_invoices")) In this above line "number" is a field in my model and sum_invoices I have added by using annotate. -
Django admin: Prefetch choices in list_editable
I have a model Domain and I set it's ForeignKey Language model in list_editable in ModelAdmin. The problem is that it causes lot of SQL queries according to django_debug_toolbar. I thought that I could solve it using select_related but it did not help. @register(Domain) class DomainAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'main_url', 'language', 'max_depth', 'number_of_urls'] list_editable = ['name', 'main_url', 'language', 'max_depth'] list_select_related = ['language'] #def get_queryset(self, request): # return super(DomainAdmin, self).get_queryset(request).prefetch_related('language') It still perform SQL query for every Domain to fetch all Language objects. How to make it fetch once for all Domains? -
Django query a model from another model in form
I am trying to build up a query for my form. Thing is that I want my query to point to show all the courses a teacher has. In creating a teacher account though, I use 2 models, one for verification of the teacher_ID field. So to display the courses for a specific logged in teacher, I have to point from all courses that have a teacher from TeacherData model to Teacher model by using the teacher_ID column which is the same and then find a way display courses based on that. I am close to the answer, tho my query doesn't work as intended. No courses show in the dropdown.. class LectureForm(forms.ModelForm): lecture_title = forms.CharField(max_length=100, required=True) course = forms.ModelChoiceField(initial=Course.objects.first(), queryset=Course.objects.filter( Q(teacher1_id__in=[t.pk for t in TeacherData.objects.filter(teacher_ID=[t.teacher_ID for t in Teacher.objects.all()])]) | Q(teacher2_id__in=[t.pk for t in TeacherData.objects.filter(teacher_ID=[t.teacher_ID for t in Teacher.objects.all()])]))) class Meta: model = Lecture fields = ('course', 'lecture_category', 'lecture_title', 'content') class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=30, null=True, blank=True, default=None) surname = models.CharField(max_length=50, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) teacher_ID = models.CharField(unique=True, max_length=14, validators=[RegexValidator(regex='^.{14}$', message='The ID needs to be 14 characters long.')], null=True, blank=True, default=None) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', … -
Using subprocess call return No such file or directory
I have used this with success in the past from subprocess import call with import os To make sure I have the correct path printing I looked at the console after print str(os.path.abspath(str(os.path.join(settings.MEDIA_ROOT, 'user_2/SampleIllustration.pdf'))))]) This path/directory most certainly exists; however, after trying to convert the pdf to a text file with call(["pdftotext", "-layout", str(os.path.abspath(str(os.path.join(settings.MEDIA_ROOT, 'user_2/SampleIllustration.pdf'))))]) I receive an error that No such file or directory What is strange is that when I am developing on my local machine, this call works as expected. It's only when I'm on the server that I receive this message. -
Formset not registering as valid
I have a formset, but for some reason it isn't meeting the is_valid() criteria, so isn't saving the changes when it's submitted. Here is the relevant parts of the view: def admin_tools(request): ElectionFormSet = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, extra=0) ResultsFormSet = modelformset_factory(Result, exclude=('ElectionID','Results',), formset=BaseResultsFormSet, extra=0) if request.method == 'POST': if 'edit_elections' in request.POST: formset = ElectionFormSet(request.POST) if formset.is_valid(): formset.save() messages.add_message(request, messages.SUCCESS, 'Election settings saved') return redirect(reverse('elections:home')) else: messages.add_message(request, messages.ERROR, 'Problem') return redirect(reverse('elections:home')) else: results = Result.objects.filter(Public=False) result_list = [] for result in results: result_data = [result.ElectionID.Name] candidates = Candidate.objects.filter(id__in=json.loads(result.Results)) for candidate in candidates: result_data.append(candidate.UserID.get_full_name) result_list.append(result_data) open_elections = Election.objects.filter(Complete=False) new_election_form = NewElectionForm() formset = ElectionFormSet() result_formset = ResultsFormSet() return render(request, 'admin/admin_tools.html',{ 'new_election': new_election_form, 'formset': formset, 'elections': open_elections, 'result_formset': result_formset, 'results': result_list, }) Whenever I submit the formset, no matter what changes are made, I get the error message, meaning the condition is_valid() is not being met. Why is this and how do I fix it? -
Error in Basic User Permissions in Django blog
My simple Django blog don't work - if I go to http://127.0.0.1:8000/posts/create/ I see Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/posts/create/ Raised by: posts.views.post_create Looking in the git history I understand what error in posts/views.py. The file itself looks like this from urllib.parse import quote from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.contrib import messages from .forms import PostForm from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render def post_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, 'Successfully Created') return HttpResponseRedirect(instance.get_absolute_url()) context = { 'form': form, } return render(request, 'posts/post_form.html', context) def post_detail(request, id=None): instance = get_object_or_404(Post, id=id) share_string = quote(instance.content) context = { 'title': instance.title, 'instance': instance, 'share_string': share_string } return render(request, 'posts/post_detail.html', context) def post_list(request): queryset_list = Post.objects.all() paginator = Paginator(queryset_list, 5) page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'object_list': queryset, 'title': 'List' } return render(request, 'posts/post_list.html', context) def post_update(request, id=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = …