Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django what do i need for authentication after login?
I followed the example in: https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.login from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. This code doesn't seem to return any token or some sort to the client but just a redirection. In other codes where django checks authentication, django checks request.user.is_authenticated. Do i need to set this by myself? from django.conf import settings from django.shortcuts import redirect def my_view(request): if not request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) To get authenticated by decorators such as @login_required or have proper value for request.user.is_authenticated, what do I need to send and receive from the client(ReactJS)? -
Django insert one-to-one field only with its primary key?
When I try to create a basic post, it requires me to pass all the information about the author. post request body: { "author": { "id": 1 }, "title" : "title1", "content": "content1" } error message: { "author": { "username": [ "This field is required." ], "password": [ "This field is required." ], "profile": [ "This field is required." ] } } Is it possible to assign author only by its user id like I tried in the example above? class BasicPost(models.Model): author = models.OneToOneField(User, null=True, on_delete=models.SET_NULL, related_name='author') title = models.TextField() content = models.TextField() created_at = models.DateTimeField(default=timezone.now) modified_at = models.DateTimeField(default=timezone.now) -
Loop through django queryset in Javascript
I'm new to Django and I need to use some JS for my site, but i'm having a hard time understanding it. This is my view, where i am passing 'seats' to my template seats = Seat.objects.filter(screen = screen) seats = serializers.serialize('json', list(seats), fields = ('position', 'status')) context = {'seats': seats} return render(request, 'cart/choose_seat.html', context) This is 'seats' printed What i want to do is print the position of each seat object. So far, i've only written this: <script> var seats = "{{seats}}"; function position() { for (var i=0; i<seats.length; i++){ var obj = seats[i]; document.write(obj) } } </script> So, what should i do to print position? Thanks in advance -
Is bash_profile a shared file? Can SECRET_KEYs be shared between 2 projects?
Working on deploying the two Django projects I've developed, I deployed the first one and ran atom ~/.bash_profile in command line venv to set my SECRET_KEY and DEBUG values. I was able to deploy that app and its up and running fine. Then I went to deploy my second project and used the same command line script to open bash_profile and the SECRET_KEY and DEBUG values from the previous project is what came up. Is bash_profile a shared file? Am I supposed to have the same SECRET_KEY values for two different projects? -
Django FileResponse from io.BytesIO()
I have a view that serves PDF files, but I would like to modify the metadata of the pdfs before sending them. This is what I have so far: import i from django.http import FileResponse, StreamingHttpResponse from PyPDF2 import PdfFileReader, PdfFileWriter def doc_view(request): handle = open("documents/foo.pdf", "rb") base_pdf = PdfFileReader(handle) output_pdf = PdfFileWriter() for page in base_pdf.pages: output_pdf.addPage(page) stream = io.BytesIO() output_pdf.write(stream) stream.seek(0) return FileResponse(stream.read(), content_type="application/pdf") Running stream.read() manually returns a bytes object, which looks like it is ASCII encoded (but not certain of that). The view completes successfully, and returns a 200, but the PDF received by the browser cannot be displayed (it seems to be corrupted somehow). -
Django Rest Framework — no module named rest_framework
I am build a backend for my Nuxt.js project and I installed the following packages: django django-rest-framework django-cors-headers I installed them using pip3 but when I am trying to run migrations I get the following error: ImportError: No module named 'rest_framework' I checked my settings.py and I have everything as it should be. Do you guys have an idea how to solve this? -
Retrieve and update field of a model on views and display updated field in template
I am working on a view that retrieves the field(user's score) that is declared in a model, where I will also update the field(user's score) after a simple if-else statement, then display the field in template. But now, in the template's text area, where I put the result, it is now only showing userScore: userScore object (1), False, instead of the value of the user's score. So, how can I retrieve the score of the user from the model and update the field in views? morse_logs/game1.html {% block content %} <title>GAME 1</title> <h1>GAME 1</h1> <h2>1 + 1 = ?</h2> <form action="" method="get" > <input type="number" id="ans1" name="ans1"/><br><br> <button type="submit" name="game1Answer">Submit</button><br><br> <textarea rows="10" cols="50" name='a2' > {{currentS}} </textarea> </form> </div> {% endblock content %} morse_logs/views.py @login_required() def game1(request): if request.user and not request.user.is_anonymous: user = request.user #else: #Throw some raised exception here as the user is not valid... """The Game 1 page""" def verifyGame1(val1): user_score = userScore.objects.get_or_create(user=user) if val1 == 2: #user's score declared in model increase 5points #display correct and 5 points added to user user_score.score += 5 #user_score = str(user_score) user_score.save() return user_score else: #user's score declared in model has no point #display incorrect and 1 point added to … -
Executing a function from a third party package when a Record/Domain model is saved
I've been stuck on this for over a day now. Here is the function I want to execute: https://github.com/gnotaras/django-powerdns-manager/blob/master/src/powerdns_manager/utils.py#L551 rectify_zone As you can see, it saves the model, so if I put it in save(), or a presave or postsave signal, it will result in infinite recursion. In the package, a signal is automatically executed when a Domain or Record is saved in the admin, but not anywhere else. I want to be able to run rectify_zone outside of the admin. At the moment I'm stumped. Can anyone help? Thanks in advance. -
Error : MultiValueKeyError at /quiz/2/11 'choice'
I am creating a multi-choice quiz app, I have created a view which shows the question and its 4 option I have given radio button to each option but is giving me this error:MultiValueDictKeyError at /quiz/2/11/ 'choice' views.py def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk=quiz_id) que = Question.objects.get(pk=question_id) ans = que.answer_set.all() selected_choice = que.answer_set.get(pk=request.POST['choice']) if selected_choice is True: come = que.rank came = come + 1 later_question = q.question_set.get(rank=came) return render(request,'app/question_detail.html',{'que':que , 'later_question':later_question, 'ans':ans}) else: come = que.rank later_question = q.question_set.get(rank=come) return render(request, 'app/question_detail.html', {'que': que, 'later_question': later_question, 'ans': ans}) question_detail.html <form action="{% 'app:detail' quiz_id=quiz.id question_id=que.id %}" method="post"> {% csrf_token %} {% for choice in que.answer_set.all %} <input type="radio" name="choice" id="choice{{forloop.counter}}" value="{{choice.id}}"> <label for="choice{{forloop.counter}}">{{choice.answer}}</label> {% endfor %} -
Django, Post Form Data Not Binding or Received By View
My view is not receiving and binding the data from the form. The goal of the form page is standard. Form Page loads without errors, user inputs data, if errors form is reloaded with prior user data and errors called out. If Form is valid it saves data to the DB. I have followed the Django Form documentation, and read through Stack Overflow threads, but have not been able to achieve the above behavior. FORM.PY from django import forms class templateForm(forms.Form): TemplateName = forms.CharField(max_length=50) Descriptions = forms.CharField(initial="User Name & Date") Contents = forms.CharField(required= False, max_length=50, widget=forms.HiddenInput()) CPU_Quantity = forms.IntegerField(initial=1) Memory_Quantity = forms.IntegerField(initial=12) VIEWS.PY class Add_Server_Template(View): def post (self, request): #If this is a POST then process the form data if request.method == 'POST': ### Binds user data to form form = templateForm(request.POST) if form.is_valid(): # <process form cleaned data> model_instance = form.save(commit=False) model_instance.save() return render(request, "Server_Template/index.html", {'form': form}) ### if form is not valid. Re-render form with user data. else: form = templateForm() return render(request, 'Server_Template/index.html', {'form': form}) URLS.PY url(r'serverstructure/add/$', views.Add_Server_Template.as_view(), name='serverStructure-Add'), TEMPLATE Configtempaltes.html {% extends 'Server_Template/base.html' %} {% block body %} {% load bootstrap4 %} <div class="container-fluid" > <div class="row"> <div class="col-sm-4 col-sm-offset-1" > <h3>Server Template</h3> </div> </div> <div … -
How to change filter queryset depends on user
I am using django-filter and I have two models CustomUser and Shop. How to change filter choices queryset so that user(request.user) can filter only his shops? User class CustomUser(AbstractBaseUser, PermissionsMixin): shop = models.ManyToManyField(Shop, blank=True, related_name='custom_user') Shop class Shop(models.Model): address = models.CharField(_('Address'), unique=True, max_length=64, blank=False, null=False, db_index=True) filters.py shops = Shop.objects.filter(is_active=True) SHOP_CHOICES = [('All', 'All')] for x in shops: SHOP_CHOICES.append((x.address, x)) SHOP_CHOICES = tuple(SHOP_CHOICES) class ShopFilter(django_filters.FilterSet): address = django_filters.MultipleChoiceFilter(choices=SHOP_CHOICES) class Meta: model = Shop fields = ['address'] views.py f = ShopFilter(request.GET) -
Django: drop-down-box
My forms.py has this: SIZE_CHOICES = ( ('s', 'Small'), ('m', 'Medium'), ('l', 'Large') ) class ChooseSize(forms.Form): size_choice = forms.ChoiceField(choices=SIZE_CHOICES) My product_page.html tries to implement this form: <form method="POST" class="card-body"> {% csrf_token %} <div> {{ form.size_choice }} </div> </form> For some reason size_choices doesn't show up on the web-page. What gives? -
DJANGO - Extract filtered data to excel
I have a view for filtering data and display it in a table. I would like to export the filtered data to excel. I wrote the view for exporting but I don't know how to connect the two. OrderFilter is a django-filter Views.py def data(request): orders= Order.objects.all() filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date','-Hour') return render(request, 'template.html',{'orders':orders,'filter': filter}) def export_data(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Hour', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Order.values_list('Date', 'Hour', 'Category', 'Item__Item') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response -
How to declare common variables for all methods of a Django class-based view?
I have a class-based view in my Django application and it works fine. But I guess it is not coded well, because it violates the DRY principle. Specifically, I have two absolutely similar declarations of the posts_list variable inside get() and post() methods: class TopicView(View): def get(self, request, topic_id): post_form = PostForm() posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date') return render(request, 'discussions/topic.html', {'posts_list': posts_list, 'post_form': post_form, 'topic_id': topic_id}) def post(self, request, topic_id): post_form = PostForm(request.POST) if post_form.is_valid(): post = post_form.save(commit=False) post.author = request.user post.topic = Topic.objects.get(pk=topic_id) post.save() return redirect('discussions:topic', topic_id=topic_id) posts_list = Post.objects.filter(topic_id=self.kwargs['topic_id']).order_by('-creation_date') return render(request, 'discussions/topic.html', {'posts_list': posts_list, 'post_form': post_form, 'topic_id': topic_id}) Is there a way how I can declare this variable as a class attribute instead of a simple variable inside each of the methods? When I declaring it, I use topic_id as a filter for objects, and I extract topic_id from the URL (self.kwargs object, self is passed to both get() and post() as an input parameter). This is the main issue. -
How do I display user profile pic if saved in custom directory?
I have created an app called users and have created a custom method called get_upload_path. I am using this method to allow users to upload profile pics to a custom path for better organization of images. What should I change in MEDIA_URL so that these images will be displayed on a custom template? users/models.py: from django.db import models from django.contrib.auth.models import User def get_upload_path(instance, filename): return '%s/%s' % (instance.user.username, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # make bio and other stuff here image = models.ImageField(default='default.jpg', upload_to=get_upload_path) def __str__(self): return f'{self.user.username} Profile' settings.py: # Directory where uploaded files will be saved MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' users/templates/users/profile.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.first_name }} {{ user.last_name }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <!-- FORM HERE --> </div> <p class="text-muted">Joined on: {{ user.date_joined|date:"F d, Y" }}</p> <p class="text-muted">Last logged in on: {{ user.last_login|date:"F d, Y" }}</p> {% endblock content %} File Structure: -
how to serve django with react frontend using webpack?
I used webpack to convert react to static files and render them in django templates but even though the static files are changed the website rendered by django is same -
Errors with models in django, creating events registration app
i am creating django app that allows users to register to different events. I created one Registration model in .models and added specific views but i have got some model errors. Wondered if anyone could help out a little? I am also not 100% sure if i have done all code correctly because i am quite new to django. Thanks a lot! Here is my model file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse import datetime class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) hardness_level = models.TextField(max_length=20, default='easy') author = models.ForeignKey(User, on_delete=models.CASCADE) location = models.CharField('location', max_length=150) info = models.TextField() starts = models.DateTimeField('Starts') ends = models.DateTimeField('Ends') arrive_when = models.DateTimeField('Arrival time', null=True, blank=True) arrive_where = models.CharField('Arrival location', null=True, max_length=150, blank=True) registration_starts = models.DateTimeField('Registration start') registration_limit = models.IntegerField('Guest limit', default=0, choices=[(0, u"No limit")] + list(zip(range(1, 100), range(1, 100))), on_delete=models.CASCADE()) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Meta: verbose_name = "event" verbose_name_plural = "events" ordering = ['-starts'] def __str__(self): if self.starts.date() != self.ends.date(): return u"%s, %s - %s" % (self.title, self.starts.strftime("%a %H:%M"), self.ends.strftime("%a %H:%M")) else: return u"%s, %s - %s" % (self.title, self.starts.strftime("%H:%M"), self.ends.strftime("%H:%M")) def get_registrations(self): return EventRegistration.objects.filter(event=self) … -
How to add a row ID in django-tables to get the selected radio button from the specific row
I am trying to use the jQuery to get the row that selected radio is in and also the selected radio button value when using django-tables2. So, I have three columns in a table and I rendered it with django-tables2. The third columns is templatecolumn with the HTML template (buttons.html: <form class="myForm"> <input type="radio" class="Yes" name="result" value="Yes"> <label for="Yes">Yes</label> <input type="radio" class="No" name="result" value="No"> <label for="No">No</label><br> </form> I then add templatecolumn to the table ( I created my own table class by inheriting from tables.Table): myTableCol={} mylist = [] for i in queryResults: mydic = {} for j in i: className=str(type(j)).split(".")[1] mydic.update({className: j.name}) myTableCol.update({className: tables.Column()}) mylist.append(mydic) myTableCol.update({'Action': tables.TemplateColumn(template_name="buttons.html", verbose_name=("Actions"), orderable=True)}) Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},}) myTableCol.update({'Meta':Meta}) QueryTable2=type('QueryTable', (tables.Table,), myTableCol) The table is then rendered using {% render_table table %} that gives the html below. I am trying to get which radio button that was selected for the row. $(document).ready(function () { $('input').click(function() { var $selectedButton = $('input[name=result]:checked').val(); var $row = $(this).closest("tr"); var $rowData = $row.children("td").map(function() { return $(this).text(); }).get(); alert($selectedButton); });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <div class="table-container"> <table class="paleblue"> <thead class="thead-default" > <tr> <th class="orderable"> <a href="?sort=UseCase">UseCase</a> </th> <th class="orderable"> <a href="?sort=MainFlow">MainFlow</a> </th> <th class="orderable"> <a href="?sort=Action">Actions</a> </th> </tr> </thead> … -
Android-Django image upload:- App closes after image capture, Caused by: java.lang.NullPointerException: uri
I am making an Android app to capture an image and upload to Django development server, which will do some decoding on the uploaded image. Following are my Android side codes: MainActivity.java package com.example.original; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import androidx.loader.content.CursorLoader; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.original.apiinterface.APIInterface; import com.original.decoder.response.MyResponse; import java.io.File; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.provider.Settings; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.File; import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class MainActivity extends AppCompatActivity { Button camera_open_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); camera_open_id = (Button)findViewById(R.id.camera_button); camera_open_id.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent camera_intent = new Intent(MediaStore .ACTION_IMAGE_CAPTURE); startActivityForResult(camera_intent, 100); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 100 && resultCode == RESULT_OK && data != null) { //the image URI Uri selectedImage … -
HttpResponseRedirect в Django. Can't do redirect on 'done' page
After filling the page should appear 'done', but i have a error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/candidate/done.html The current path, candidate/done.html, didn't match any of these. Can't configure redirect to 'done' page. Here views.py: from django.http import Http404, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import AnketaForm from .models import Anketa def anketa_create_view(request): if request.method == 'POST': form = AnketaForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('candidate/done.html') else: form = AnketaForm() return render(request, 'candidate/anketa_create.html', {'form': form}) urls.py (apps/candidate) from django.urls import path from . import views urlpatterns = [ path('', views.anketa_create_view, name = 'anketa_create_view'), ] urls.py from django.contrib import admin from django.urls import path, include from candidate.views import anketa_create_view urlpatterns = [ path('done/', anketa_create_view), path('', anketa_create_view), path('grappelli/', include('grappelli.urls')), path('admin/', admin.site.urls), ] -
How can I show auto_now_add field in Django admin?
I have a model (as below) and in that, I've set auto_now_add=True for the DateTimeField class Foo(models.Model): timestamp = models.DateTimeField(auto_now_add=True) From the doc, As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set. Q: How Can I show this auto_now_add field in Django Admin? (by default Django Admin doesn't show auto_now_add fields) -
Where does the value 'form' in 'form.as_p' in Django template come from?
I know this question was asked before, but the accepted answer does not really answer the question: where `form.as_p`in django templates come from? In Django doc: Example myapp/views.py: from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] Example myapp/author_form.html: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> The question is, where does the template get the 'form' context from, since we did not explicitly define a render() function inside the AuthorCreate class? Thanks. -
Django: Select a valid choice. <choice> is not one of the available choices
I'm trying to make use a choice field to all users to add permissions to a role. The permissions are defined in their own class and are displayed in the drop-down box correctly, however when submitting the form, it says that the option selected isn't an available choice. forms.py from django import forms from .models import RolePermission, Permission class AddPermissionForm(forms.ModelForm): class Meta: model = RolePermission fields = ['permission'] permission = forms.ChoiceField(choices=Permission.choices) def __init__(self, *args, **kwargs): super(AddPermissionForm, self).__init__(*args, **kwargs) self.fields['permission'].widget.attrs.update({'class': 'form-control'}) views.py def role_view(request, role_id): role = Role.objects.get(id=role_id) add_permission_form = AddPermissionForm(request.POST) if request.method == 'POST' and add_permission_form.is_valid(): new_permission = add_permission_form.cleaned_data['permission'] # is_already_permission = RolePermission.objects.filter(role_id=role_id, permission=new_permission) # if is_already_permission: new_role_permission = RolePermission(role_id=role_id, permission=new_permission) new_role_permission.save() return redirect('core:role_view role_id=role_id') return render(request, 'role_view.html', {'role': role, 'form': add_permission_form}) Permissions class class Permission(models.TextChoices): PAGE_CREATE = 111 PAGE_EDIT = 112 PAGE_PUBLISH = 113 PAGE_DELETE = 114 I've tried changing the choice field to a select field, but that doesn't solve the problem. -
Use a single function for multiple serializer fields with different arguments
I have a serializer for a model with an image field, for which I have saved multiple different sized thumbnail images. I access them by returning their URL using the SerializerMethodField: class GalleryImageSerializer(serializers.ModelSerializer): image_sm = serializers.SerializerMethodField() image_md = serializers.SerializerMethodField() image_lg = serializers.SerializerMethodField() image_compressed = serializers.SerializerMethodField() def get_image_sm(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/sm.jpg') def get_image_md(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/md.jpg') def get_image_lg(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/lg.jpg') def get_image_compressed(self, obj): return default_storage.url(f'{splitext(obj.image.name)[0]}/compressed.jpg') This code works, but it kind of violates the "don't repeat yourself" guideline. As you can see, these are all duplicate SerializerMethodFields, with the only difference being the filename, eg 'lg.jpg', 'md.jpg', etc. I'd much prefer to have only one function that I call with an argument for the filename, as an example(pseudocode): class GalleryImageSerializer(serializers.ModelSerializer): image_sm = serializers.SerializerMethodField(filename='sm.jpg') image_md = serializers.SerializerMethodField(filename='md.jpg') image_lg = serializers.SerializerMethodField(filename='lg.jpg') image_compressed = serializers.SerializerMethodField(filename='compressed.jpg') def get_image(self, obj, filename=''): return default_storage.url(f'{splitext(obj.image.name)[0]}/{filename}') Currently I am unable to find any way to achieve this. Reading the source code of SerializerMethodField, it doesn't seem to support it. Is there any way to avoid creating duplicate functions for fields with arbitrary differences? -
Django Form Instance not showing the Uploaded Image
I am making a CMS platform in Django. I want to create the EDIT Post method so that anyone can edit their post. The main problem is the ImageField. As ImageField is required in Django's Models.py.So, while creating edit Post method for the user the ImageField, the image which was uploaded at the time of post creation, is empty. Here is Edit Post View def updatePost(request,pk): getEditPost= get_object_or_404(Post,pk=pk) if request.method=="POST": form = CkEditorForm(request.POST,request.FILES,instance=getEditPost) try: if form.is_valid(): form.save() except Exception as e: print(e) else: form = CkEditorForm(instance=getEditPost) context= { 'myForm':form, 'post':getEditPost, } return render(request,"post/editPost.html",context) Here is my forms.py class CkEditorForm(ModelForm): ..... ..... featuredImage = forms.ImageField(required=True) My models.py class Post(models.Model): ..... ..... featuredImage = models.ImageField(upload_to="featured_image/")