Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Order matching query doesn't exist in Django?
HViews is as follows def deleteorder(request, pk): order = Order.object.get(id=pk) if request.method == 'POST': order.delete() return redirect() context = {'item':order} return render(request,'accounts/delet.html', context) And Urls.py is as path('delete_order//', views.deleteorder, name= 'delete_order') -
Django: Trying to update an object based on selection by a checkbox in a list display
In the template I am displaying a list of objects in a table. Since its a list I did not use a form. I then added checkboxes to approve each entry (as shown below) The problem is that now I cannot figure out how to iterate over the checkboxes. template.html <form method="post" > {% csrf_token %} {% for row in row_list %} <tr> <td><input type="checkbox" name="result" value=""/></td> <input type="hidden" name="task_id" value="{{ row.id }}"/> <td>{{ row.id }}</td> <td>{{ row.name }}</td> </tr> {% endfor %} <tr> <td colspan="5"> <button type="approve">Approve</button> </td> </tr> views.py def review_results(request, batch_id): batch = get_object_or_404(Batch, pk=batch_id) if request.method == 'POST': # I have tried the following print("Result is ", request.POST.getlist('result')) print("Result is ", request.POST.getlist('task_id')) print("Result is ", request.POST.lists()) request.POST.getlist('result')) returns the value of checkboxes which are checked (array size is 0 if nothing checked). request.POST.getlist('task_id')) returns the list of ids as originally passed (fine). But both lists are out of sync. I cannot use the array from 'result' and perform a save on the appropriate 'task_id' Any ideas on how should i fix this ? Thank you in advance. -
Using Django, How can I delete a file right after downloaded without refreshing the page?
I have the next link to download a file that was generated before rendering a view: <a href="{% static download_path %}" download> Download File </a> How can I delete the file right after the user clicks on that link but without leaving the page? -
Django Forms CheckboxInput on Y/N String field in existing database
I'm relatively new to Django, and I'm making a form which I'm connecting to a existing MySQL database. What I'm trying to do is create a maintenance page for countries. One of the fields in my database is eu_member_state. What I'm trying to do here is create a checkbox for this field, so I can uncheck it for the United Kingdom which recently got out of the EU. class CountryForm(forms.ModelForm): class Meta(): model = Countries fields = '__all__' widgets = { 'eu_member_state': forms.CheckboxInput() } The checkbox does appear on my form, but how can I make this talk to my database? How can this checkbox only be checked when the database value is 'Y', and how do I write this back to my database on save, so 'Y' when checked and 'N' when unchecked? -
EB deploy error : AssertionError: django-countries==6.1 .dist-info directory not found
I try to deploy using AWS Elastic beanstalk but the error is continually occurred Can anyone give some advice of what and why it is coming. [Instance: i-01899473c529952e4] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 2. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. My requirements.txt : appdirs==1.4.3 attrs==19.3.0 awsebcli==3.17.1 bcrypt==3.1.7 blessed==1.17.3 botocore==1.14.17 cached-property==1.5.1 cement==2.8.2 certifi==2019.11.28 cffi==1.14.0 chardet==3.0.4 colorama==0.3.9 cryptography==2.8 distlib==0.3.0 Django==2.2.5 django-countries==6.1 django-dotenv==1.4.2 docker==4.2.0 docker-compose==1.25.4 dockerpty==0.4.1 docopt==0.6.2 docutils==0.15.2 filelock==3.0.12 future==0.16.0 idna==2.9 importlib-metadata==1.5.0 jmespath==0.9.5 jsonschema==3.2.0 paramiko==2.7.1 pathspec==0.5.9 pbr==5.4.4 pipenv==2018.11.26 pipenv-to-requirements==0.9.0 pycparser==2.20 PyNaCl==1.3.0 pyrsistent==0.15.7 python-dateutil==2.8.0 pytz==2019.3 PyYAML==5.2 requests==2.23.0 semantic-version==2.5.0 sentry-sdk==0.14.1 six==1.14.0 sqlparse==0.3.1 termcolor==1.1.0 texttable==1.6.2 urllib3==1.25.8 virtualenv==20.0.13 virtualenv-clone==0.5.3 wcwidth==0.1.8 websocket-client==0.57.0 zipp==3.1.0 .ebextensions>packages.config: packages: yum: postgresql96: [] postgresql96-devel: [] I attached full activity-log: /var/log/eb-activity.log Requirement already satisfied: importlib-resources<2,>=1.0; python_version < "3.7" in /opt/python/run/venv/lib/python3.6/site-packages (from virtualenv==20.0.13->-r /opt/python/ondeck/app/requirements.txt (line 48)) Installing collected packages: django-countries Exception: Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/opt/python/run/venv/local/lib/python3.6/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files … -
Filter objects based on th current user django model admin
Hello I am trying to filter objects in model inline admin based on a field in Profile models I have created with a OneToOneField with User the profile model has a field branch so I want to filter objects based on the logged-in user with respect to their branch class ProductDetailInlineAdmin(admin.StackedInline): readonly_fields = ('created_date', 'generated_url') model = ProductDetail extra = 1 def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "product": kwargs["queryset"] = ProductDetail.objects.filter( product=request.user.profile.branch_id) return super().formfield_for_foreignkey(db_field, request, **kwargs) the product foreignkey still returns everything without filtering out the branch. How do I accomplish the filtering? -
TypeError: unsupported operand type(s) for +: 'WSGIRequest' and 'str'
Stuck on this from last few days i want to join .NS string to the parameter passed by the index function and use that string to web.DataReader() def index(request): if request.method == 'POST': search = request.POST['search'] graph_data(search) def graph_data(request): requestp = request ex = '.NS' st_name = requestp+ex df = web.DataReader(st_name, data_source='yahoo', start='2019-01-01', end='2020-03-16') Error:- TypeError: unsupported operand type(s) for +: 'WSGIRequest' and 'str' -
Can't render html page on the templates folder in the django project?
enter image description here [enter image description here][2] Template doesn't exist error is revoking. Firstly django-project is reading html file as django template file but I added "emmet.includeLanguages": {"django-html": "html"}, to settings.json but it doesn't help -
How Can I add new line string,paragraph in Django
How Can I display in one string/paragraph text with few new line? Code: Text = " " for i in range(len(DictModels)): Text += str(list(DictModels)[i]) + " x" + str(list(DictModels.values())[i]) + " " TextMail = { 'ShowText': Text, } return render(request, 'Order.html', TextMail) Code html: <div id='TextMail'> <p style="text-align: center;"> {{ ShowText }} </p> </div> I want always in begin loop add new line, but ending with "\n" or get in string "< br />" doesnt work. I gets the text on one line. I don't want use 'for loop' in html file, beacuse I want all text in one paragraph. Method " {{ ShowText.as_p }} too doesn't work. -
FieldError at /generic/robot/2/ Cannot resolve keyword 'id' into field. Choices are:
I am trying to access my certain object with integer primary key value. The problem i am facing is that in model i have defined my primary key explicitly but i cannot figure out what is reason i am having this error Error is: FieldError at /generic/robot/2/ Cannot resolve keyword 'id' into field. Choices are: robotID, robotName, robotprofile URL is: path('generic/robot/<int:id>/', GenericRobotAPIView.as_view()) Model is: class Robot(models.Model): robotID = models.AutoField(db_column='robotID', primary_key=True) robotName = models.CharField(db_column='robotName', max_length=50) def __str__(self): return self.robotName View is: class GenericRobotAPIView(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin): serializer_class = RobotSerializer queryset = Robot.objects.all() lookup_field = 'id' def get(self, request, id= None): if id: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) def put(self, request, id=None): return self.update(request, id) def delete(self, request, id): return self.destroy(request, id) Seriallizer is: class RobotSerializer(serializers.ModelSerializer): class Meta: model = Robot fields = '__all__' I have tried query_set.get(Robot.roboID) if i do that it gives me assertion error For instance i write this url 'generic/robot/2/' it should give me object details of this model, i know there are other ways to get Detaiview but for now i just want to use this GenericAPIView to get thing done -
django create/save form using two models with a manytomany relationship
I'm less than 7 days into my Django journey - so please forgive me. I'm in a rout, requiring a bit of expert guidance - having researched/attempted to solve my problem for 10 thankless hours. Code examples are starting to look like hieroglyphics. In essence, how do I build a simple form where you can concurrently create a list and product? I have two rudimentary models a "list" and a "product". class Product(models.Model): name = models.CharField(max_length=100) url = models.URLField() price = models.DecimalField(max_digits=8, decimal_places=2) class List(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=100) category = models.CharField(max_length=50) products = models.ManyToManyField(Product) I have this error: ValueError: 'core_lists.Product' has no ForeignKey to 'core_lists.List'. The above error surely does not restrict inline_formfactories to ForeignKey ones? Having researched this - I am not intelligent enough to merge the various sources into one cogent code block: Great article with a similar pizza and topping analogy Should I just ignore inline_formfactories and loop through everything i.e. the opposite recommendation Wtf is super mixin and **'s in front of parameters forms.py class ProductListForm(ModelForm): class Meta: model = Product class ListForm(ModelForm): class Meta: model = List fields = '__all__' list_form.html <form method="POST" action=""> {% csrf_token %} {{ ProductListFormSet }} <input type="submit" … -
How can I access multiple Querysets in a template in the same cycle?
I am transferring different similar Querysets to a template. Eg. qset01, qset02, ... qset10. The number of Querysets in known and can be transferred as well. How can I access these Querysets in a template in a cycle in the same iteration level. When I iterate through a single query, the code is: {% for i in qset01 %} {{i.field_01}} {% endfor %} What would it look like for many Querysets? This is what I need {% for more_complex_iteration %} {{qset01.field_01}}, {{qset02.field_01}}, ... {{qset09.field_01}} {% endfor %} Thank you -
multi-tenant architecture acessing tenant's external data source
I am building a Saas with django. Its job is to provide a dashboard for each tenant. The architecture is a multi-tenant with each tenant having its own schema in a postgresql database. My problem comes from the data processing on the backend. Each tenant needs to be able to pull data from an external source (most likely ERP system database), from there I have a python script that process this data and then stores it in the postgreSQL schema of the tenant. My biggest issue is the code to letting the tenant connect to its external database to pull data from outside. I have not found any way to do that from Django documentation. Would anyone has a hint on how to proceed or a resource I could consult. -
ModuleNotFoundError: No module named 'todo_list.forms' in Django app
I am following a tutorial online for a to-do app using Django, but I keep getting this error. File “C:\DjangoStuff\my_app\todo_app\urls.py”, line 3, in from todo_list import views File “C:\DjangoStuff\my_app\todo_list\views.py”, line 3, in from .forms import ListForm ModuleNotFoundError: No module named ‘todo_list.forms’ I have tried deleting and adding back the forms.py file, but no success. The todo_list folder does contain all the files being referenced as far as I can tell. I have a todo_list folder where all the below mentioned files are stored This is the code I have imported in the urls.py file: from django.urls import path from . import views in the views.py file, I have the following imported: from django.shortcuts import render, redirect from .models import List from .forms import ListForm from django.contrib import messages from django.http import HttpResponseRedirect I have also created the models.py file and forms.py files as part of the todo_list folder. I'ms sure it's something simple but have been through the tutorial many times and cannot find anything wrong... -
Django, REST framework - How to ensure absolute url will be returned for image?
I need viewset to return always absolute url for avatar / avatar_thumbnail image fields in response, but I'm getting relative paths. I have two such cases: 1st) is in image field in nested serializer, 2nd) is in viewset where I want to use two serializers in retrieve method. models.py class CustomUser(AbstractUser): avatar = ProcessedImageField(upload_to='users/',format='JPEG',options={'quality': 60}) avatar_thumbnail = ImageSpecField(source='avatar',processors=[ResizeToFill(50, 50)],format='JPEG') settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)here forum/api/serializers.py (nested serializer) class UserSerializer(serializers.ModelSerializer): avatar_thumbnail = serializers.ImageField(read_only=True) class Meta: model = CustomUser fields = ['id', 'username', 'avatar_thumbnail'] class ThreadSerializer(serializers.ModelSerializer): class Meta: model = Thread fields = ['id', 'title', 'subject', 'user'] def to_representation(self, instance): representation = super().to_representation(instance) representation['user'] = UserSerializer(instance.user).data return representation forum/api/viewsets.py class ThreadViewSet(viewsets.ModelViewSet): serializer_class = ThreadSerializer queryset = Thread.objects.all() For UserViewSet I have also similar problem with urls for "avatar". I need absolute urls. I get relative url, but only when I overwrite retrieve method in viewset. (I overwrite it to use different serializer "UserPrivateSerializer" for user that is owner of the profile) .For list I always get absolute url. users/api/serializers.py class UserPublicSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['id', 'username', 'avatar'] class UserPrivateSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) class Meta: … -
Django intersection of ManyToMany using Through model
I have two models that have a ManyToMany relationship using a through model. class Person(Model): departments = ManyToManyField('Department', through='DepartmentStaff') class Department(Model): id = ... class DepartmentStaff(Model): staff_member = ForeignKey(Person, on_delete=CASCADE) department = ForeignKey(Department, on_delete=CASCADE) experience = DurationField() I want to check if 2 Person objects share at least one department. e.g. if person p1 works in departments d1 and d2, and Person p2 works in departments d2 and d3, then they both work in d2, the output should be True I know that I can't do something like this >>> p1.departments.intersection(p2.departments).exists() ... AttributeError: 'ManyRelatedManager' object has no attribute 'query' because I'm using a through relationship. What is the best way to check if 2 through ManyToMany query sets contain at least one same element? -
Get values of ForeignKey related objects in django
There are two models in my django ORM: class Product(models.Model): product_id = models.IntegerField(default=0,unique=True) product_short_code = models.CharField(max_length=500, default=0,unique=True) class GRN(models.Model): owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='grn_owner') warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name="grn_warehouse") reference_no = models.CharField(max_length=500, default=0) inward_date = models.DateField(default=datetime.now) product1 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product1') product1_quantity = models.IntegerField(default=0) product1_price = models.IntegerField(default=0, blank=True, null=True) product2 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product2', blank=True, null=True) product2_quantity = models.IntegerField(default=0, blank=True, null=True) product2_price = models.IntegerField(default=0, blank=True, null=True) product3 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product3', blank=True, null=True) product3_quantity = models.IntegerField(default=0, blank=True, null=True) product3_price = models.IntegerField(default=0, blank=True, null=True) How can I get the short code of all the products stored in GRN model along with their total quantity? Is this something like this ? for i in range(1,4): p = "product"+str(i)+"__product_short_code" q = "product"+str(i)+ "_quantity" g_prod = Grn.objects.all().values_list(p,q) But it will not give the unique products and their cumulative count -
Django - Query set is not displaying the result from db
I have values stored in the db but it is not displaying the query set View.py Models.py Models.py empty query set------- [28/Mar/2020 16:31:25] "GET /products/ HTTP/1.1" 200 34 -
Best practice for reverse access for foreign key in Django admin list_display
I have a django application which clients make some online orders and then we dispatch them by post courier. For orders and post parcels , I have defined two models which postparcel has order field as foreign key to Orders model. I put list_per_page = 250 . Now I have around 100,000 orders in my postgresql database. Everything is also indexed. In admin.py, I needed to access barcode for each postparcel when I view the order model in admin panel. So I made a function for the query. However, when I use Django admin toolbar, I can see 250 queries are made to catch all results from postparcel table. This is time consuming process. What is best practice for this. I tried using PostParcel__parcel_post_barcode and PostPacel.parce_post_barcode .. Both have compile error saying that this object is not found within this class. Please let me know how I can chain these two tables for one single query and make it faster in my admin panel. I found a code snippet here but seems old. I use django 3.1. I think there must be better way. https://djangosnippets.org/snippets/2887/ models.py class Orders(models.Model): order_id = models.CharField(max_length=255, null=True, unique=True, verbose_name=_("order id")) creation_time = models.DateTimeField(auto_now_add=True, verbose_name=_("creation time")) … -
Django - upload images with additional information
So let's say I have a blog website. And each blog consists of images. So, I want to sort the images depending on which blog they belong to. But when uploading, how do I automatically pass the blog id with the image? I have my model like this: class Blog(models.Model): name = models.CharField() blog = models.CharField() class Photo(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) file = models.FileField(upload_to=get_upload_path) My forms.py looks like: class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file', 'blog') You see in the fields there is 'blog'. How do I actually pass the blog id there? Currently, my html for upload page is like this: <div style="margin-bottom: 20px;"> <button type="button" class="btn btn-primary js-upload-photos"> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'blog' blog.id %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> </div> Actually this way of uploading images is taken from this great article by Vitor Freitas Now, I am wanting to pass the blog id to the template through views.py with context which I have done. But how do I save that and pass that with the images I upload? the views.py looks like: class BlogDetailView(View): def get(self, request,**kwargs): page = get_object_or_404(Page, pk=self.kwargs['pk']) context = {'page':page} return render(self.request, 'blog.html', context=context) … -
Auto send email when new post has created in django
When I save my post, I want to send email for user automatically. But it's not working. This is my code signals.py from django.db.models.signals import post_save from django.dispatch import receiver from mysite.models import Post, Email from django.core.mail import send_mail from blog.settings import EMAIL_HOST_USER @receiver(post_save, sender=Post) def SendEmail(sender , instance, created, **kwargs): if created: emails = list(Email.objects.values('email')) recepients = [] for i in range(0, len(emails)): recepients.append(emails[i]['email']) pass send_mail('New post on blog', str(instance.title), EMAIL_HOST_USER, recepients, fail_silently=False) pass -
how to store mulitple image in database by selecting multiple image from a single input file
I have model class Images(models.Model): schedule = models.ForeignKey(Schedule, default=None,on_delete=models.CASCADE) image = models.ImageField(default='jpt.png',upload_to='images/',null=True,blank=True) i want to store multiple image for a single schedule and i have used react as front end from where i get the list of multiple image suppose i got image list as var image_list = [...this.state.image] and on console i get image list is: (2) […] 0: File { name: "Screenshot (70).png", lastModified: 1580296846904, size: 359266, … } 1: File { name: "Screenshot (71).png", lastModified: 1580296853318, size: 239091, … } then i called the django api and passed only single image like below: var formData = new FormData() formData.append('image',this.state.image[0]) axios.post('http://127.0.0.1:8000/account/api/view_schedule',formData).then(res=>{ console.log(res.data) }).catch(err=>{ console.log('error message') }) in this way i can store single image into the database But my problem is to store the multiple image into single schedule i have tried to passed list of file and i have django view as below : @api_view(['POST',]) def scheduleview(request): if request.method=='POST': sche = ScheduleSerializer(data=request.data,many=True) img = ImageSerializer(data = request.data,many=True) image = img.initial_data['image'] while printing i get img serializer as ImageSerializer(data=<QueryDict: {'title': ['df'], 'datetime_field_start': ['2020-3-28 16:36'], 'datetime_field_end': ['2020-3-28 16:36'], 'rj': ['1,2'], 'image': ['[object File],[object File]'], 'owner': ['1']}>, many=True): my question is how to access that two image file … -
How do I redirect to url2 after performing a task on url1 in django?
I have a edit-scholarship.html in which you can search for a scholarship by passing name and type and then select that scholarship and edit it in update-scholarship.html by passing scholarship id from the url. Now after updating the scholarship, the url becomes http://127.0.0.1:8000/admin/updatescholarship/50 50 is the scholarship id passed into the url Now when I try to go to dashboard in my project, the url becomes http://127.0.0.1:8000/admin/updatescholarship/dashboard I dont't want the dashboard to get appended after the updatescholarship . The url should be http://127.0.0.1:8000/admin/dashboard Here's my edit-scholarship view def admin_editscholarship(request): if request.method == 'POST': name = request.POST['sch_name'] type = request.POST['sch_type'] schdets = ScholarshipDetails.objects.filter(name = name,type = type) if schdets is not None: #if something exists in scholarship details, then print it print('Scholarship found') else: schdets = None return render(request,'admin-editscholarship.html',{'schdets':schdets}) Here's my update-scholarship view def admin_updatescholarship(request,pk=None): #can update the new data in the selectd scholarship if pk: sch = ScholarshipDetails.objects.get(pk = pk) if request.method == 'POST': form = EditScholarshipForm(request.POST,instance=sch) if form.is_valid(): form.save() print('\nform saved') args = {'form' : form} messages.success(request,'Successfully updated') return render(request,'admin-editscholarship.html',args) Here's my urls.py path('admin/dashboard',views.admin_dash), path('admin/addscholarship',views.admin_addscholarship), path('admin/editscholarship',views.admin_editscholarship), url(r'^admin/updatescholarship/(?P<pk>\d+)$',views.admin_updatescholarship,name = 'updatescholarship'), path('admin/students',views.admin_students), path('admin/requests',views.admin_requests) -
How can I stream big data to Google Cloud Storage?
I am working on a system for analyzing data of any size and format streamed by the users to my private cloud based on Google Cloud Storage. Do you have any ideas how can I allow them to stream big data? At the moment I use Django API and I do this in this way: def upload_blob(source_file_name, destination_blob_name): blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print('File {} uploaded to {}.'.format( source_file_name, destination_blob_name)) It works correctly with small files however when I send for example large movie I get the error shown below. I am aware that this is not the optimal solution but I have no idea how can I solve this. As you can notice at the moment they send me requests with the blob format but with very large files it does not work. Do you have any ideas how can I solve my problem and send users data of any size to Google Cloud Storage? Internal Server Error: /cloud/ Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 672, in urlopen chunked=chunked, File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 387, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1252, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py", line 1298, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File … -
Django: is_valid() method is always return why?
I'm just practicing django and creating simple app that take user name and profile pic and then save it in database.is_valid() method is always return false when i do form validation. views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .models import student,photo from .forms import student_data # Create your views here. def my_data(request): check=0 myform=student_data() if (request.method=="POST"): myform=student_data(request.POST,request.FILES) if (myform.is_valid()): stu_name=myform.cleaned_data['name'] stu_image=myform.cleaned_data['image'] d=photo.objects.filter(name=stu_name) myform.save() if not d: new_data=photo(image=stu_image,name=stu_name) photo.save(self=new_data) else: check=1 else: myform=student_data return render(request,'show.html',{'student':stu_name,'check':check}) forms.py from django import forms #from .models import student class student_data(forms.Form): name=forms.CharField(widget=forms.TextInput,max_length=20) image=forms.ImageField() models.py from django.db import models class photo(models.Model): image=models.ImageField() name=models.CharField(max_length=20) class Meta: db_table='photo' html file for form. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <form name="form" action="/payment/show/" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Add Me</button> </form> </div> </body> </html>