Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a field thats connected with another in Django
The thing is that I'd like to create a field with a title that shows available titles depending on the artist's choice in the field above. For example, if a user selects "Drake" in the artist field, only the titles for that artist will be displayed in the title field. I'm completely stuck. Could you give me a hint how to solve the problem? I was wandering if I have to change my models.py by adding some kind of One-To-Many relationship or is there diffrent method? Webpage: enter image description here My models.py file: from django.db import models class SpotifyData(models.Model): title = models.CharField(max_length=60) rank = models.IntegerField() date = models.DateField() artist = models.CharField(max_length=60) region = models.CharField(max_length=20) chart = models.CharField(max_length=8) streams = models.IntegerField() class Meta: indexes = [ models.Index(fields=['title']), models.Index(fields=['rank']), models.Index(fields=['date']), models.Index(fields=['artist']), models.Index(fields=['region']), models.Index(fields=['chart']), ] My view.py file: import plotly.express as px import plotly.graph_objects as go from django.shortcuts import render from spotify_data.models import SpotifyData from spotify_data.charts import (make_song_rank_changes_chart, ) from typing import Any, Dict from django.views.generic import TemplateView from django.views.generic.list import ListView class HomeView(ListView): model = SpotifyData context_object_name = "record" def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) context["records_all"] = SpotifyData.objects.all().count() return context class SongRankChangesChart(TemplateView): model = SpotifyData context_object_name = … -
Is it possible with Django to have a global view that is called on every page?
I was wondering if it is possible with Django to have a "global view" that is called on every page before all the initial views, for example to display additional information other than the user's information. All of this to avoid having to call a model on all of my views. To allow me to call it only once. -
`pytest-django` tables are emptied when used with `live_server`
I need prevent the tables from being emptied after each test, which is the default behavior when the tests are defined as below. Note: I populate the User table before running the tests, that's why the below works. class TestViews: @staticmethod def test1(django_user_model): assert django_user_model.objects.count() > 0 @staticmethod def test2(django_user_model): assert django_user_model.objects.count() > 0 result: ============================= test session starts ============================== collecting ... collected 2 items test_live_server.py::TestViews::test1 test_live_server.py::TestViews::test2 ============================== 2 passed in 7.86s =============================== Process finished with exit code 0 However, when live_server fixture is included: class TestViews: @staticmethod def test1(django_user_model, live_server): assert django_user_model.objects.count() > 0 @staticmethod def test2(django_user_model, live_server): assert django_user_model.objects.count() > 0 all model tables are emptied after each test. ============================= test session starts ============================== collecting ... collected 2 items test_live_server.py::TestViews::test1 test_live_server.py::TestViews::test2 PASSED [ 50%] FAILED [100%] tests/test_live_server.py:5 (TestViews.test2) 0 != 0 Expected :0 Actual :0 <Click to see difference> django_user_model = <class 'django.contrib.auth.models.User'> live_server = <LiveServer listening at http://localhost:61926> @staticmethod def test2(django_user_model, live_server): > assert django_user_model.objects.count() > 0 E AssertionError: assert 0 > 0 E + where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>>() E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>> = <django.contrib.auth.models.UserManager object at 0x10d83fc90>.count E + where <django.contrib.auth.models.UserManager object … -
Django AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
The problem just appeared now. When I try to ./docker-compose.sh development up my django application, and after the ./manage.py collectstatic I see the error: => ERROR [6/6] RUN EXTRA_SETTINGS_URLS=/usr/src/app/dummy_external_settings.yml ./manage.py coll 3.2s ------ > [6/6] RUN EXTRA_SETTINGS_URLS=/usr/src/app/dummy_external_settings.yml ./manage.py collectstatic: #0 2.996 Traceback (most recent call last): #0 2.996 File "/usr/src/app/./manage.py", line 15, in <module> #0 2.997 execute_from_command_line(sys.argv) #0 2.998 File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line #0 2.998 utility.execute() #0 2.998 File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute #0 2.999 django.setup() #0 2.999 File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup #0 3.000 apps.populate(settings.INSTALLED_APPS) #0 3.000 File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate #0 3.000 app_config = AppConfig.create(entry) #0 3.000 File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create #0 3.000 import_module(entry) #0 3.000 File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module #0 3.001 return _bootstrap._gcd_import(name[level:], package, level) #0 3.001 File "<frozen importlib._bootstrap>", line 1030, in _gcd_import #0 3.002 File "<frozen importlib._bootstrap>", line 1007, in _find_and_load #0 3.002 File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked #0 3.002 File "<frozen importlib._bootstrap>", line 680, in _load_unlocked #0 3.003 File "<frozen importlib._bootstrap_external>", line 850, in exec_module #0 3.003 File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed #0 3.003 File "/usr/local/lib/python3.9/site-packages/ucamwebauth/__init__.py", line 7, in <module> #0 3.004 from OpenSSL.crypto import FILETYPE_PEM, load_certificate, verify #0 3.004 … -
"python manage.py makemigrations" command is not executing in a production environment
i have a live database and i have committed my models.py file in live server using git push. after login into the live server by using ssh (1) when i run python3 manage.py makemigrations i get this error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (2) when i run python manage.py makemigrations i get this error: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax How to run migrations in a production environment? Any help will be more valuable for me i have committed my models.py file using git push, then i have tried to run python manage.py makemigrations. i want my changes to be applied in production environment. -
Django How to use drf-yasg in class-base view which is parent of all other views to generate swagger docs?
I'm trying to add swagger to my project so drf-yasg was the option with @swagger_auto_schema, but I'm using a baseView view which is parent class view for all other views, thus all HTTP methods are written in baseView, so that children views doesn't need to implement these methods. the problem is that when I added @swagger_auto_schema to baseView methods it didn't see the child attributes but the baseView's attributes. The baseView: class BaseView(APIView): model = models.Model serializer_class = serializers.Serializer description = '' id = openapi.Parameter('id', in_=openapi.IN_QUERY, type=openapi.FORMAT_UUID) @swagger_auto_schema(manual_parameters=[id] ,responses={200: serializer_class},operation_description=description) def get(self, request, id=None, **kwargs): .... @swagger_auto_schema(request_body=serializer_class) def post(self, request, **kwargs): .... Then let's say I have this child view: class TestApi(BaseView): model = test description = 'This is test api' serializer_class = TestSerializer In this approach Swagger are show empty values for description and serializer_class because it doesn't see child values how to solve this without have to configure each view with HTTP methods and @swagger_auto_schema. thank you in advance. -
How to integrate VISA, MASTERCARD payment in my Django website project [closed]
I want to add this payment option to my website, how do i integrate the VISA, mastercard API to my website ,,, a step to step guide will be helpfulenter image description here -
How to create a form with fields for all instances of another model in Django?
I'm new to Django and I'm currently trying to create a form which should contain input fields for all existing objects of another model. Let's say that I would like to manage my supplies at home and make sure that I have enough of various products at diffect storage locations. For example, I would like to make sure that the storage locations bathroom and basement should always have plenty of the supply toilet paper. I don't need toilet paper in the location kitchen. The storage locations are pre-defined and available through a model. I couldn't find any way to create a form for Supply which dynamically generates form fields for MinimumQuantity objects based on all available StorageLocation objects. My form should look like this when creating the supply "toilet paper": supply name: <input example: "toilet paper"> minimum supply quantities bathroom - amount: <input example: 6> kitchen - amount: <input example: 0> basement - amount: <input example: 3> I'm a bit lost here and any hints would be much appreciated. This is my current code (shortened): models.py: class Supply(models.Model): name = models.CharField(max_length=50) class StorageLocation(models.Model): name = models.CharField(max_length=50) class MinimumQuantity(MinimumQuantity): storage_location = models.ForeignKey(StorageLocation, on_delete=models.PROTECT) supply = models.ForeignKey(Supply, on_delete=models.PROTECT) amount = models.IntegerField() views.py: … -
How to transfer date from form to django code (datepicker form to value (htmx))?
Good good evening! I have a standard datepicker form. I'm trying to figure out how to take the start and end date values. At least one date value from the form to use in various Python calculations. I have a data table where the data is sorted by date. And I need to take only certain rows from the given table. Having values in code. I need to somehow capture the date value and send this value to the code. Maybe there are some modern methods for taking data from an html or htmx form? I have been thinking for a long time how and what can be done in order to take data from a form and put it into code for some kind of calculation processing. I would be very grateful for any hints, help. models.py from django.db import models class Offer(models.Model): expiration_date = models.DateField(null=True) forms.py from django import forms from django.forms import ModelForm from .models import Offer class DateInput(forms.DateInput): input_type = 'date' class OfferForm(forms.ModelForm): class Meta: model = Offer fields = fields = '__all__' widgets = { 'expiration_date': DateInput(), } template <form action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form|crispy }} <input type="submit" name="submit" value="Submit"> </form> -
Openedx Sometimes throws Internal Server error while calling “api/courseware/sequence” api
we have installed openedx with tutor and we are making one edu-tech platform where it is using openedx apis and maintaining its own database at the same time on another django-project in docker. our edu-tech django-project docker is communicating with openedx apis, and sometimes openedx returns 500 Internal Error while i calling /api/courseware/sequence/{{block_key}} api. then i traced the exception from tutor local lms logs, this is exception made by openedx-lms. NOTE: It happens only sometimes lms_1 | 2023-01-02 18:32:42,511 ERROR 19 [django.request] [user 42] [ip 172.18.0.14] log.py:224 - Internal Server Error: /api/courseware/sequence/block-v1:SOS+CSE-10+2022_r1+type@sequential+block@b9aad4acdd1f48259c3dfd92fdc216c2 lms_1 | Traceback (most recent call last): lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner lms_1 | response = get_response(request) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response lms_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) lms_1 | File "/opt/pyenv/versions/3.8.12/lib/python3.8/contextlib.py", line 75, in inner lms_1 | return func(*args, **kwds) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view lms_1 | return view_func(*args, **kwargs) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view lms_1 | return self.dispatch(request, *args, **kwargs) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch lms_1 | response = self.handle_exception(exc) lms_1 | File "/openedx/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch lms_1 | response = handler(request, *args, **kwargs) lms_1 | File "/openedx/edx-platform/./openedx/core/djangoapps/courseware_api/views.py", line … -
Waiting list db model desgin
I am creating a web app using Django, which ultimately will allow users to take up certain activity over some period of time. However, each day has a maximum capacity of users for an activity. This means, that all the activities requested for a given day, that are over this limit, should be put in a waiting list. Right now, my models are like this: Activity model: class Activity(models.Model): user = models.ForeignKey( 'User', related_name="user", ) activity_type = models.ForeignKey( "Activity_type", null=True, blank=True ) start_date = models.ForeignKey("Calendar") end_date = models.ForeignKey("Calendar") Calendar model: class Calendar(models.Model): date = models.DateField() limit = models.IntegerField() Please note that those are only fields relevant for the problem and there are more fields in those as well. As you can see, Activity entity has a start_date and end_date fields, which represent when the user will start and end his activity. Now, note that every DAY in the Calendar entity has it's own limit. This means, that we should put this activity to the waiting list but only for this day. How would you approach such a design? I thought of something like so: class WaitingList(models.Model): activity = models.ForeignKey('Activity') date = models.ForeignKey(Calendar) enlist_date = models.DateTimeField(default=datetime.now) But this means that if … -
Groupby using Django's ORM to get a dictionary of lists from the queryset of model with foreignkey
I have two models, Business and Employee: from django.db import models class Business(models.Model): name = models.CharField(max_length=150) # ... class Employee(models.Model): business = models.ForeignKey( Business, related_name="employees", on_delete=models.CASCADE, ) name = models.CharField(max_length=150) # ... Here's a sample data: Business.objects.create(name="first company") Business.objects.create(name="second company") Employee.objects.create(business_id=1, name="Karol") Employee.objects.create(business_id=1, name="Kathrine") Employee.objects.create(business_id=1, name="Justin") Employee.objects.create(business_id=2, name="Valeria") Employee.objects.create(business_id=2, name="Krista") And I want to get a dictionary of lists, keys being the businesses and values being the list of employees. I can do so using prefetch_related on the Business model. A query like this: businesses = Business.objects.prefetch_related("employees") for b in businesses: print(b.name, '->', list(b.employees.values_list("name", flat=True))) Which gives me this: first company -> ['Karol', 'Kathrine', 'Justin'] second company -> ['Valeria', 'Krista'] And this is exactly what I want and I can construct my dictionary of lists. But the problem is that I only have access to the Employee model. Basically I only have a QuerySet of all Employees and I want to achieve the same result. I figured I could use select_related, because I do need the business objects, but this query: Employee.objects.select_related("business") Gives me this QuerySet: <QuerySet [<Employee: Employee object (1)>, <Employee: Employee object (2)>, <Employee: Employee object (3)>, <Employee: Employee object (4)>, <Employee: Employee object (5)>]> And I don't … -
Django wanted to use existing student.db
Can anyone share me a tutorial on how to connect this .db file to django project Thanks in advance I tried to connect via dbshell im new to this can any1 help -
'cannot write mode RGBA as JPEG' when saving image
I'm getting: OSError at /admin/blog/post/add/ cannot write mode RGBA as JPEG error when uploading an image file other than 'jpeg' with Pillow. This is the function I'm using to resize the image: def resize_image(image, size): """Resizes image""" im = Image.open(image) im.convert('RGB') im.thumbnail(size) thumb_io = BytesIO() im.save(thumb_io, 'JPEG', quality=85) thumbnail = File(thumb_io, name=image.name) return thumbnail Most solutions to this same error seem to be solved by converting to 'RGB', but I'm already doing that in my function except it still keeps giving error when uploading, for example, a .png image. How can I fix it? -
djangoCMS : Resources and Flow
Could anyone please suggest me any flow for learning djangoCMS and any video tutorials/articles. I have good knowledge of both python and django. I was suggested to learn the djangocms framework for my internship. When I looked into the documentation i thought it will be easy to understand. But I am not getting anything from it. I am in full confusion to understand (sometimes even when i typed the same code in documentation i am not getting the same result shown in documentation) Thanks in advance. -
(Python) have existing "mySQL Database" and "website", want to connect/synchronize both part
Main problem: I have existing mySQL Database and website, how do I connect/synchronize both, that input or update from mySQL, can also result in website too I did learn HTML, CSS but was required to find the way, instead input from <p> </p>, need to find a way CRUD from mySQL, and result to website after a day of research, python django seems has the possiblity solve my problem, but all the tutorial is buttom up create an new website and new mySQL, I'm stock on connecting existing one (that the "mySQL Database" and "website"), that how far I reach , therefore want to ask the export in here, thanks environment: I'm using python, window and mySQL the already set website screenshot the existing mySQL Database screenshot (MySQL Database, and using HeidiSQL ) -
Is it possible to connect AWS Dynamodb with django, I'm trying to connect more than a week. Will anybody find solution with this
I can able to create table in dynamodb using django, but I keep on gettin g configural error while I migrate the errror is- (django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.) will anyone has idea about settings.py configuration in django. some one says we django cannot access nosql but I configured Mongodb and cassendra I'm trying to migrate and runserver , while migration i'm getting (django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.) when i run the server i get Object 'EXCLUDE' is not a valid value for the 'unknown' parameter -
how to add form as data in class-base views?
I used to send form as content in function-base-view and I could use for loop to simply write down fields and values like: {% for x in field %} <p>{{ x.label_tag }} : {{ x.value }} </p> I don't remember whole the way so maybe I wrote it wrong but is there anyway to do this with class-based-views, because when I have many fields its really hard to write them 1by1 -
How to send back a numerical value to Django serialiser to display as JSONResponse?
I have a function that calculates a value from Django models/data. def protein_coverage(request, protein_id): try: proteins = Protein.objects.filter(protein_id=protein_id) domain_length = 0 for protein in proteins.all(): protein_length = protein.protein_length for protein_domains in protein.protein_domains.all(): length = protein_domains.stop - protein_domains.start domain_length += length coverage = domain_length / protein_length except Protein.DoesNotExist: return HttpResponse({'message': 'This Protein does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ProteinCoverageSerializer(coverage) return JsonResponse(serializer.data,safe=False) serializer: class ProteinCoverageSerializer(serializers.ModelSerializer): class Meta: model = Protein fields = ('coverage',) lookup_field = 'protein_coverage' 'coverage' is correctly calculated, I can print it. I just don't know how to display it as JSON response, I get errors like: ImproperlyConfigured at /api/coverage/xxx Field name `coverage` is not valid for model `Protein`. How can I display this calculated numerical value as a JSONresponse? -
how to make alert pop up in html while error in django function
I have a function, where if the function has an error in it, a "wrong key" message will pop up in the html. I tried to use messages, but it has a condition that it must use request. because i call this messages inside the function, so there is no request. how can I display the "wrong key" pop up, if the iv cannot be used/wrong? I use try and except, so if it can't be processed, then except runs. here's my function code: def decrypt(cipher_text, key): if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" assert len(key) == key_bytes private_key = hashlib.sha256(key.encode("utf-8")).digest() cipher_text = base64.b64decode(cipher_text) try: iv = cipher_text[:16] cipher = AES.new(private_key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(cipher_text[16:]).decode('utf-8')) except: print("WRONG PASSWORD") messages.error(request, 'wrong key!') return redirect('decode') here's my html: {% for message in messages %} <div class="alert alert-warning" role="alert" id="some_flag"> <a class="close" href="#" data-dismiss="alert">×</a> {{message}} </div> {% endfor %} -
Second Model form is over riding the first model form of same model Django
Hello i am having an issue in django forms. i am passing 2 forms in a same view. these both forms are model forms with the same fields and same model as well. the code is: class IncomingOrderForm(forms.ModelForm): class Meta: model = connector_models.Order fields = ['message_type', 'position', 'field'] widgets = { "message_type": forms.TextInput( attrs={"data_icon": "fa fa-envelope", "required": "", "col_cls": "col-md-4"}), "position": forms.TextInput( attrs={"data_icon": "fa fa-hashtag", "required": "", "type": "number", "col_cls": "col-md-4", "value": "0"}), "field": forms.TextInput(attrs={"data_icon": "fa fa-keyboard", "required": "", "col_cls": "col-md-4"}) } class OutgoingOrderForm(forms.ModelForm): class Meta: model = connector_models.Order fields = ['message_type', 'position', 'field'] widgets = { "message_type": forms.TextInput( attrs={"data_icon": "fa fa-comment", "required": "", "col_cls": "col-md-4"}), "position": forms.TextInput( attrs={"data_icon": "fa fa-hashtag", "required": "", "type": "number", "col_cls": "col-md-4", "value": "0"}), "field": forms.TextInput(attrs={"data_icon": "fa fa-keyboard", "required": "", "col_cls": "col-md-4"}) } i am showing these both forms in a same view for getting 2 different entries. for example i am typing values for incoming form: message_type : 'A',position :1, field:1 and for outgoing form:message_type : 'B',position :2, field:2 and when i save these forms it saves outgoing form entries 2 times instead of saving both forms once please give me any solution, thanks in advance -
ordering is not working with django model seralizer
I am using 2.2.16 django versiong and 3.11.2 django_rest_framework version and using serializers.ModelSerializer CRUD operation is working but ordering is not working. models.py code is below, class Ticket(models.Model): title = models.CharField(max_length=255) description = models.CharField(blank=True, max_length=255) notes = models.TextField() eg: code in seralizers.py from rest_framework import serializers class Ticket(serializers.ModelSerializer): title = serializers.CharField() description = serializers.CharField(required=False) notes = serializers.CharField(required=False) class Meta(object): fields = '__all__' depth = 1 model = Ticket ordering_fields = ["title"] def __init__(self, *args, **kwargs): super(Ticket, self).__init__(*args, **kwargs) When i do GET operation as below, ordering is not working with query parameters eg: http://localhost:4200/api/ticket?ordering=title Above api call is returning add data with default ordering as ID (auto created field), but not returning in the assenting of title field (which is a char field). How can I fix this? Also how can i add filtering to the same eg: http://localhost:4200/api/ticket?title=abc # this should give me result of only matching title field with abc or starts with abc -
I want a logged in user to see only its saved information
I just started learning django. i created a model and i expect when a user logs in, the user should see only info it saved but when another user logs in, it sees saved information from other users view.py def user_locker(request): saved_info = Locker.objects.all() all_saved_info = {'saved_info': saved_info} return render(request, 'pwdbank/user_locker.html', all_saved_info) model.py class Locker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) site_name = models.CharField(max_length=55) site_url = models.URLField(max_length=55) username = models.CharField(max_length=55) email = models.EmailField(max_length=100) password = models.CharField(max_length=55) created_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now=True) def __str__(self): return f'{self.site_name}' Thank you. Please Help! -
django.core.exceptions.ImproperlyConfigured
`I have watched a tutorial. But that was an old version of Django 1.1 and now I am using Django 4.1.So there is a problem that is telling me about django.core.exceptions.ImproperlyConfigured: "post/(?\d+)$" is not a valid regular expression: unknown extension ?<p at position 6. I didn't get it what it was views.py from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from blog.models import Post,Comment from blog.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView,DetailView,DeleteView,CreateView,UpdateView) # Create your views here. class AboutView(TemplateView): template_name = 'about.html' class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class PostDetailView(DetailView): model = Post class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class PostUpdateView(LoginRequiredMixin,UpdateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('created_date') class PostDeleteView(LoginRequiredMixin,DeleteView): model = Post success_url = reverse_lazy('post_list') ####################################### ## Functions that require a pk match ## ####################################### @login_required def post_publish(request, pk): post = get_object_or_404(Post, pk=pk) post.publish() return redirect('post_detail', pk=pk) @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = … -
What's the difference between Cleaned data and is valid in django
What is the difference between cleaned_data and is_valid functions in django?, I just came across forms and immediately i got stuck there can anyone play with some simple examples. I've read many documentation but i cant able to differentiate it.