Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where in Django code put code disconnecting signal and doing monkey-patching?
I'm working on custom authorization backend for Django 2.2. I don't want django to update last_login for user so I wanted to disconnect signal user_logged_in from triggering update_last_login. I also have to do monkey patch in SimpleJWT library changing User to point OtherUserModel Where is the best place to put this code? For now, I have added in CoreConfig.ready method and it works but is it a good place for this logic? from django.apps import AppConfig class CoreConfig(AppConfig): name = 'core' def ready(self): from django.contrib.auth import user_logged_in from django.contrib.auth.models import update_last_login user_logged_in.disconnect(update_last_login, dispatch_uid='update_last_login') import rest_framework_simplejwt.state rest_framework_simplejwt.state.User = OtherUserModel -
Showing the uploaded csv file on Django template
I have a project that accepts an uploaded .csv file and shows it on the admin via the models.py. What I want to happen is to show these uploaded .csv file on the template. my views are: def data_upload(request): template = "home.html" if request.method == 'GET': return render(request, template) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a .csv file.') data_set = csv_file.read().decode('ISO-8859-1') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=','): _, created = Table.objects.update_or_create( page=column[0], keyword=column[1], interval=column[2], email=column[3], notes=column[4], billing=column[5], ) context = {} return render(request, template, context) The views are already working when I upload the .csv file. On the home.html file, this is what I did: <table class="table table-condensed"> <thead> <tr> <th>...</th> </tr> </thead> <tbody> <tr> <th class="center-align" scope="row"><i class="small material-icons green">check</i></th> {% for t in tables %} <td class="center-align">{{t.page}}</td> <td class="center-align">{{t.keyword}}</td> <td class="center-align">{{t.interval}}</td> <td class="center-align">{{t.email}}</td> <td class="center-align">{{t.notes}} </td> <td class="center-align">{{t.billing}}</td> {% endfor %} </tr> </table> How do I properly iterate on the template to show what I uploaded on my html file? -
Django runserver not running when importing another python file
I'm new to Django, so I am trying to import a python file in the views.py inside my Django app. When I run the server with python manage.py runserver it's not doing anything. When I comment out the import part it works for some odd reason I've already tried some solutions. Like: import [file] from . import [file] from .[file] import [function in the file] and all these still didn't work. DETAILS: -Python version 3.7.3 -Django version 2.2.5 CODE: Note: this is in views.py import bot def process(request): username = request.POST["username"] email = request.POST["email"] code = generate_code(random.randrange(5, 12)) data = {"username": username, "email": email, "code": code} bot.say("Hi", channel_id=600617861261819906) return render(request, "process.html", data) -
Unit Testing - Get Request that includes JSON-data
I´m currently creating Unit-Tests for existing endpoints. I have a GET-Request Endpoint to whom I send JSON Data is a kind of filter parameters. By using Postman everything works well. When I create the Unit-Tests the JSON Parameters are not used. In the documentation I saw that data in the request is send as Parameter in the URL. But that is not working for me. Thanks in advance! Checked the django documentation Views.py def get_queryset(self): return self.model.objects.filter( **{ field + '_id': self.request.data[field] for field in ['post', 'user', 'product'] if field in self.request.data } ).order_by( '-time_stamp' ) Unit Test response = self.client.get( "/api/v1/post/get_clicks_stats/", data={ "user": "5b1d4efa-09e1-4a29-ba50-314d34cd50f0", } ) self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['count'], 1) -
SQL script replace all id in data base
I have imported not correct data. All users in my data base have id with .0, for exaple user.id 123321.0. I need to replace all .0 from all database. I have writen script like this: UPDATE users_groups, user_synchronization, `user additional info`, major_minor, commitment, budget, users SET users_groups.user_id = REPLACE(users_groups.user_id, '.0', ''), user_synchronization.user_id = REPLACE(user_synchronization.user_id, '.0', ''), `user additional info`.user_id = REPLACE(`user additional info`.user_id, '.0', ''), major_minor.major_id = REPLACE(major_minor.major_id, '.0', '') AND major_minor.minor_id = REPLACE(major_minor.minor_id, '.0', ''), commitment.dealer_id = REPLACE(commitment.dealer_id, '.0', '') AND commitment.grower_id = REPLACE(commitment.grower_id, '.0', ''), budget.user_id = REPLACE(budget.user_id, '.0', ''), users.id = REPLACE(users.id, '.0', ''); but i have an error: Data truncation: Truncated incorrect DOUBLE value: 'D22203' -
Running manage.py shell with -c flag within docker-compose run
I want to run a script that runs Django code in my docker container. My initial plan was to run the following: docker-compose run web python manage.py -c "import django; print(django.__version__)" However, that isn't working: it prompts manage.py shell: error: unrecognized arguments. I guess it has to do with the fact that -c is a flag shared both by manage.py and by bash, or at least that's what I gathered from the docker-compose docs and Django's. If I run docker-compose run web bash, it prompts the shell, where I can do python manage.py shell -c "...". How can I do that in just one step? Any help is much appreciated. -
Getting Check that 'apps.ChatbotConfig.name' is correct. after restructuring
I changed my project's structure adding everything in a src folder, but my server stopped working. The error i'm getting is : Cannot import 'chatbot'. Check that 'apps.ChatbotConfig.name' is correct I tried looking for an answer, and most of the suggest to change apps.py to name = 'src.chatbot', but that didn't work for me. Tried changing the apps.ChatbotConfig.name but if change anything, it says no Module named 'chatbot'. Here is my structure. base.py DJANGO_APPS = [ "apps.ChatbotConfig", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "django.contrib.messages", # "django.contrib.humanize", # Handy template tags "django.contrib.admin", "debug_toolbar", 'django.contrib.staticfiles', ] apps.py from django.apps import AppConfig class ChatbotConfig(AppConfig): name = 'chatbot' admin.py from django.contrib import admin from django.apps import apps app = apps.get_app_config('chatbot') for model_name, model in app.models.items(): admin.site.register(model) Full traceback Traceback (most recent call last): File "C:\Users\lbajarunas\virtualenv\lib\site-packages\django\apps\config.py", line 143, in create app_module = import_module(app_name) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'chatbot' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "C:\Users\lbajarunas\virtualenv\lib\site-packages\django\core\management\__init__.py", line … -
django: How to render CharField as right to left?
In my app froms.py I defined my textfield as: class ContactForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'نام' } )) but as it can be seen in the screenshot, the text of placeholder and the actual text (that user would add) is being rendered left to right. How can I make it to render in right to left form? -
Effective ways of reusing python-request in function for internal api calls
I'm using python request lib for internal calls in our Django app. we have many helper functions for such internal calls. The problem with this approach is we are repeating the same function for different internal calls. Differences being request_url, request_data, request_response(tuple/list/dict). We are using the following function for internal calls, the same function is used for different calls based on the difference in input data, URL and response. for ex: get_data_from_service1, get_data_from_service2 etc def get_data_from_service(data): request_url = BASE_URL + "api/post/service/" request_data = rqt.get_service_request_translator(data) try: request_response = requests.post(url=request_url, data=request_data) except requests.exceptions.RequestException as ex: logger_excp.exception(str(ex)) return error_msg.UNABLE_TO_REACH_SERVICE if request_response.status_code == 200: models_data = request_response.json().get("data") total_count = request_response.json().get("total_count") return models_data, total_count elif request_response.status_code == 500: logger.error(request_response.text) return error_msg.PROBLEM_WITH_SERVICE else: logger.error(request_response.text) return error_msg.SOMETHING_WENT_WRONG please help with the following points. What would be an effective way of not repeating function everywhere should something like a base class be used? How to handle timeouts at global(base class/factory function?) and local functions? for ex: a base class/function having a timeout of say timeout=5 while local function having a timeout of timeout=2 or no timeout at all. how to change the error response of such functions. say for example if I want to raise an exception instead … -
Creating a control number for controlling a post
I want to create a control number that will be controlling every post posted by user, every time a user post in the site control number should be attached in the database in each post. Same number will be used for mobile payment, once user has payed using control number post will be deleted I want to use primary key to generate numbers but I get error named "1091, "Can't DROP 'id'; check that column/key exists"" views.py @login_required def Claim(request): max_val = Documents.objects.aggregate(max_no=Max('pay_no'))['max_no'] or 0 # then just make new object, and assign max+1 to 'that_field_in_question' control_number = Documents(pay_no=max_val) control_number.save() return render(request, 'loststuffapp/claim.html', context={'documents':Documents.objects.all()}) models.py class Documents(models.Model): docs_name = models.CharField(max_length=200) item_type = models.CharField(default="", max_length=100 ) police_station = models.CharField(max_length=255,) phone_no = models.CharField(max_length=10, blank=False, validators=[int_list_validator(sep=''),MinLengthValidator(10),]) date = models.DateTimeField(default=timezone.now) Description = models.TextField(blank=True, null=True) pay_no = models.IntegerField(default=11001, primary_key=True) publish = models.BooleanField(default=False) image = models.ImageField(upload_to="Documents",blank=False) """docstring for Documents""" def __str__(self): return self.docs_name -
Django query OneToMany by multiple fields
I have schema similar to this one (obviously this one is simplified) class Pet(models.Model): name = TextField() date_vaccinated = DateTimeField(null=True) # null indicates no vaccination owner = ForeignKey(Person, related_key="pet") class Person(models.Model): name = TextField() people_with_a_vaccinated_pet_named_rex = Person.objects.filter(pet__date_vaccinated__isnull=False, pet__name="Rex") As indicated in the last line I'm trying to find all people who have a pet called Rex that is also vaccinated. The query I wrote will find all people with a pet named rex, and a vaccinated pet (not necessarily the same pet..) Is there a way to query with multiple conditions on the same OneToMany relation? P.S the real query I'm trying to write is more similar to the following: Person.objecs.filter(pet__class1__date__isnull=False, pet__class1__class2__class3__name="blabla") where I want to reach class 3 only through class1 instances that their date is not null -
how to pass default value from database to mapfield panel in wagtail
This is my code.zoom_level is a column in my model, so i want to pass the respective value as default zoom value in my mapfieldpanel zoom_level = models.CharField(max_length=255) MapFieldPanel('latlng_address',latlng=True,zoom=zoom_level) but i am getting error like Object of type 'CharField' is not JSON serializable I tried MapFieldPanel('latlng_address',latlng=True,zoom='zoom_level'), zoom_level is passing as a string.How i can pick the value from database and pass it as a default value -
How to extend django UserCreationForm model to include phone number field
I cant seem to find any posts here regarding extending the Django UserCreationForm model to include a phone number field for users to enter their number and then validate the phone number using phonenumbers.parse in the backend to check if the number is in the respective format and whether it exists or not. I need to know what code I should include in my forms.py under my "users" app. I've tried including normal html text field for the phonenumbers and it does not belong to the default UserCreationForm model in Django and neither can it be stored in the database. (I need it to be stored in the database for the phone numbers). I am only using forms.py, views.py and register.html to be rendered in views as shown below, currently I am not using models.py. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user /* views.py */ from django.shortcuts import render, redirect from django.contrib import … -
Setting the choice field of one variable according to the value of another variable in the same form
I'm trying to plot graphs based on the values of the form variables in my django template. I have 4 variables (ChoiceFields) in my form I want my second choice field to change the choices with respect to the value of first variable Eg. is var1='age' var2_options=['M','F'] if it is var1='Education', var2_options=['Bachelors','Masters','High School'] here's my code: views.py- class HomeView(TemplateView): template_name='charts.html' def get(self, request): form = HomeForm() return render(request, self.template_name, {'form':form}) def post(self,request): form=HomeForm(request.POST) if form.is_valid(): text_1 = form.cleaned_data['post_1'] global z z=text_1 text = form.cleaned_data['post'] global b b=text text1 = form.cleaned_data['post1'] global c c=text1 text2 = form.cleaned_data['post2'] global d d=text2 args = {'form':form, 'text_1':text_1,'text':text, 'text1':text1, 'text2':text2} return render(request, self.template_name, args) charts.html (template) <form method="POST"> {%csrf_token%} {{form.as_ul}} <button type="submit">get</button> {{form.as_ul}} <button type="submit">PLOT GRAPH</button> </form> forms.py class HomeForm(forms.Form): post_1 = forms.ChoiceField(choices=((None,None),('लिंग :','sex :'),('शिक्षण:','education:'),('जात :','caste :'),('व्यवसाय :','occupation :'))) post = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'),('व्यवसाय :','व्यवसाय :'))) post1 = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'),('व्यवसाय :','व्यवसाय :'))) post2 = forms.ChoiceField(choices=((None,None),('bar','bar'),('horizontalBar','horizontalBar'),('line','line'))) I have arrays of choices ready for each variable How can I pass one variable and then assign the choice field of next variable according to it? -
Django: Is there a way to specify key_name of MySql index in migrate?
There is the following model, and you are trying to set index_together. class Event(models.Model): class Meta: ordering = ["-id"] index_together = ["user", "action"] action = models.IntegerField(db_index=True) user = models.ForeignKey("users.User", on_delete=models.CASCADE) post = models.ForeignKey("posts.Post", null=True, on_delete=models.CASCADE) When python manage.py makemigrations is executed, the following migration file is generated class Migration(migrations.Migration): dependencies = [ ('users', '00xx_auto_yyyymmdd_hhmm'), ('events', '00xx_auto_yyyymmdd_hhmm'), ] operations = [ migrations.AlterIndexTogether( name='event', index_together=set([('user', 'action')]), ), ] SHOW INDEX FROM tbl_name; in MySQL, index is assigned. Is it possible to specify Key_name? I want to use ignore_index anduse_index from Python code, so I want to specify the index Key_name by myself. Is there any way? -
Django: Read child objects from parent object effectively
I am fairly new to django and want to know the most effective way to go about my requirement here. I am creating a project tracking app, where a single project can have many team members and clientteam members and also multiple feedbacks. I have a table for team members and clientteam individually, but I also want to track the role of each team member within a project. I tried the following model structure using a mapping table, but now I am struggling to fetch data from it to django template. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Project(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) primary_contact1 = models.CharField(max_length=100) primary_contact2 = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() owner = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) date_last_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Teammember(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) def __str__(self): return self.first_name + " " + self.last_name def get_absolute_url(self): return reverse('teammember-detail', kwargs={'pk': self.pk}) class ProjectTeam(models.Model): project_team_member = models.ForeignKey(Teammember, related_name="project_team_member", on_delete=models.SET_NULL, null=True) project = models.ForeignKey(Project, related_name="project_team_project", on_delete=models.CASCADE) project_role = models.CharField(max_length=50) def __str__(self): return self.project.title + " - " + self.project_team_member.first_name + … -
ModuleNotFoundError: No module named 'wsgi'
I was going to host it using Heroku. But it does not work because of the problem with the profile. This my Procfile -> web: gunicorn wsgi:app I tried these things. ->web : gunicorn wsgi.py ->web : gunicorn .wsgi --log-file- my wsgi.py code """ WSGI config for config project. It exposes the WSGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) this is my heroku log Starting process with command gunicorn wsgi:app 2019-09-13T06:06:27.409894+00:00 heroku[web.1]: State changed from starting to crashed 2019-09-13T06:06:27.388714+00:00 heroku[web.1]: Process exited with status 3 2019-09-13T06:06:27.176179+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-09-13T06:06:27.177866+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [4] [INFO] Listening at: http://0.0.0.0:56276 (4) 2019-09-13T06:06:27.177959+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [4] [INFO] Using worker: sync 2019-09-13T06:06:27.181907+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [10] [INFO] Booting worker with pid: 10 2019-09-13T06:06:27.187052+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [11] [INFO] Booting worker with pid: 11 2019-09-13T06:06:27.187674+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [10] [ERROR] Exception in worker process 2019-09-13T06:06:27.187678+00:00 app[web.1]: Traceback (most recent call last): 2019-09-13T06:06:27.187680+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2019-09-13T06:06:27.187682+00:00 app[web.1]: worker.init_process() 2019-09-13T06:06:27.187684+00:00 app[web.1]: File … -
Django: TemplateView with selenium
I use djangos TemplateView. One of the attribute is a webbrower. My question is now, how can I automatically quite/kill/exite/close the webbrower if the server is restartet? I alreay tried to use "try and exception" class Heatmap(TemplateView): template_name = "map.html" options = Options() if platform.system() == "Windows": options.headless = False else: def post(self, *args, **kwargs): """ @description: -
django html file is not showing
It keeps showing index.html file instead of register.html file which is supposed to display register form. Please help this newbie.. I will provide more info if needed. i checked with all the files i have been working on and googled similar issues but i cant find a solution. sdjflasjfsfjdsjdkdkdkdkdkdkslal dsfas dafsfds dafdsafdas dsfsafsavsavsavswgweg '''my views.py''' # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic.edit import FormView from django.shortcuts import render from seany_user.forms import registerform # Create your views here. def index(request): return render(request, 'index.html') class registerview(FormView): template_name = 'register.html' form_class = registerform '''my forms.py''' from django import forms class registerform(forms.Form): email = forms.EmailField( error_messages={ 'required': 'enter your goddamn email' }, max_length=64, label='email' ) password = forms.CharField( error_messages={ 'required': 'enter your password' }, widget=forms.PasswordInput, label='password' ) re_password = forms.CharField( error_messages={ 'required': 'enter your password' }, widget=forms.PasswordInput, label='confirm password' ) ''' my register.html''' {% extends "base.html" %} {% block contents %} <div class="row mt-5"> <div class="col-12 text-center"> <h1>register</h1> </div> </div> <div class="row mt-5"> <div class="col-12"> {{ error }} </div> </div> <div class="row mt-5"> <div class="col-12"> <form method="POST" action="."> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> <input type="{{ field.field.widget.input_type }}" class="form-control" … -
How to call a view class from another view class in django rest framework?
I have a project structre as following, .. ├── project │ ├── app1 │ ├── manage.py │ ├── project │ └── app2 │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── tests.py │ └── views.py ├── app2_views── project │ ├── main_view.py │ ├── view1.py │ ├── view2.py i want to call classes defined in view1.py in my main.py I have tried the following code, main.py from rest_framework import viewsets from app2.app2_views.view1.py import class1 class mainclass(viewsets.ModelViewSet): class1.view1_data() view1.py from app2.models.py import table1 from rest_framework import viewsets from app2.serializers.py import seri1 from django.db.models import Sum class class1(viewsets.ModelViewSet): def view1_data(): queryset = table1.objects.values('column') serializer_class = seri1 but i am getting an error saying should either include a `serializer_class` attribute, or override the `get_serializer_class()` method i am new to python, what am i doing wrong here? Thank you for your suggestions -
Cannot import s3
i am trying to import s3 so i can use the code `conn = S3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) as used here but i get this error import s3 File "C:\Users\abcedfghijk\Envs\myblog\lib\site-packages\s3__init__.py", line 1, in from .s3 import * File "C:\Users\abcedfghijk\Envs\myblog\lib\site-packages\s3\s3.py", line 253 except Exception, e: ^ SyntaxError: invalid syntax please help out.. thanks -
Serving static files in django with Nginx and gunicorn
Hi guys im trying to run my project on nginx with gunicorn. I have successfully access it but i have a problem on serving static files. I totally understand how manage.py collect static works but i think i am missing something on my configuration file in nginx or in my settings.py. Hoping you can help me. -
Pymongo Mongoclient connection issue
I have enabled the authentication of MongoDB from its config file and added one user with readWriteAnyDatabase role. Below is the query: db.createUser( { user: "username", pwd: "password", roles: [ { role: "readWriteAnyDatabase", db: "admin" } ] } ) I am trying to authenticate to MongoDB with pymongo on my local system but getting the below error: I am using the below configurations: pymongo==3.5. python 3.6.8 Django==1.11.7 MongoDB version v4.2.0 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb6c2b776a8> Traceback (most recent call last): File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 68, in get_handler return get_internal_wsgi_application() File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/home/akash/Documents/Python/project/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/akash/Documents/Python/project/Web/project/project/wsgi.py", line 16, in <module> application = get_wsgi_application() … -
i found this error 'NoneType' object is not iterable
similarity_score = [] for sentence1 in text: for sentence2 in text: if sentence1!=sentence2: sim_score = [] temp2 = [] sim = [[wn.word_similarity(word1,word2,'jcn') for word1 in sentence1] for word2 in sentence2] # s_sim = sum([sum(i) for i in zip(*sim)]) s_sim = sum(sum_similarity(sim)) sim_score.append(s_sim) # C_sim = content_sim(sentence1,sentence2) # sim_score.append(C_sim) # t_sim = sum([e/max(sim_score) for e in sim_score]) t_sim = sum(sim_score)/len(sim_score) temp2.append(sentence1) temp2.extend((sentence2,t_sim)) similarity_score.append(temp2) return similarity_score File "C:\Users\Waqar Ahmad\projects\website\website\pages\Sentence_similarity.py", line 83, in similarity s_sim = sum(sum_similarity(sim)) TypeError: 'NoneType' object is not iterable [12/Sep/2019 22:02:51] "POST /genericbased_similaritymatrix HTTP/1.1" 500 371830 -
Django/DRF filtering
I filter my list of Product models by title field. For example, I want to find this title = 'Happy cake'. And if I type Case 1. 'happy cake', Case 2. 'hapy cake', happi kake' it should return me 'Happy cake'.As I know icontains helps me with case 1. How can I get that?May be some sort of technologies should be added or django itself has appropriate solution?