Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display foreign key as a link to a model in another app in django admin
I'm using Django==2.1.5. And I've gone through the similar questions to what is in my title but couldn't find a working solution due the similarity in model names and their respective field names used in foreign key relationships and also the models in those use cases were in the same app, so it confused me. I've a model Order in my Shopping_cart app: class Order(models.Model): owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) I've another model Profile in my accounts app: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) def __str__(self): return self.user.username In the admin of Order I've displayed the respective user for the particular order like so: class OrderAdmin(admin.ModelAdmin): list_display = ('__str__', 'date_ordered', 'is_ordered', 'buyer_email') def buyer_email(self, instance): return instance.owner.user.email I want to display this buyer_email in list_display of order as a link, right now it's just a text. One thing to note here is Profile has again OneToOneField with AUTH_USER_MODEL. I want the link to got to the Profile or if we can send it to the AUTH_USER_MODEL user, it would be of much help! -
How to resolve IntegrityError which caused Foreign Key constraint failed
I encountered this error when trying to change/add/delete users in the Admin. I don't really know what is referencing my model, that has caused the Foreign KEY Constraint to fail. Below is the model.py, forms.py, and admin.py Model.py This is my custom user model for the Signup. class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) class User(AbstractUser): first_name = models.CharField(max_length=35, blank=False, null=False) last_name = models.CharField(max_length=35, blank=False, null=False) username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() forms.py Also, my form is defined as this class SignUpForm(UserCreationForm): class Meta: model = User fields = ('first_name', 'last_name', 'email',) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) helper = self.helper = FormHelper() layout = helper.layout = Layout() for field_name, field in self.fields.items(): layout.append(Field(field_name, placeholder=field.label)) helper.form_show_labels = False … -
Leaflet marker cluster not displaying
I'm showing a map using leaflet with clusters on it. all works fine when I zoom in The icon doesn't show up and I get an error in the console. error: https://imgur.com/a/xfL94Sz I am following this example however I can't seem to figure out the problem http://intellipharm.github.io/dc-addons/examples/leaflet-marker.html I'm building this map withing a django project if this might help result that i got: https://imgur.com/DEAd0Dp expected result : https://imgur.com/HJrxzzS -
Difficulty writing tests, getting wrong responses?
My problem: I'm writing tests and I'm getting 302 responses instead of 200. I figure this is kind of expected because when a user isn't logged in and isn't assigned to the group Employee_Management, they will always be redirected. So I'm trying to create a user and add it to the group, but I have no idea how to check if the user is actually logged in, or if it is part of the group. I get no errors from the setUp, but the test still fails and gives me a 302. So my guess is I've messed up my setUp. Ideas? view: @method_decorator(group_required('Employee_Management'), name='dispatch') class ListActiveView(TemplateView): def get(self, request): users = User.objects.all().exclude(is_superuser=True) return render(request, 'user/list_active.html', { 'users': users, }) urls: app_name = 'user' urlpatterns = [path('list_active/', ListActiveView.as_view(), name='list_active')] test: class TestListActive(TestCase): def setUp(self): user = User.objects.create(username='testuser', password='testuserpass') emp_man = Group.objects.create(name='Employee_Management') user.groups.add(emp_man) c = Client() c.login(username='testuser', password='testuserpass') def test_list_active_url(self): response = self.client.get(reverse('user:list_active')) self.assertEquals(response.status_code, 200) -
Restarting a python project in the virtual environment - where are the parentheses?
I was working on a python project with django in a virtual environment but had to come back to it the next day and turned of terminal. Before, it had the name of the project in (). I think I have opened the directory I was in, but it doesn't have the () just the name of the project plus the $ symbol. Am I still working on it? -
Is it possible to extend the Django extends tag
I'm trying to create a dynamic template loader for a Django project that can be used across multiple brands just by changing an environmental variable. I'm injecting the context with a variable called brand_module and I would like to use this when it's not set to None. Is this possible. Can I fall back on a default like so? {% extends brand_module|add:"/base.html"|default:"base.html" %} Which I would like to try to look in "BRAND_NAME/base.html" if the variable is set or "base.html" if it's not. -
How can i identify my css to my django project
i am new at django and i could not identify CSS to my django project i even read the docs but my project is still wrong in simple english please help me to fix this this is important parts of my project as i said i am beginner in django so this is a very very simple setting.py """ Django settings for myshop project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'uhln7d--gk-(i6+py1@f)#su35249@@noydffkj$jd4$l(obj)' # 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', 'shop.apps.ShopConfig', ] 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', ] ROOT_URLCONF = 'myshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = … -
Syntax error cannot import React and React-Dom
I'm getting a syntax error when trying to import React and React-Dom, I'm totally new to react and would appreciate if you could help me. SyntaxError: C:/Users/Genti/Anaconda3/envs/MMS/geodjango/MMS/static/js/index.js: Unexpected token (1:18) > 1 | import React from react; | ^ 2 | import ReactDOM from 'react-dom'; 3 | 4 | function Hello(props) { this is my code: import React from react; import ReactDOM from 'react-dom'; function Hello(props) { return <h1> Hey, {props.name} </h1> } const element = <Hello name="Gent" />; ReactDOM.render( element, document.getElementById('react') ) -
gunicorn: error: argument --error-logfile/--log-file: expected one argument
I am trying to make a gunicorn bash executable file to run django server but getting error - gunicorn: error: argument --error-logfile/--log-file: expected one argument. Its working fine with - gunicorn bekaim_pre_registration.wsgi:application --bind 0.0.0.0:8001 but getting error with bash file. Here is my - gunicorn_start.bash #!/bin/bash NAME="django_app" # Name of the application DJANGODIR=/home/ubuntu/bekaim_pre_registration # Django project directory SOCKFILE=/home/ubuntu/django_env/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=bekaim_pre_registration.settings # which settings file should Django use DJANGO_WSGI_MODULE=bekaim_pre_registration.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ubuntu/django_env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file To make this script executable. $ sudo chmod u+x gunicorn_start.bash When I test - ./gunicorn_start.bash Starting django_app as ubuntu usage: gunicorn [OPTIONS] [APP_MODULE] … -
Django rest multiple models sorting result and pagination
I in need to get multiple result from many models and I did it by using django rest multiple models but I need to sort the results and paginate it. I did sorting and pagination also. But I read and faced an issue for my business which is. I need to retrieve for example 10 results in every page from all models and may some time the same page contains all results from same model, which is not available in django rest multiple models. As their document, "The limit in LimitOffsetPagination is applied per queryset. This means that the number of results returned is actually number_of_querylist_items * limit. This is intuitive for the ObjectMultipleModelAPIView, but the FlatMultipleModelAPIView may confuse some developers at first when a view with a limit of 50 and three different model/serializer combinations in the querylist returns a list of 150 items. The other thing to note about MultipleModelLimitOffsetPagination and FlatMultipleModelAPIView is that sorting is done after the querylists have been filter by the limit/offset pair. To understand why this may return some internal results, imagine a project ModalA, which has 50 rows whose name field all start with ‘A’, and ModelB, which has 50 rows whose … -
Django array field foreign key
I have extended my user mode with a profile that has an optional field that is an array. Each element in the array can be is a unique value from a field in another table. In that specific table, I have a field that is an array field that I want to hold the email addresses of the users that have that option in their array field. Is there a way that I can make it to where that field contains the email addresses of the users that have that particular fields value in their array field? And if that element gets removed from the user profile array field it gets removed from that table’s array as well? -
How to fix name 'fieldname' is not defined in django admin.py
I am working on a django app where I have a members model and another model called reviews. My members model class Members(models.Model): TITLES = (('chairman', 'Chairman'), ('secretary', 'Secretary'),) user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=10, choices=TITLES, default='secretary') active = BooleanField(default=False) My reviews model class Reviews(models.Model): chairman = models.ForeignKey(Members, related_name='chairs', on_delete=models.PROTECT) secretary = models.ForeignKey(Members, related_name='secretaries', on_delete=models.PROTECT) review = models.TextField() There could be several chairmen and secretaries but in the foreign key drop down, on the Reviews model, I would like to only display the ones who are active (i.e have the active field set to True). I have tried to achieve that by having the following in my admin.py... class ReviewsAdmin(admin.ModelAdmin): ... def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "chairman": kwargs["queryset"] = Members.objects.filter(title=='chairman', active==True) elif db_field.name = "secretary": kwargs["queryset"] = Members.objects.filter(title=='secretary', active==True) return super().formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Reviews, ReviewsAdmin) I'm getting the error, name 'title' is not defined around where I'm doing the filter. What is wrong here? -
django pagination filter - according to one row but getting error
i have 1 table name "Post" in which i have multiple rows one of them is 'cat'(row-category) i just wanna filter data that if my url contain cat=1 so it show all the cat 1 listings My Views.py i tried this but getting error. please guide me what i am doing wrong? def listing(request,post_cat): var_cat = get_object_or_404(Post, cat=post_cat) user_list = Post.objects.all(var_cat) paginator = Paginator(user_list, 5) page = request.GET.get('page') try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, 'ads/listing.html', { 'users': users }) -
Celery cannot connect to Redis
The celery cannont connect to Redis server. Here you can see the output of the command celery -A mysite worker -l info: cp058:NCNSAC username$ celery -A mysite worker -l info Warning: SSH not available Warning: SSH not available -------------- celery@cp058.local v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Darwin-18.0.0-x86_64-i386-64bit 2019-02-05 09:36:25 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: mysite:0x104b4f0f0 - ** ---------- .> transport: redis://localhost:6379/0 - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . devadmin.tasks.do_work_ChangeConfig . devadmin.tasks.do_work_CheckConfig . devadmin.tasks.do_work_Netcrawler . devadmin.tasks.do_work_SecureCRT . mysite.celery.debug_task [2019-02-05 09:36:26,000: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 8 connecting to localhost:6379. nodename nor servname provided, or not known.. Trying again in 2.00 seconds... [2019-02-05 09:36:28,005: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 8 connecting to localhost:6379. nodename nor servname provided, or not known.. Trying again in 4.00 seconds... Any solution for this problem? Thank you. -
In test.py, how do I create a user, add user to group in the setUp function?
Writing tests, most of my app is hidden unless you belong to a certain group, so I will need to make a test user that belongs to that group. I want to do this in the setUp function so all following functions can use this user. -
factory boy - how to create the required data of a factory (pre-generation hooks)
note: I will try to explain the use case with a simplified scenario (which might look really odd to you). I am having 2 models (which are related but do not have a foreign key): # models.py class User(models.Model): name = models.CharField() age = models.IntegerField() weight = models.IntegerField() # there are a lot more properties ... class Group(models.Model): name = models.CharField() summary = JSONField() def save(self, *args, **kwargs): self.summary = _update_summary() super().save(*args, **kwargs) def _update_summary(self): return calculate_group_summary(self.summary) # this helper function is located in a helper file def calculate_group_summary(group_summary): """calculates group.summary data based on group.users""" # retrieve users, iterate over them, calculate data and store results in group_summary object return group_summary for above models I have this factories: # factories.py class UserFactory(factory.DjangoModelFactory): class Meta: model = User name = factory.Sequence(lambda n: "user name %d" % n) age = randint(10, 90)) weight = randint(30, 110)) class GroupFactory(factory.django.DjangoModelFactory): class Meta: model = Group name = factory.Sequence(lambda n: "group name %d" % n) summary = { "users": [34, 66, 76], "age": { "mean": 0, "max": 0, "min": 0, }, "weight": { "mean": 0, "max": 0, "min": 0, } } the particularity is that I update the JSON data in field group.summary on group.save(). … -
How to keep original ID using UUID as primary key in Django RF project?
I'd like to use two different primary keys in my DRF database app. By default django "create" id as PK but when i'm trying to define new field in model (uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)), default id field is not defined (in DB exist only uuid). How to initialize both of them ? I can mention that i did't define id field in my model because it is (or should be - as i suppose) adding by DRF. class Store(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=False) url = models.URLField(max_length=300, blank=False) country = models.CharField(max_length=100, blank=True) -
Empty Django Form Select Field
I want empty job_users field before sending to the template. Because job_groups and job_users is dependent. I am calling ajax call when the group is select and users of that group will be displayed inside job_users. But now all users are displayed inside job_users select field. class JobForm(forms.ModelForm): job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15})) job_users = None class Meta: model = Jobs fields = [ 'job_name', 'job_group', 'job_users', ] def __init__(self, *args, **kwargs): self.user_company = kwargs.pop('user_company', None) super().__init__(*args, **kwargs) self.fields['job_group'].queryset = None self.fields['job_group'].queryset = None i am using this but it is giving me error -
Adapting MultiHostMiddleware for django 2.1+
I have a single django project with several different apps that are supposed to be hosted on different domains. For example let's call them: Administrative site, ourdashboard.com First Content site oursite1.com Second Content site oursite2.com Dashboard site is only for content publishers, while content sites are for visitors. Each site is different in terms of functionality, content and design. I want publishers to be able to post content on both sites, so I don't wont to create different django projects. But the genre of the content requires different sites for specific audience. I started an app called dashboard. I would like this app to be hosted on ourdashboard.com domain, where accessing this domain will directly access dashboard.urls. So basically I want to host multiple sites using a single django project, where each domain will be linked to a specific app url file. I did a little bit of a research, and stumbled upon MultiHostMiddleware and tried to implement it. Looked simple and easy, but having never worked with djangos middleware before, I hit the brick wall right at the start. I properly implemented the code as instructed but I kept getting 500 Internal Server Error. Initially I thought I messed … -
Template Based : Load Dynamic Content in Django Through Ajax using Dynamic URL Pattern based on Slug
Facing issues for loading (including) dynamic content through a template tag "include" or from 'Ajax' based Loading. As said Here, There are three ways to do... But still having issues Working on Django 2.1.3, Python 3.6... I have tried two ways: 1. Using "Include" Tag 2. By Loading Through Ajax Python views.py def equity(request,symbol): """ some code """ context_all = { 'template_Name': ('/autoRefreshEqu/{}/').format(symbol) } template = loader.get_template('equity/equity.html') response_body = template.render(context_all,request) return HttpResponse(response_body) def autoRefreshEqu(request,symbol): """ code for generating context """ context_all = { 'quote':quote, 'changeQuote':changeQuote, 'lastPrice': x['data'][0]['change'], 'change':x['data'][0]['change'], 'pChange':x['data'][0]['pChange'], 'lastUpdateTime': x['lastUpdateTime'], } template = loader.get_template('equity/autorefequ.html') response_body = template.render(context_all,request) return HttpResponse(response_body) urls.py path('autoRefreshEqu/<slug:symbol>/',views.autoRefreshEqu, name="autoRefreshEqu"), path('equity/<slug:symbol>/',views.equity, name="equity"), HTML Section equity/equity.html Reference Provided for Comment With Nos. as Guidance in Description. <!-- Code Persists + Load Static + Humanize + Extends base.html, all working well --> <!-- Reference for 2. --> <script>$("#autoupdate").load("{% url template_Name %}");</script> <div id="autoupdate"> <!-- Reference for 1. --> {include template_Name} <!-- Load The Content Generated by autoRefreshEqu/<slug:symbol>/ --> </div> equity/autorefequ.html {% load humanize %} {% load static %} <div class="card text-center"> <div class="card-header"> <h2 class="alignleft">Current Price</h2> <p class="alignright"><label class="switch"> <input type="checkbox" > <span class="slider"></span></label></p> <!--p class="alignright"><label class="switch"> <input type="checkbox" checked> <span class="slider"></span></label></p--> </div> <div class="card-body"> <!--h5 class="card-title"></h5--> <p class="card-text"> … -
not able to fetch comment from django templates
I am trying to build a social network in django. In this code I am trying to enter comments to a post through the template box in my template. But the comment is not getting fetched in my database. My code is as below: My forms.py creates a model form for comments forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('ctext',) Models has a seperate comment model which has foreign keys from post model and user model. models.py class Comment(models.Model): comment_auth = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.ForeignKey(Post, on_delete=models.CASCADE) ctext = models.TextField(blank=True, null=True, max_length=200) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.ctext I guess the logic in views is going wrong somewhere as it been shown while debugging views.py def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') post = get_object_or_404(Post, title=title) cform = CommentForm() comments = Comment.objects.all() if request.method == "POST": comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() #cform = CommentForm(request.GET) #data = {} #Comment.ctext(**data) #if cform.is_valid(): #comment={} #comment['ctext'] = request.POST['ctext'] #cform.changed_data['comment_auth'] = request.user #cform['comment_auth'] = request.user #cform['comment_auth_id_id'] = request.user #cform.save() return render(request, 'users/post_list.html', {'posts': posts, 'comments': comments, 'form': cform}) else: form = CommentForm() return render(request, 'users/post_list.html', {'posts': posts, 'comments': … -
Django opening balances calculations
I am trying to create a simple inventory app using Django. My project came to a stand still when I couldn't find a solution for calculating opening and closing balances on the fly/dynamically. I tried for days researching on the web but no progress yet. If anyone could help i will appreciate. All I need is a query to calculate opening and closing balances dynamically. My Models: class Item(models.Model): name = models.CharField(max_length=30) buying_price = models.PositiveIntegerField() selling_price = models.PositiveIntegerField() quantity = models.PositiveIntegerField() def __str__(self): return self.name class SalesSheet(models.Model): txn_date = models.DateField() item = models.ForeignKey(Item, on_delete=models.CASCADE) purchases = models.PositiveIntegerField() sales = models.PositiveIntegerField() What I want after posting purchases and sales is an output like this id date item opening purchases sales closing 1 1-1-19 abc 10 20 5 25 2 2-12-19 def 25 20 10 35 3 3-1-19 abc 25 10 25 10 4 4-1-19 def 35 10 30 15 5 7-1-19 abc 10 0 0 10 6 9-1-19 def 15 0 5 10 and so on..... I am using item.quantity to store opening stock for the first time only. Take into consideration that there will be different items and also back dated entries. help me guys. -
Using Custom Search Form Post with jQuery Datatables/Ajax in Django
I'm using Djano 2.x and Django-Datatable-View to display table data on a website. I've got a very large table that I want to display only after some search fields have been populated. I've set up the search form using the POST method to filter the table and generate the new queryset. I'm rather new to the web, particularly ajax and js and have run into a problem with the my approach and the way that the datatable seems to be loaded. the post method in the view looks like: def post(self, *args, **kwargs): context = self.get_context_data() return render(self.request, self.template_name, context) I filter the get_queryset method as the docs and others have suggested. Inside of Django-Datatable-View package however this method is called twice. Once in the get_context_data method, and once in the dispatch method. I've copied some of the terminal log below. I added a print to check if there are any Ajax calls and you can see that it sends a GET call, after my POST call, using the dispatch method in the underlying mixin. The problem is that by the time this GET method is called, all the search params and the filtered queryset are long gone and it … -
MultiValueDictKeyError at /count/ while using .GET[]
I am getting the below-mentioned error while executing the code:- MultiValueDictKeyError at /count/ 'textbox' Request Method: GET Request URL: http://127.0.0.1:8000/count/ Django Version: 2.1 Exception Type: MultiValueDictKeyError Exception Value: 'textbox' Exception Location: /Users/rajans/anaconda3/lib/python3.7/site-packages/django/utils/datastructures.py in getitem, line 79 Python Executable: /Users/rajans/anaconda3/bin/python Python Version: 3.7.0 Python Path: ['/Users/rajans/Documents/djangoprojects/wordcount', '/Users/rajans/anaconda3/lib/python37.zip', '/Users/rajans/anaconda3/lib/python3.7', '/Users/rajans/anaconda3/lib/python3.7/lib-dynload', '/Users/rajans/anaconda3/lib/python3.7/site-packages', '/Users/rajans/anaconda3/lib/python3.7/site-packages/aeosa'] Server time: Tue, 5 Feb 2019 06:39:06 +0000 Python from django.http import HttpResponse from django.shortcuts import render def homepage(request): return render(request,'home.html') def contact(request): return HttpResponse("<h2> This is a contact_us page</h2><br> You can write to rajan.sharma@freshworks.com for any query") def count(request): data=request.GET['textbox'] data_list=split(data) data_len=len(data_list) return render(request,'count.html',{'length':data_len}) -------- html form:- <h1>Word Count</h1><br> This is the home page for the Word count. <form action="{% url 'count' name%}"> <!-- "{% url 'count' %}". this will load the url even if the path is changed..it will look for the name count--> <textarea name="textbox" cols=40 rows="10"></textarea><br/> <input type="submit" value="count"/> </form> count.html <h1>Counted</h1><br/> The length is :- {{length}} -
How to create django class from exist table
I have django project and have to migrate one table (that table didn't define like a django class in model.py, but it is exist in postgres DB) from postgresql to django. Witch instrument can to create class from exist table in database?