Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When running my django project in python3 manage.py run server i get this error ModuleNotFoundError: No module named 'pip._vendor.urllib3.connection'
After i run python3 manage.py runserver i get the following error: Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/django/core/management/init.py", line 12, in from django.conf import settings ImportError: cannot import name 'settings' from 'django.conf' (unknown location) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( 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? (nova_venv) Luiss-MacBook-Pro:novadjango luiseduardo$ pip install django Traceback (most recent call last): File "/Users/luiseduardo/Practice/nova/nova_venv/bin/pip", line 6, in <module> from pip._internal import main File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/pip/_internal/__init__.py", line 19, in <module> from pip._vendor.urllib3.exceptions import DependencyWarning File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/pip/_vendor/urllib3/__init__.py", line 7, in <module> from .connectionpool import ( File "/Users/luiseduardo/Practice/nova/nova_venv/lib/python3.8/site-packages/pip/_vendor/urllib3/connectionpool.py", line 30, in <module> from .connection import ( ModuleNotFoundError: No module named 'pip._vendor.urllib3.connection' Im using mac and i do have my virtualenv activated. -
Django Rest Framework group and count POST
I am new to DRF and am trying to create some kind of dynamic serializer to calculate the objects posted but I cannot find out how to do it. models.py class Company(TimeStampedModel): name = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) date_founded = models.DateField(null=True, blank=True) def get_year (self): return self.date_founded.strftime("%Y") def get_quarter (self): x = self.date_founded if int(x.strftime("%m")) <= 3: return '1' elif int(x.strftime("%m")) <= 6 and int(x.strftime("%m")) > 3: return '2' elif int(x.strftime("%m")) <= 9 and int(x.strftime("%m")) > 6: return '3' else: return '4' def __unicode__(self): return u'{0}'.format(self.name) serializers.py class StatsSerializer(serializers.ModelSerializer): year = serializers.DateField(source='get_year') quarter = serializers.CharField(source='get_quarter') # total = serializers.SerializerMethodField() class Meta: model = Company fields = ['year', 'quarter', #'total'] views.py class CompanyStatsView(generics.ListCreateAPIView): queryset = Company.objects.all() serializer_class = StatsSerializer So far my results are: [ { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "2" }, { "year": "2018", "quarter": "3" }, { "year": "2018", "quarter": "3" }, ] however I am looking for something like this: [ { "year": "2018", "quarter": "2" "total": 4 }, { "year": "2018", "quarter": "3" "total": 2 }, ] How can I group and count this values? Any help is much … -
admin_order_field not ordering in descending order
Am trying to order items in the column in descending order, but it's not working , below is my model : class Person(models.Model): first_name = models.CharField(max_length=50) color_code = models.CharField(max_length=6) count_num = models.IntegerField() def __str__(self): return self.first_name Then, in the admin.py file I have this : @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ('first_name', 'color_code', 'counting') def counting(self, obj): return obj.count_num counting.admin_order_field = '-count_num' But the column counting seems not to be sorted , below is the screenshot : -
Type error __str__ returned non-string (type employeeName)
I am trying to make a one to many database with name and time in time out fields but when I enter value to the child table by using the admin site it gives me this error __str__ returned non-string (type employeeName) here is my model: from django.db import models from datetime import datetime, date from django.utils.timezone import localtime #Create your models here. class employeeName(models.Model): employee = models.CharField(max_length=200) def __str__(self): return self.employee class Name(models.Model): name = models.ForeignKey(employeeName, null=True,on_delete=models.CASCADE) timeIn = models.TimeField() timeOut = models.TimeField(default=datetime.now()) date = models.DateField(auto_now=True) def __str__(self): return self.name admin : from django.contrib import admin from .models import Name, employeeName from .forms import CreateNewList class ComputerAdmin(admin.ModelAdmin): list_display = ["name", "date","timeIn", "timeOut"] admin.site.register(Name, ComputerAdmin) admin.site.register(employeeName) I have also tried using def __str__(self): return str(self.name) It still gives me the same error -
TypeError: Field 'price' expected a number but got <django.db.models.fields.FloatField>
I have that exception"TypeError: float() argument must be a string or a number, not 'FloatField'" even thought i deleted the price field and runned makemigrations , how??? -
Trigger multimple events from one click button - write to database & render an HTML
Here is my scenario. I am building a website where I have created a dependent dropdown menu. Say select A(first dropdown) then select A2 (second Dropdown) ----> Submit Then I am writing the values to databse (A-A2). Below is the flow. Submit button in JS --> Call funciton in views.py --> writing to database. In JS, I have used 2 event handlers on same itemForm object: itemForm.addEventListener('submit', e=>{ e.preventDefault() console.log('submitted') $.ajax({ type: 'POST', url: '/create/', data: { 'csrfmiddlewaretoken': csrf[0].value, 'firstItem': firstitemText.textContent, 'secondItem': seconditemText.textContent, }, success: function(response){ console.log(response) alertBox.innerHTML = `<div class="ui positive message"> <div class="header"> Success </div> <p>Your order has been placed</p> </div>` }, error: function(error){ console.log(error) alertBox.innerHTML = `<div class="ui negative message"> <div class="header"> Ops </div> <p>Something went wrong</p> </div>` } }) itemForm.addEventListener('submit', e=>{ e.preventDefault() console.log('submitted') $.ajax({ type: 'POST', url: `orders/${seconditemText.textContent}`, data: { 'csrfmiddlewaretoken': csrf[0].value, 'firstItem': firstitemText.textContent, 'secondItem': seconditemText.textContent, }, success: function(response){ console.log(response) }, error: function(error){ console.log(error) } }) }) Now from second event handler, I want to call same html file and render a plot as shown below: In views.py: def main_view(request): qs = FirstItem.objects.all() return render(request, 'orders/main.html', {'qs':qs}) #Some other views funtion for writing data to dropdown, which might not be relevant def create_order(request): if request.is_ajax(): secondItem … -
Change the client-site "pattern" for URL-"input" using Django
I have a model which contains link = URLField(). The problem is, I don't want the client-side to do any kind of validation (i'm doing that in the clean_link). I have tried using django-widget-tweaks such as mytemplate.html {% load widget_tweaks %} <div class="form-group"> {{form.link|attr:"pattern:.*"|as_crispy_field}} </div> which has no effect. I can include novalidate in my <form> but then that'll remove validations for all my fields, and not only for link. How do we properly manage the attributes/properties for <input> when we are using the Django-form? -
Python - Django - How to write log to an existing Kibana from Django framework?
Well my team is currently having a Kibana working. I am building a source by Django Framework. I was told to write log into that existing Kibana. I was provided : LOGSTASH_HOST=172******** LOGSTASH_PORT=5***** INDEX=platform-staging After looking up for some resources: I did this in my settings.py 'logstash':{ 'level':'DEBUG', 'class': 'logstash.LogstashHandler', 'host': '172******, 'port': 5000, 'version':1, 'message_type' : 'logstash', 'fqdn':False , 'tags': ['tag1', 'tag2'] } 'loggers': { 'django.request':{ 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True }, When I build my app: I got an error like this: raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'logstash' Well please help me out of this situation, and it would be nice if you can me a detailed document. -
I have coded some python program and I want it to implement on website so that everyone with the link can use it by providing necessary arguments
I have a python program and I want to make it online as a website so that anyone can visit that site fill the required information and run the program , I don't know how I can implement it on a website so can anyone please help me out ? Can I do with Django, If yes then how? -
How to validate a subscription in google play store using receipt in python
I need to validate a receipt received from the android app while a subscription is taken. I have tried using the python package for validating in-app purchases, but end up in error. I have used pyinapp for this... link(https://pypi.org/project/pyinapp/#description) from pyinapp import GooglePlayValidator, InAppValidationError bundle_id = 'com.yourcompany.yourapp' api_key = 'API key from the developer console' validator = GooglePlayValidator(bundle_id, api_key) receipt = json.dumps({"orderId": "GPA.3371-6663-9953-88022", "packageName": "com.yourcompany", "productId": "com.yourcompany.basic.five.annually", "purchaseTime": 1617944948660, "purchaseState": 0, "purchaseToken": "fkefffonlgkfapblnahlokjp.AOJ1OzvaGGwTt24bMs47c98hpPQI62qdITM- uphoHzK4HQkW5locx9xDILRasO7eQTTRoGr0LwyflO2mqvnfn0fNVkZ0ipPgQ", "autoRenewing": true, "acknowledged": true}) signature = '' (signature from android app) purchases = validator.validate(receipt, signature) process_purchases(purchases) but always ended up in bad signature error at line validator.validate(receipt, signature) Can you please help....don't know what is wrong -
Different images of two users are showing in one story
I am building a Social Media app. AND i stuck on a Problem. What i am trying to do :- I have build a story feature ( users can make their story like instagram ) everything is working fine BUT When two different users post images in stories then images are showing in single story BUT i am trying to show if two users post two images in stories then show in different stories.- As you can see in first picture that first story is by user_1 and another is by user_2, They are showing in same story but i want them to show in different stories. stories.html <script> var currentSkin = getCurrentSkin(); var stories = new Zuck('stories', { backNative: true, previousTap: true, skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], avatars: currentSkin['params']['avatars'], paginationArrows: currentSkin['params']['paginationArrows'], list: currentSkin['params']['list'], cubeEffect: currentSkin['params']['cubeEffect'], localStorage: true, stories: [ // {% for story in stories %} Zuck.buildTimelineItem( 'ramon', '{{ user.profile.file.url }}', '{{ story.user }}', 'https://ramon.codes', timestamp(), [ [ 'ramon-1', 'photo', 3, // '{% for img in story.images.all %}' '{{ img.img.url }}', '{{ img.img.url }}', // '{% endfor %}' '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> </body> </html> models.py class ImgModel(models.Model): img = models.ImageField(upload_to='status_images',null=True) … -
Filtered left outer join in Django that gives access to related Model, not its fields via values()
I am trying to build a list of products for further use in view template. This list is based on filtered Product model that are referred by ForeignKeys in ProductInfo and Image models. Final QuerySet should include all Products that are fall under given criteria and one or zero (depending on additional filters) objects from ProductInfo and Image. If I use annotate() and FilteredRelation() like this: ll = Product.objects.filter(Category=category) \ .annotate(pi=FilteredRelation('productinfo', condition=Q(productinfo__Language=language.id))) \ .annotate(im=FilteredRelation('image', condition=Q(image__IsPrimary=True))) then I need to use values() to access data from jointed Models, and some of custom template tags that I use (for example django-imagekit) will fail because they expect an instance, not just field. I don't expect that the products list will be more than 100 items, and I am thinking that it will be easier to retrieve 3 correctly filtered sets (Product, ProductInfo, Image) and try to join them in code. However I cannot pass it correctly to template engine via context. -
how to unit test custom product models with Foregienkey in unittest in django with pytest
I am trying to unit test a specific model which has a foregienkey with pytest , but after lot of effort I am still facing error and I am new to unit test . error : @pytest.mark.django_db def test_create_pg(client): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') make_pg=PG() > assert PG.objects.count==0 E assert <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x04E8D220>> == 0 E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x04E8D220>> = <django.db.models.manager.Manager object at 0x04E8D220>.count E + where <django.db.models.manager.Manager object at 0x04E8D220> = PG.objects PPpgOwner\test\test_views.py:41: AssertionError My MODELS.PY class PG(models.Model): pg_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) pg_Owner = models.ForeignKey(PPuseers, on_delete=models.CASCADE) pg_name = models.CharField(max_length=255,default='Null') location = models.CharField(max_length=50,default='Null') describtion = models.CharField(max_length=10000, default='Null') pg_main_price = models.IntegerField(default=0) pg_discount_price = models.IntegerField(default=0,blank=True,null=True) ...... ....... this model is liked with a PPusers model PPusers MODEL class PPuseers(AbstractBaseUser, PermissionsMixin): Uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email", max_length=554, unique=True) username = models.CharField(max_length=500, unique=False) date_joined = models.DateTimeField(verbose_name="Date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) ...... ...... ...... MY Pytest : from django import urls from django.contrib.auth import get_user_model from django.http import response from django.urls.base import reverse from PPCustomer.models import PPuseers from PPpgOwner.models import PG @pytest.mark.django_db def test_create_ppuser(client,ppuser_data): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') assert PPuseers.objects.count()==1 @pytest.mark.django_db def test_create_pg(client): user=PPuseers.objects.create(Uid='6fa459ea-ee8a-3ca4-894e-db77e160355e') make_pg=PG() assert PG.objects.count==0 pg_tester=PG.objects.create( pg_id='6fa459ea-ee8a-3ca4-894e-db77e160355e', pg_Owner … -
Does behave-django do migrations before running the tests?
I am trying to do a behavior testing on my API, but it seems like it does not run all my migrations. I can't seem to find something about this in their documentation. -
Saving Longitude and Latitude to a user profile in Django
I was looking for a way to use HTML5 (and possibly JS) to save visitor/user Longitudnal & Latitudnal data to a database. I do not wish to use packages out there as they seem a bit outdated and may break my code in future considerting their own reliance on other APIs. I know there is a way around using AJAX, but I clearly dont know and understand it well enough to implement it. My ask of the learned Lords is - 1. Get Loc data 2. Send it to Python in dict or json or string format from where it can be further processed and saved. Why you may ask - Good question. I would use it for displaying weather on the homepage and local twitter trends on a 'logged-in' page. Any assistance would be appreciated. Cheers! -
adding choices dynamically in django model based on 2-3 other models
I have a model which has an intake field.. class University(models.Model): name= models.CharField(max_length=50) .... .... def __str__(self): return str(self.name) class Course(models.Model): name= models.CharField(max_length=50) university= models.ForeignKey(University, on_delete= models.DO_NOTHING) .... .... def __str__(self): return str(self.name) class CourseDeadline(models.Model): intake= models.CharField(max_length=50) course= models.ForeignKey(Course, on_delete= models.DO_NOTHING) .... .... def __str__(self): return str(self.intake) class Coupon(models.Model): code= models.CharField(max_length=20) university= models.ForeignKey(University, on_delete= models.DO_NOTHING) intake= models.ForeignKey(CourseDeadline,on_delete= models.DO_NOTHING) .... .... def __str__(self): return str(self.code) I would like to show intakes dynamically as a choice field based on selected university.something like u= Universitiy.objects.get(id=university) c= Course.objects.filter(university=u).order_by('id').first() cd= CourseDeadline.objects.filter(course=c).all() intake= models.CharField(max_length=20, choices=cd) Is it possible through Models or Forms and this model is for django admin. -
Disable logging exceptions in Django (logging.raiseException = True)
Is there any equivalent to : import logging logging.raiseException = False in Django's log configuration ? -
Django : Not able to convert CSV file to HTML table using AJAX
i have a code which should display the contents of CSV file using AJAX , i did it in Django folder structure , so currently when i use Django for that purpose it shows error "Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/pandas.csv" But when i do the same without Django it works fine . So here is my code . $(document).ready(function() { $.ajax({ url: "pandas.csv", dataType: "text", success: function(data) { var employee_data = data.split(/\r?\n|\r/); var table_data = '<table class="table table-bordered table-striped">'; for (var count = 0; count < employee_data.length; count++) { var cell_data = employee_data[count].split(","); table_data += '<tr>'; for (var cell_count = 0; cell_count < cell_data.length; cell_count++) { if (count === 0) { table_data += '<th>' + cell_data[cell_count] + '</th>'; } else { table_data += '<td>' + cell_data[cell_count] + '</td>'; } } table_data += '</tr>'; } table_data += '</table>'; $('#employee_table').html(table_data); } }); }); {{ %load static%}} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="table-responsive"> <h1 align="center">CSV File to HTML Table Using AJAX jQuery</h1> <br /> <br /> <div id="employee_table"> </div> </div> </div> </body> </html> So this pandas.csv is kept inside Stat-->Static-->Pandas.csv and html template in Stat-->Website-->templates-->template.html So … -
How can use the exclude query in django
I just want to show that items which are in order table. I am using exclude query for that but when i use it it show nothing OrderProduct and Order are tables. view.py def get(self, request, *args, **kwargs): allOrder = OrderProduct.objects.all() categories = Category.objects.all() categoryId = self.request.GET.get('SelectCategory') product = Product.objects.filter(category_id=categoryId) orders = Order.objects.all() checkOrder = Order.objects.exclude( orderProduct__order__in=orders ) args = {'categories': categories, 'product': product, 'checkOrder': checkOrder} -
How to migrate a Django web app from local machine to another machine[with no internet; can't use PIP] as deployable app
I have a running Django application in my local system and I want to transfer and run the same to another machine in the same network. But, the destination machine cannot use PIP cmd to install dependencies as it does not have internet connectivity. Any ideas to transfer the project are appreciated. -
Uploading crop image and form using cropperjs in Django
I am using https://github.com/fengyuanchen/cropper/blob/master/README.md as the cropper function. However, I want to submit field objects (in this case the title) and the cropped image. But I got an error on the admin. And of course, I have done the makemigrations and migrate before running the server Error Picture admin.py from django.contrib import admin from .models import Image # Register your models here. class ImageAdmin(admin.ModelAdmin): pass admin.site.register(Image, ImageAdmin) models.py from django.db import models # Create your models here. class Image(models.Model): title = models.CharField(max_length=10) image = models.ImageField(upload_to='images') def __str__(self): return str(self.pk) forms.py from django import forms from .models import Image class ImageForm(forms.Form): image = forms.ImageField() title = forms.CharField( max_length=10, widget=forms.TextInput( attrs={ "class": "form-control", "placeholder": "Title", }, ), required=True ) views.py from django.shortcuts import render, redirect from .models import Image from .forms import ImageForm from django.http import JsonResponse from django.http import HttpResponseRedirect def main_view(request): form = ImageForm() if request.method == "POST": form = ImageForm(request.POST, request.FILES) if form.is_valid(): addimage = Image( title=form.cleaned_data['title'], image = form.cleaned_data['image'], ) addimage.save() else: form = ImageForm() context = {'form': form} return render(request, 'photo_list.html', context) photo_list.html {% extends "base.html" %} {% block javascript %} <script> console.log("Hello"); const imageBox = document.getElementById("image-box"); const confirmButton = document.getElementById("confirm-button") const input = document.getElementById("id_image"); const csrf … -
Username is not showing but user id is showing in html template in Django
Below is my Model : class Problem_Solved(models.Model): user_ref = models.ForeignKey(User, on_delete=models.CASCADE) contest_ref = models.ForeignKey(Contest, on_delete=models.CASCADE) problem_ref = models.ForeignKey(Problem, on_delete=models.CASCADE) points_get = models.IntegerField(default=0) time_submitted = models.DateTimeField('date published') class Meta: unique_together = (("user_ref", "problem_ref")) def __str__(self): return self.user_ref.username + " solved " + self.problem_ref.problem_name + " and got " + str(self.points_get) + " marks " Below is my view function : def pointtable(request, contest_id): context = {} contest_obj=Contest.objects.get(pk=contest_id) points_list = Problem_Solved.objects.filter(contest_ref = contest_obj).values('user_ref').annotate(user_sum = Sum('points_get')).order_by('-user_sum') print(points_list) context['points_list'] = points_list return render(request,'leaderboard.html', context) Now below is my html code : {% for pt in points_list %} <div class="container-sm w-75 tb-bg-color"> <div class="row mb-3 "> <div class="col-1 themed-grid-col col-border">{{forloop.counter}}</div> <div class="col-6 themed-grid-col col-border">{{pt.user_ref.username}}</div> <div class="col-2 themed-grid-col col-border">{{pt.user_sum}}</div> </div> </div> {% endfor %} Below is output : Username is not showing As clearly seen in image that username is not showing but if I write pt.user_ref in my html code then it will print user_id as shown below : User id is showing Now I want username but not user id what should i do as I am stuck with this from 2 days. Help me if u can. -
Invalid block tag in django
I've done pretty much everything in my knowledge to solve this, but I guess I've gone wrong somewhere as I'm still a beginner, so I'd like someone to kindly help me out with this and also I've added the error message at the bottom, including the code error TemplateSyntaxError at / Invalid block tag on line 9: 'static'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.6 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 9: 'static'. Did you forget to register or load this tag? Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py, line 531, in invalid_block_tag Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['C:\\Users\\Admin\\Desktop\\Django\\ecommerce', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Fri, 09 Apr 2021 00:16:08 +0000 setting STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] css/main.css body { background-color: blue; } store/main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ecommerce</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}" type="text/css"> </head> <body> <h1>Navbar</h1> <hr> <div class="container"> {% block content %} {% endblock content %} </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script> </body> </html> store {% extends 'store/main.html' %} {% load static %} … -
addBooks() got an unexpected keyword argument 'name'
I want to take data from user and save it to database by using django. Have tried to solve it. But I am not able to solve this problem and didn't find any working solution on internet. I am getting this error:- My views.py file is:- from django.shortcuts import render, HttpResponse from home.models import addBooks def index(request): return render(request, "index.html") def checkBooks(request): return render(request, "checkBooks.html") def contactUs(request): return render(request, "contactUs.html") def addBooks(request): name = request.POST.get('name', False) email = request.POST.get('email', False) bookName = request.POST.get('bookName', False) authorName = request.POST.get('authorName', False) desc = request.POST.get('desc', False) book = addBooks(name=name, email=email,bookName = bookName, authorName = authorName, desc = desc) book.save() return render(request, "addBooks.html") And my models.py file is:- from django.db import models class addBooks(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) bookName = models.CharField(max_length=122) authorName = models.CharField(max_length = 122) desc = models.TextField() This is addBooks.html(Here I am getting the data from user by using from):- <form method="POST" action = "/addBooks"> {% csrf_token %} <div class = "container"> <h1 class = "text-center"> Add Books </h1> <div class="mb-3"> <label class="form-label">Your Name</label> <input type="text" name = "name" class="form-control"> <div class="form-text"></div> <div class="mb-3"> <label class="form-label">Email Address</label> <input type="email" name = "email" class="form-control"> <div id="emailHelp" class="form-text">We'll never share your email with … -
My django manage.py is not running server
I am connected to internet and everything is fine but as in the picture you can see manage.py is not running server