Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add value to a many-to-many field in Django
Suppose I have a relation as down below: class Student(models.Model): firstname lastname ... class Teacher(models.Model): firstname lastname email ... class Meeting(models.Model): student = models.ManyToManyField(Student) teacher = models.ManyToManyField(Teacher) How should I add/set a value to field 'student' or 'teacher'. I tried to assign an object from related models to them but got an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use student.set() instead. -
How do I overwrite the variable from cleaned_data
I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved. if request.method == 'POST': form_w = ImageForm(request.POST, request.FILES) if form_w.is_valid(): form = form_w.save(commit=False) cd = form_w.cleaned_data['img'] im = Image.open(cd) width, height = im.size draw = ImageDraw.Draw(im) text = "TEST WATERMARK" font = ImageFont.truetype('arial.ttf', 36) textwidth, textheight = draw.textsize(text, font) margin = 10 x = width - textwidth - margin y = height - textheight - margin draw.text((x, y), text, font=font) im.save('Luki/media/upload_p/{}'.format(cd)) form.save() return redirect('Luki:gallery') else: form = ImageForm() return render(request, 'Luki/upload_img.html', { 'form': form, }) -
Django admin panel not showing related foreign key correctly - Postgresql
I'm new to Django. I've defined 2 tables and have set a foreign key. So I want to link the column note from table Comment to the column id from table Note. As I'm using PostgreSQL, when I check the psql shell, the name of the column note will be displayed as note_id. So for using in template, if I use something like comment.note, it prints the "quick_note" of the note table, which I don't want that. I want to get the "id" of the related post to the current comment, not the quick_note of the related post. But if I use something like comments.note_id, it shows the id of the related post, which is what I expect to get. Also in the admin panel, I see a field of note: that shows related quick_note not id. How can I fix it that admin panel show the related id? So here I want the id of related post to be shown in front of note:. This is my model.py: class Note(models.Model): title = models.CharField(max_length=100) quick_note = models.CharField(max_length=500) pub_date = models.DateTimeField('date published') author = models.CharField(max_length=100) class Comment(models.Model): text = models.CharField(max_length=200) note = models.ForeignKey(Note, on_delete=models.CASCADE) pub_date = models.DateTimeField('date published') -
Run Celery Task For Past Timestamps
My app was running celery tasks on daily basis. It faced an outage due to some server issues. This made a blank windows in between the tasks. Can somebody let me know if running celery tasks for past timestamps is possible to fill up those gaps? -
The comment form is displayed incorrectly
I am making comments on django on this video https://www.youtube.com/watch?v=bmFkND-scpY when the author in the middle of the video showed what he had done, he showed this (this is how it should be) enter image description here but for some reason it turned out like this enter image description here class Comment in models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255, default="Some String") body = models.TextField(max_length=255, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) forms.py from django.forms import ModelForm from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['name', 'body'] def detail in views.py def detail(request, slug): post = Post.objects.get(slug=slug) form = CommentForm() context = { 'post': post, 'form': form } return render(request, 'myblog/templates/post_detail.html', context) post_detail.py {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p> <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p> <img src="{{ post.header_image.url|default_if_none:'#' }}"> {{ post.body|urlize }} {% for comm in post.commentpost_set.all%} {{ comm.user }} <br> {{ comm.text }} <br><br> {% endfor %} <article class="content"> <br><hr> <h2>Add a comment</h2> <form method="post" action="."> {% csrf_token %} {{ … -
Extending django User Model (Unable to add extra fields)
Here is the code files. admin -> init__.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from usermanagement.models import UserProfile scrumboard_models = [models.Board, models.Setting, models.CheckList, models.CheckListItem, models.Comments, models.Subscribers, models.Lists, models.Label, models.Card, models.Attachment, models.Team] admin.site.register(scrumboard_models) class UserProfileAdmin(UserAdmin): list_display = ( 'id', 'first_name', 'username', 'email', 'is_active', 'dob' ) admin.site.register(UserProfile, UserProfileAdmin) **Settings.py** """ Django settings for app project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent import datetime JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600), } # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'v!t5abxm^t@tyj=z5gp!*_%qy=$q-d6g!4zx(!r3_nn)7h^ee7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'scrumboard', 'admin_app', 'whitenoise.runserver_nostatic', 'corsheaders', 'usermanagement', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': … -
How to compare IntegerChoice values in Django Templates
I intend to compare the value of an IntegerChoice inside Django Template : class SomeModel(models.Model): class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') __empty__ = _('(Unknown)') answer = models.IntegerField(choices=Answer.choices) SomeModel.objects.create(answer=0) somemodel = SomeModel.objects.filter(answer=0) Inside template : {% if somemodel.answer == SomeModel.Answer.YES %} ... {% else %} <h1>{{ SomeModel.get_answer_display() }}</<h1> {% endif %} Yet, this does not get inside the true if case, and also does not like "()" at the end of "SomeModel.get_answer_display" with the following message : Could not parse the remainder: '()' from 'SomeModel.get_answer_display()' How can I make the filter work as expected? -
How to store multiple records in single column using python and postgresql?
Was going through calorie counter made with django. there are two columns each store multiple records like if food.weight==100 gram: calorie will be 56 fat will be something.. sugar will be something if food.weight==1tbsp: calorie will be 2 fat will be something.. sugar will be something if food.weight == 1oz: calorie will be 0 fat will be something.. sugar will be something means multiple data are being stored in single column (food.weight) and those data are related to other data of other column (calorie/fat/sugar) (i think similar results can be found with number of relational table , like if i create a separate model for each type of food.weight ) How can i achieve this. I am a new django learner developed some initial projects. Btw i am from a different background ...no where near to comupter science and learning all by myself... Please suggest what i need to learn to solve this above mentioned problem...(I am learning python and django) -
How to save data to ManyToManyField in django?
I have a question concerning the following model. I want to populate the ManyToManyField from views.py instead of doing it from the Admin. But how do I add data to the cylinder field which is the ManyToManyField? Your help will be nice for me. Here are that codes: views:- def issue(request): form=IssueForm() if request.method=='POST': form=IssueForm(data=request.POST,files=request.FILES) if form.is_valid(): confirm=form.save(commit=False) confirm.save() form.save_m2m() return redirect(cylinderListView) return render(request,'cylinderentry_form.html',{'form':form}) models: class CylinderEntry(models.Model): substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued'), ] cylinderId=models.CharField(max_length=50,primary_key=True) Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def __str__(self): return str(self.cylinderId) class IssueCylinder(models.Model): cylinder=models.ManyToManyField('CylinderEntry') userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) form: class IssueForm(forms.ModelForm): class Meta: model=IssueCylinder fields=['cylinder','userName','issueDate'] cylinder= forms.ModelMultipleChoiceField( queryset=CylinderEntry.objects.all(), widget=forms.CheckboxSelectMultiple ) userName=forms.CharField() issueDate=forms.DateInput() -
Is there a possibility to set property to swagger_auto_schema resquest_body please?
I want to pass a list to admin parameter at the bottom, but it ask to set items and I do not know how ? It get an error @swagger_auto_schema( operation_description="Modification d'une boutique d'un utilisateur", method='PUT', request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'name': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'description': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'logo': openapi.Schema(type=openapi.TYPE_FILE, description='file'), 'cover_picture': openapi.Schema(type=openapi.TYPE_FILE, description='file'), 'category': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'phone_number': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'email': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'coords_lat': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'coords_lng': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'audio': openapi.Schema(type=openapi.TYPE_FILE, description='file'), 'address': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'admin': openapi.Schema(type=openapi.TYPE_ARRAY, description='array', items=UsersSerializer), } ) ) -
Django rest_framework dynamic selecting other objects
i want to create an Api for an order system. I have Ingredients and Products, both have categories which have to match if you want to combine them. So if a user selects a Pizza how can I only load in the ingredients which are available for Pizza, so the user cant select pasta as a Topping on his Pizza. So if the User selects a Product pizza in extra and extraWo only the ingredients should show up, which are available for pizza Thank you for your help -
status 415 image upload DRF
why i get 415 response when try to post by code? having no problems with browser upload. class UploadImageView(generics.CreateAPIView): parser_classes = [MultiPartParser] queryset = Image.objects.all() serializer_class = ImageSerializer class ImageSerializer(serializers.ModelSerializer): class Meta: fields = ('image', 'tags') model = Image def create(self, validated_data): image = Image.objects.create(**validated_data) return image first try: data = {'tags': 'testtag', 'image': '/home/Test/test.png'} second: data = {'tags': 'testtag', 'image': b'\x89PNG\r\n\x1a\n......\x82'} resp = requests.post(url, data=data) Also tried BytesIO object with the same result. Response 415 - Unsupported Media Type -
How to arrange data according status=True in django
I want to display card first which have status=True, so how can i arrange it by status in my views.py or in template this is my views.py: def myItem(request): context = {} if Item.objects.filter(status=True).exists(): context['data'] = Item.objects.all()#here i am taking all data but i want to arrange it so that which data have status=True will come first. else: context['data'] = Item.objects.all() context['data_false'] = True return render(request,'frontend/myeoffice.html',context) this is in my Template: {% for i in data %} {% if i.status %} <div class="col-xl-4"> <div class="card shadow-sm p-4"> <div class="card-header p-0 text-center"> <h2 class="title">{{i.name}}</h2> </div> <div class="content text-break p-2"> <p class="copy">{{i.description|truncatechars:100}}</p> </div> <div class="card-footer text-left p-0"> <button class="btn btn-primary m-3">View</button> </div> </div> </div> {% else %} <div class="col-xl-4"> <div class="card shadow-sm p-4" data-toggle="modal" data-target=".bd-example-modal-lg" style="background: #ccc;"> <div class="card-header p-0 text-center"> <h2 class="title">{{i.name}}</h2> </div> <div class="content text-break p-2"> <p class="copy">{{i.description|truncatechars:100}}</p> </div> <div class="card-footer text-left p-0"> <button class="btn btn-primary disabled m-3" data-toggle="modal" data-target=".bd-example-modal-lg"> View </button> </div> </div> </div> {% endif %} {% endfor %} NOTE : I want data which have both status=False and status=True but order should be True first and False last -
How do I add 'extraPlugins' to Django CKeditor
For various reasons I need to create my own CKeditor plugin. However when I add the plugin to the 'extraPlugins' list in settings.py : CKEDITOR_CONFIGS, and add it to my custom toolbar, it simply doesn't show up in the CKeditor on my page. If I disable my custom toolbar, and instead set: 'toolbar': 'full' My custom plugin DOES indeed show up. This is my CKEDITOR_CONFIGS with custom toolbar, where my plugin doesn't show up: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', 'toolbar_YourCustomToolbarConfig': [ {'name': 'AdvancedFunctions', 'items': [ 'Undo', 'Redo' ]}, {'name': 'BasicText', 'items': [ 'Bold', 'Italic', 'Underline', '-', 'TextColor', 'BGColor', '-', 'RemoveFormat' ]}, {'name': 'Formating', 'items': [ 'Format' ]}, {'name': 'BasicPosition', 'items': [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ]}, {'name': 'BasicIndent', 'items': [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent' ]}, {'name': 'AdvancedFunctions', 'items': [ 'Find', 'Link', 'Unlink', 'Anchor' ]}, {'name': 'FileSystem', 'items': [ 'mbn_filesystem' ]}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }], # 'height': 291, 'width': '100%', 'tabSpaces': 4, 'extraPlugins': ','.join([ 'mbn_filesystem' ]), } And replacing 'YourCustomToolbarConfig' with 'full' makes my plugin show up, however it also shows a bunch of unnecessary plugins, since it by definition shows … -
How to paste 'br' after 'label' in django forms?
I have a form: class AddNewContactForm(forms.Form): name = forms.CharField(max_length=200, required=True, label='Enter contact name') number = forms.IntegerField(required=False, label='Enter contact phone number') and i would to have tag 'br' after 'label' to print 'lavel' above 'input' -
Django query filter on nested ManyToMany field
My models are below: class Label(models.Model): name = CharField() class Message(models.Model): labels = ManyToManyField(Label) class Thread(models.Model): messages = ManyToManyField(Message) I have to filter out thread whose all messages don't have label assigned. Thread --> all Messages --> Labels.empty() I have tried this Query: Thread.objects.filter( Q(messages__labels__isnull=True) ) But it returns thread object, even if one message in that thread doesn't have label. How to get query which iterates all messages and check if labels are empty in that each message. -
Django Validators in Serializer vs Validators in Models
I have searched about this extensively and have not found any substantial explanation for this - I have read the DRF documentation and also gone over the following SO links Django Model field validation vs DRF Serializer field validation, Django Model field validation vs DRF Serializer field validation. I have a certain Model where I want to define a Constraint where two fields cannot be the same and need to be unique together. Django models provide the following way to do this class Std(models.Model): std_cons = models.DecimalField(max_digits=11, decimal_places=4, null=True, blank=True) target_cons = models.DecimalField(max_digits=11, decimal_places=4, null=True, blank=True) key_item = models.BooleanField(default=False) class Meta: constraints = [ models.UniqueConstraint(fields = ['std_cons','target_cons'], name='unique_std_entry') ] I can also achieve this in the serializers using the UniqueTogetherValidator from rest_framework.validators import UniqueTogetherValidator class StdSerializer(serializers.Serializer): class Meta: model = Std fields = '__all__' validators = [ UniqueTogetherValidator( queryset=Std.objects.all(), fields=['std_cons', 'target_cons'] ) ] Questions: Which method should be used when and why? What is the significance of both the methods? Should both be used? (maybe Model Level to take care of DjangoAdmin and Serializer to take care of HTTP calls) -
You are trying to add a non-nullable field 'name' to comment without a default
Error ```You are trying to add a non-nullable field 'name' to comment without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: ``` models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey('auth.User', on_delete=models.CASCADE, ) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='fox.jpeg') def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)]) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField(max_length=255, null=True, blank=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) i tried and without blank=True and body = models.TextField(max_length=255, null=True, blank=True, default='Some String') This error constantly pops up, I would be grateful for any help -
how to create view for appointment form in footer in every page in Django
I could not add appointment data in the database In my every html template file, I have added a footer.html like bellow: <!DOCTYPE html> <html> <head> <head> <body> some content {% include 'footer.html' %} </body> <html> in footer.html, I have mentioned the address and appointment form as above <section> <div class="fo-appointment-form"> <form class="forms-sample" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> adress </div> <input type="text" name="name" id="id_name" placeholder="Name"> <input type="text" name="phone" id="id_phone_0" placeholder="Phone number"> <input type="email" name="email" id="id_email" class="gui-input" placeholder="Email address"> <textarea class="gui-textarea" id="id_message" name="message" placeholder="Message"></textarea> <input type="Submit" class="submit-btn" type="submit"> <form> </div> </section> in Django view.py def Appointment_view(request): if request.method == 'POST': appointment= Appointment.objects.create( name = request.POST.get("name"), phone = request.POST.get("phone"), email = request.POST.get("email"), message = request.POST.get("message"), ) appointment.save() return redirect('same?_page') return render(request, 'frontend/footer.html') can someone tell me how to do this? how to write view for footer? where is the mistake? -
How to print / access Django IntegerChoice human readable labels with Model definition
For the Django Model inherited from IntegerChoices with following human readable strings : class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') __empty__ = _('(Unknown)') How can I access the human-readable 'No' and 'Yes' text? -
making a smaller Django/mysql docker image
I am currently using this Dockerfile to build my backend service: FROM python:3.9-buster ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8002 I also have a mysql database the Docker-compose file is: version: '3.8' services: dj: build: context: . dockerfile: Dockerfile ports: - 8000:8002 volumes: - .:/app depends_on: - db db: image: mysql:5.7.22 restart: always environment: MYSQL_DATABASE: ... MYSQL_USER: ... MYSQL_PASSWORD: ... MYSQL_ROOT_PASSWORD: ... volumes: - .dbdata:/var/lib/mysql ports: - 33068:3306 I want to reduce the size of my container which is currently 1.2G any detailed explanation on how to do that would be helpful, precisely I want to know how to do a multisatge build or use a lighter base image properly because I looked at some blogs that use the alpine as their base image but that doesn't work for me probably because my requirement.txt: Django==3.1.3 djangorestframework==3.12.2 django-cors-headers==3.5.0 djangorestframework-simplejwt==4.7.1 pyjwt==2.1.0 mysqlclient==2.0.1 django-mysql==3.9 is not enough. -
"The view page.views.register_view didn't return an HttpResponse object. It returned None instead." Error while using custom registration form
I'm trying to create a custom user registration page only with email and password. This is my view.py file: def register_view(request, *args, **kwargs): user =request.user if user.is_authenticated: return HttpResponse(f"You are already authenticated as {user.email}.") context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email').lower() raw_password = form.cleaned_data.get('password1') account = authenticate(email=email, password=raw_password) login(request, account) destination = kwargs.get("next") if destination: return redirect(destination) return redirect("home") else: context['registration_form'] = form return render(request, 'page/templates/register.html', context) When I try to access to the register.html page using the link in my website this is the error I'm gettin. The view page.views.register_view didn't return an HttpResponse object. It returned None instead. What could be the problem? Thank you -
Django, creating multiple identical fields in the same model
I am completely new to Django, so forgive me if this is the wrong approach. While I'm trying to learn Django, I like to do my own little practice problems to solidify my understanding. Working with models I created the example model objects: from django.db import models class Food(models.Model): name = models.CharField( max_length=50, help_text="Name of Fruit or Vegetable" ) food_group = models.CharField( max_length=9, class Vitamins(models.Model): name = models.ForeignKey( Food, on_delete=models.CASCADE ) vitamin_A = models.CharField( max_length=20, ) . . . folate = models.CharField( max_length=20, help_text="Folic Acid" ) In my object, I have 5 identical fields that store text i.e. (Trace amounts, 5mg, No Information). However it seems tedious to type out every field. Is there a more efficient way to do this? -
Import could not be resolved when trying to create mezzanine project in a venv with vs code
I tried to setup my first mezzanine project in a venv. pip install mezzanine gives me the warning django-contrib-comments 2.1.0 has requirement Django>=2.2, but you'll have django 1.11.29 which is incompatible.. Why does it want to use django-contrib-comments at all if mezzanine only works with older django versions? When I open the env folder in vs-code I get several import cloud not be resolved and foo is not definedwarnings. I tried to change the interpreter by choosing it in the dropdown-menu, by changing my settings.json and by updating the venv path as stated in https://techinscribed.com/python-virtual-environment-in-vscode/ and I checked for the pip and python version. The strange thing is that I get ➜ foundation_site_env python --version Python 2.7.16 ➜ foundation_site_env pip --version pip 21.1.2 from /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pip (python 3.9)when I only open the env folder in vs code but (foundation_site_env) ➜ .venv python --version Python 3.6.8 (foundation_site_env) ➜ .venv pip --version pip 18.1 from /Users/lindacarmenschmid/.venv/foundation_site_env/lib/python3.6/site-packages/pip (python 3.6) when I open the .venv folder in vs code, so it only seems to activate the env when I open the .venv folder, but in both cases the warnings remain the same. Any ideas on what I might have done wrong and what else I … -
object has no attribute 'cleaned_data'
I am working on CS50 django project, yet i keep receiving the error of " object has no attribute 'cleaned_data". I have read all the related question but still cant figure out my problem here is my script of view.py class NewTitleForm(forms.Form): newtitle = forms.CharField(label="title ") class NewContentForm(forms.Form): newcontent = forms.CharField(widget=forms.Textarea(attrs={"rows":5, "cols":5})) def newpage(request): if request.method == "POST": titleinput = NewTitleForm(request.POST) contentinput = NewContentForm(request.POST) if titleinput.is_valid(): newtitle = titleinput.cleaned_data["newtitle"] newcontent = contentinput.cleaned_data["newcontent"] util.save_entry(newtitle,newcontent) else: return render(request, "encyclopedia/newpage.html", { "NewTitleForm": NewTitleForm(), "NewContentForm": NewContentForm() }) return render(request, "encyclopedia/newpage.html",{ "NewTitleForm": NewTitleForm(), "NewContentForm": NewContentForm() }) And the error code is AttributeError: 'NewContentForm' object has no attribute 'cleaned_data' I have no idea what's going on