Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Join and format array of objects in Python
I want to join and format values and array of objects to a string in python. Is there any way for me to do that? url = "https://google.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" } ] url = "https://google.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "Chennai Express", "rating": "5.0" } ] url = "https://bing.com", search = "thai food", search_res = [ { "restaurant": "Siam Palace", "rating": "1.5" }, { "restaurant": "Bangkok Palace", "rating": "4.5" } ] url = "https://bing.com", search = "indian food", search_res = [ { "restaurant": "Taj Palace", "rating": "4.5" }, { "restaurant": "Chennai Express", "rating": "3.0" } ] I want to be able to format the values as such: If I could make it look like: all_data = [{ url = "https://google.com", results = [{ search = "thai food", search_res = [{ "restaurant": "Siam Palace", "rating": "4.5" }, { "restaurant": "Bangkok Palace", "rating": "3.5" }] }, { search = "Indian food", search_res = [{ "restaurant": "Taj Palace", "rating": "2.5" }, { "restaurant": "CHennai Express", "rating": "5.0" }] }] }, { url = "https://bing.com", … -
Webhost Platform for PostGIS, Django and Celery
I'm currently developing a django web app. I'm trying to decide which platform is best suited to host it. I was considering PythonAnywhere but it seems like they don't support celery or other long running processes. Any suggestions? -
How to initialize form with some parameters of model instance
I would like be able to send SMS/Email notifications manually using the groups/users of a model instance. Let's say the model looks like this: class Memo(models.Model): title = models.CharField(max_length=100) receiver = models.ManyToManyField(EmployeeType, related_name='memos_receiver') I pass the object instance to the view: path('<int:pk>/notify', NotificationView.as_view(), name='memos-notify'), The form and the view are where I am having trouble. I figure I should be able to just pass the forms initial fields right there in the view: class NotificationView(FormView): template_name = 'memos/notification_form.html' form_class = MemoNotificationForm success_url = reverse_lazy('overview') def get_initial(self): initial = super(NotificationView, self).get_initial() memo = Memo.objects.filter(id=id) initial['receiving_groups'] = memo.receiver return initial And the form looks like this: class MemoNotificationForm(forms.Form): class Meta: fields = [ 'receiving_groups' ] receiving_groups = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple) TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Do I need to initialize the queryset in the form? Would appreciate it if someone could paint me a clear picture of the why and how here. Thank you! -
Crispy Django Form With RadioBox - Using InlineRadios
I want to style in Radio button in Django using Crispy Form. However, I have successful making use of CSS which is applied to the form but I need to display the form n inline format. After rendering the form in my html, I got a put which is not in inline format. I will be very happy if I can more detail about crispy form using radio button or selected button class ViewForm(forms.Form): #django gives a number of predefined fields #CharField and EmailField are only two of them #go through the official docs for more field details VIEWS = ( ('1', 'Likes & Comments'), ('2', 'Subscribers'), ('2', 'App Installs'), ) GENDER = ( ('1', 'Female'), ('2', 'Male') ) AGE = ( ('All', 'All'), ('13 - 24', '13 - 24'), ('25 - 34', '25 - 34'), ('35 - 44', '35 - 44'), ('45 - 54', '45 - 54'), ('55 - 64', '55 - 64'), ) CATEGORY = ( ('Auto', 'Auto'), ('Beauty', 'Beauty'), ('Sport', 'Sport'), ) CHOICES=[('select1','select 1'), ('select2','select 2')] view= forms.ChoiceField(label='BESIDE VIEWS, I ALSO WANT:', widget=forms.RadioSelect, choices=VIEWS) age= forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=AGE) gender = forms.ChoiceField(label='AGE?', widget=forms.RadioSelect, choices=GENDER) location = forms.CharField(max_length=25, required=False) category= forms.CharField(label='CATEGORY', widget=forms.Select(choices=CATEGORY)) keyword = forms.CharField(max_length=50, required=False) my css input[type=radio], … -
Django TestCase object has no attribute 'login'
I have used selenium to test my login method and it works fine. Then, I tried to test other parts of the website. So, I needed to create a user in my test. To do that, I've used client instead of request factory (since there are middleware classes). However, I am getting the error: AttributeError: 'ProjectListTestCase' object has no attribute 'login' I do have a custom authentication backend to allow for email address to be used instead of username: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'phonenumber_field', 'rest_framework', # 3rd party apps 'crispy_forms', # Local apps 'accounts', ... I tried the code in the console: >>> the_client = Client() >>> the_client.login(email='test@testing.com', password='testingPassword') True Here is the code in my test_views.py: from django.core.urlresolvers import reverse from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.test import TestCase from django.test import RequestFactory from model_mommy import mommy from selenium import webdriver from project_profile.models import Project from user_profile.models import UserProfile class ProjectListTestCase(TestCase): def setUp(self): # login the user login = self.client.login(email='test@testing.com', password='testingPassword') print ('Login successful? ', self.login) # Just to see what's going on response = self.client.get(reverse('development:list_view_developmentproject') ) print('response: ', self.response) # Just to see what's going on def test_user_login(self): self.assertEqual(self.response.status_code, 200) Why do I … -
Send mail inside action django-rest-framework
i'm learning django restframework by myself I'm trying to send a mail with sengrid inside an action enter image description here The mail doesn't send Sorry for menglish thank you -
Django background task repeating more than it should
I am trying to run a django background task every 30 seconds, as a test I'm having it print "hello", but instead of printing every 30 seconds it is printing about every second or less very quickly. Here is my code currently: from background_task import background from datetime import timedelta, datetime @background(schedule=datetime.now()) def subscription_job(): print("hello") subscription_job(repeat=30) -
How to make the user visible to al his group activities
I am doing a django-rest-framework project in which one can create groups by adding member’s email id and the logged in user should be able to see all the group activities. I used django-multi-email-field to store the list of emails of respective members Now the user can see his own activities when logged in.How can i make the user visible to all the group activities.Should i create a model inside a model? Please help me. -
Failed lookup for key in templates
I am trying to get Specific List in Dictionary, but first i got the error: "fail to lookup for key", searching on internet I found out a tread with this solution: {% with obj1.page.val2 as val2 %} {{ obj1.val1|default:val2 }} {% endwith %} But It does not work any help here is my code: keyData = '\'' + id + '|' + id2 + '|' + id3 + '\''; console.log(keyData); var val2; try { {% with keyData as val2 %} console.log(val2); datas = {{product_prices_complex_key|get_item:val2|safe}}; {% endwith %} console.log(datas); }catch(err){console.log(err);} KeyData: WA5-8|2|5 And is in the dictionary. Thanks in Advanced -
Django model method error: missing 1 required positional argument: 'self'
I want to do some calculations inside a model and between attributes. I want 3 fields that can be entered by the user to add the model, but those fields get concatenated into a non-editable field that can be used for viewing purposes only. Here is the model I have: class Dossier(models.Model): #Dossiers sinistre numero = models.CharField(max_length=20, default=dossier_number, editable=False) created_by = models.ForeignKey(Prestataire, on_delete=models.SET_NULL, null=True) mat_id = models.CharField(max_length=7, default="123456") mattypes = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ) mat_symbol = models.CharField(max_length=3, choices=mattypes, default="A") mat_ville = models.CharField(max_length=2, blank = True) def define_matricule(self): if self.mat_symbol == "A" or "B": return str(self.mat_id) + '-' + str(self.mat_symbol) + '-' + str(self.mat_ville) else: return str(self.mat_id) + '-' + str(self.mat_symbol) matricule = models.CharField(max_length=20, default=define_matricule, editable=False) But when I run this, I find this error: Django Version: 2.2.5 Exception Type: TypeError Exception Value: define_matricule() missing 1 required positional argument: 'self' Exception Location: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py in get_default, line 797 Python Executable: C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\python.exe Here's my traceback: Environment: Request Method: GET Request URL: http://localhost:8000/dossiers/nouveau Django Version: 2.2.5 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'formtools', 'dashboard.apps.DashboardConfig', 'crispy_forms', 'photologue', 'sortedm2m'] Installed 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'] Traceback: File "C:\Users\Kaiss Bouali\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" … -
get_decoded method show "Session data corrupted" in Django session
I have an application which using Django 2.0 and I'm facing with an issue about session data today. (SECRET_KEY is a static string, and consistent among the app so this might not is the issue) The command I've tried is: from django.contrib.sessions.models import Session session = Session.objects.first() session.get_decoded() # Session data corrupted # {} Even when I clear all the sessions, login again for a new session but still facing the same issue. I really want to read the session from the backend using manage.py shell and those script above. -
How to return user session id alongside Django rest serializer output
I'm writing a web application with Django. In one of my APIs which is using Django rest_framework, I want to return user's session ID alongside the default response. I know how to get the session ID but I don't know how to put it alongside the response(for example, in a JSON format) This is my code: class HouseInfoSerializer(serializers.ModelSerializer): class Meta: model = House fields = '__all__' class HouseViewSet(generics.ListAPIView): serializer_class = HouseInfoSerializer def get_queryset(self): postcode = self.kwargs['postcode'] print(self.request.session.session_key, "*"*10) return House.objects.filter(postcode=postcode) -
python - group values when generating a json
I am generating below JSON using a piece of code. Basically, I need to group my generated JSON group by continent, and then country and languages [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us" } ] }, { "region": "ar", "country": "Argentina", "languages": [ { "language": "es-ar" } ] }, { "region": "bo", "country": "Bolivia", "languages": [ { "language": "es" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "en-us" } ] }, { "region": "bra", "country": "Brazil", "languages": [ { "language": "pt-br" } ] } ] }} I am generating above JSON using the below code. def get_available_locales_json(): locales = [] for locale in get_available_locales(): append_locale = True for entry in locales: if entry['continent'] == locale.region.continent: entry['regions'].append({'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}) append_locale = False break if append_locale: locales.append( { 'continent': locale.region.continent, 'regions': [{'region': locale.region.code, 'country': locale.region.name, 'languages': [ {'language': locale.language.code} ]}] } ) return locales However, I need to group languages together without having an extra node for the country. something like below, [ { "continent": "South America", "regions": [ { "region": "ar", "country": "Argentina", "languages": [ { "language": "en-us", "language": "es-ar" } … -
How can I convert a duration or a string to an integer in a queryset in Django views.py?
I need to calculate the time difference between two rows. This duration then needs to be adjusted up to 1 if the total is 0, or if the total is over 15 minutes, adjusted to 0--I was going to put this corrected amount in strtime. Unfortunately, my calculated times are not correct nor can I convert the extracted minutes to an integer in order to test if the duration is > 15 or < 1. The only reason I converted to a string was to see if I could then convert to an integer--it didn't work. I also tried to convert to a pandas dataframe in order to do the calculations, but I could not get it back into some format to display properly on the html page. How can I do an accurate calculation between rows and how can I adjust from 0 to 1 or > 15 to 0? I have tried many different versions--just not having much luck. I normally work in javascript--this is my first Django project. I have sanitized and shortened the data. This page will fit into an existing Django setup. Thank you in advance! Code is below. models.py class testmodels(models.Model): primary_key_id = models.CharField(max_length=150, … -
Django queryset caching with exists()
Let's say, I'm trying to change the name of all profiles whose name is John to Mike queryset = Profile.objects.filter(name='John') Method 1: if queryset: queryset.update(name='Mike') Method 2: if queryset.exists(): queryset.update(name='Mike') QUESTION: Which method is more efficient? Usually, I use exists() in the same line as my filter, so it queries once. However, I'm not sure if Method 2 will make another query to the database, making it less efficient. -
Using Django to display images
I am attempting to use Django to display 3 random images from a large list of user submitted images. Each image has other values associated with it like the author, so I've been making each image a model with the image field holding the image itself. Unfortunately, I can't figure out how to randomly pick from that list and pass it in to the .html page to display it correctly. So far, I've been able to get user submitted pictures to be saved as models and submitted to a folder /media/images/. My views.py will grab 3 random and unique pictures from that folder like so: def home_view(request): form = MForm(request.POST or None) if form.is_valid(): form.save() message_list = MModel.objects.all() #Get first random file file1choice = random.choice(os.listdir(DIR)) #Get second random file file2choice = random.choice(os.listdir(DIR)) while(file2choice == file1choice): file2choice = random.choice(os.listdir(DIR)) #Get third random file file3choice = random.choice(os.listdir(DIR)) while(file3choice == file1choice or file3choice == file2choice): file3choice = random.choice(os.listdir(DIR)) context = { 'file1': file1choice, 'file2': file2choice, 'file3': file3choice, } return render(request, "home.html", context) In my .html file that the user sees, I access each image passed like so: <img src="/media/images/{{ file1 }}" width="300" height="180" alt=""> Unfortunately, this doesn't allow me to actually access the … -
Why does django send_mail fails to send email with no errors?
I want to use send_mail in django, however it doesn't send any email. Here is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'MY-GMAIL-USERNAME@gmail.com' EMAIL_HOST_PASSWORD = 'MY-GMAIL-PASSWORD' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = DEFAULT_FROM_EMAIL Then, I run python manage.py shell: from django.conf import settings from django.core.mail import send_mail subject = 'Test Subject' message = 'Test Message' email_from = settings.EMAIL_HOST_USER recipient_list = ['MY-YAHOO-USERNAME@yahoo.com'] send_mail(subject, message, email_from, recipient_list) It doesn't send the email and it prints: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Test Subject From: MY-GMAIL-USERNAME@gmail.com To: MY-YAHOO-USERNAME@yahoo.com Date: Mon, 09 Dec 2019 21:02:16 -0000 Message-ID: <157592533640.18842.5494330274157836181@thinkpad-e560> ------------------------------------------------------------------------------- 1 Test Message which seems to have no errors. Why doesn't it send the email? What is wrong? Why doesn't it log any errors? I've tried a pure python way and it works fine: import smtplib, ssl smtp_server = "smtp.gmail.com" port = 465 sender_email = "MY-GMAIL-USERNAME@gmail.com" password = 'MY-GMAIL-PASSWORD' receiver_email = 'MY-YAHOO-USERNAME@yahoo.com' context = ssl.create_default_context() server = smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) server.login(sender_email, password) server.sendmail(sender_email, receiver_email, 'Test Message') As I mentioned, this pure python way works fine! I'm confused. What did I do wrong? -
Why can't I PATCH Django REST Framework PrimaryKeyRelatedField to empty list?
I'm running into a weird issue in Django REST Framework. I'm attempting to add & remove groups to/from users using PATCH requests. I am able to PATCH to /api/users/:id/ to update the groups list, which is initially empty. For example, the following actions yield these results: PATCH /api/users/:id/ {"groups": [1]} -> Results in user with groups: [1] PATCH /api/users/:id/ {"groups": [1, 2]} -> Results in user with groups: [1,2] PATCH /api/users/:id/ {"groups": [1]} -> Results in user back to groups: [1] So I am successfully updating the state with PATCH requests. However the following fails to update accordingly: PATCH /api/users/:id/ {"groups": []} -> Results in user still at groups: [1] Here is my UserSerializer class: class UserSerializer(serializers.ModelSerializer): groups = serializers.PrimaryKeyRelatedField(many=True, queryset=Group.objects.all(), allow_empty=True, required=False) class Meta: model = User fields = ( 'id', 'username', 'first_name', 'last_name', 'is_staff', 'is_authenticated', 'is_superuser', 'email', 'groups' ) My suspicion is that it has something to do with PrimaryKeyRelatedField - I have tried many combinations of arguments to the constructor to no avail. -
My form does not send data to the db django
My form does not send data to the database. I have a form that after entering data and clicking 'Order' should send information to the database. However, this does not happen. It is a 'cart' which, after sending the data, should save in the Order table information provided by the user as well as data on ordered products. cart/views.py def cart_detail(request, total=0, counter=0, cart_items = None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) counter += cart_item.quantity except ObjectDoesNotExist: pass if request.method == 'POST': total = request.POST['total'] billingName = request.POST['billingName'] billingAddress1 = request.POST['billingAddress1'] billingCity = request.POST['billingCity'] billingPostcode = request.POST['billingPostcode'] billingCountry = request.POST['billingCountry'] shippingName = request.POST['shippingName'] shippingAddress1 = request.POST['shippingAddress1'] shippingCity = request.POST['shippingCity'] shippingPostcode = request.POST['shippingPostcode'] shippingCountry = request.POST['shippingCountry'] order_details = Order.objects.create(total=total, billingName=billingName, billingAddress1=billingAddress1, billingCity=billingCity, billingPostcode=billingPostcode,billingCountry=billingCountry, shippingName=shippingName, shippingAddress1=shippingAddress1, shippingCity=shippingCity, shippingPostcode=shippingPostcode, shippingCountry=shippingCountry) order_details.save() for order_item in cart_items: oi = OrderItem.objects.create( product = order_item.product.name, quantity = order_item.quantity, price = order_item.product.price, order = order_details ) oi.save() '''Reduce stock when order is placed or saved''' products = Product.objects.get(id=order_item.product.id) products.stock = int(order_item.product.stock - order_item.quantity) products.save() order_item.delete() '''The terminal will print this message when the order is saved''' print('The order has been created') return redirect('cart:cart_detail') return render(request, 'cart/cart.html', dict(cart_items … -
wagtail menus return an empty list menu_items
after added wagtailmenus to my wagtail project and it worked well, but when i add an item to my main menu and try to use it in my navbar it always return in empty list... it doesn't matter how many item in main menu it always give me empty list. this is my code in navbar. {% load menu_tags %} {% main_menu %} {% if main_menu %} {{ menu_items }} {% endif %} {% for item in menu_items %} and this is my code in base.html <!-- navbar --> {% load menu_tags %} {% main_menu template="base/navbar.html" %} -
Annotating data in Django Templates
I am attempting at rendering annotated data into my template My models looks like this class Content(models.Model): title = models.CharField(max_length=255) body = models.TextField() reviews_total = models.FloatField(null=True) def _str_(self): return self.title class Review(models.Model): content = models.ForeignKey(Content, null=True, on_delete=models.CASCADE) readability = models.CharField(max_length=500) readability_rating = models.IntegerField() actionability = models.CharField(max_length=500) actionability_rating = models.IntegerField() general_comments = models.CharField(max_length=500) avg_rating = models.IntegerField(null=True) And my template looks like this {% for content in content.all %} {{ content.title }} Reviews: {{ content.review_set.count }} Avg Rating: {{ ? }} {% endfor %} From the following query x = Content.objects.annotate(avg=Avg('review__avg_rating')) y = vars(x[pk]) y['avg'] Which will give me 4.0 for example. My goal is essentially to to insert y into Avg Rating {{ }} Is there a way similar to content.review_set.count? Or is it best to do in views? -
COPY failed: stat /var/lib/docker/tmp/docker-builder<num>/server/requirements.txt: no such file or directory
Appears to be some kind of context issue. I'm trying to figure out why this would work fine when spinning up a local Kubernetes cluser with Skaffold, but is failing to build the image properly when pushing to Azure. Basic structure is: test-app/ server/ requirements.txt Dockerfile azure-pipeline.yml skaffold.yaml I have the production server/Dockerfile as the following: FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 WORKDIR '/app' EXPOSE 5000 COPY ./server/requirements.txt . RUN pip install -r requirements.txt COPY ./server . CMD ["python", "manage.py", "collectstatic"] CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"] I'm using the azure-pipelines.yml that was generated for me in the Pipelines section of Azure DevOps: # Docker # Build and push an image to Azure Container Registry # https://docs.microsoft.com/azure/devops/pipelines/languages/docker trigger: - master resources: - repo: self variables: # Container registry service connection established during pipeline creation dockerRegistryServiceConnection: '<connection-string>' imageRepository: 'testapp' containerRegistry: 'testappcontainers.azurecr.io' dockerfilePath: '$(Build.SourcesDirectory)/server/Dockerfile' tag: '$(Build.BuildId)' # Agent VM image name vmImageName: 'ubuntu-latest' stages: - stage: Build displayName: Build and push stage jobs: - job: Build displayName: Build pool: vmImage: $(vmImageName) steps: - task: Docker@2 displayName: Build and push an image to container registry inputs: command: buildAndPush repository: $(imageRepository) dockerfile: $(dockerfilePath) containerRegistry: $(dockerRegistryServiceConnection) tags: | $(tag) During the automated build it gets … -
Issue with question mark in Django url
Here is the example link: abc.com/Hi-Python? So, in the backend of Django, I need data "Hi-Python?", but I'm getting - "Hi-Python" url(r'^@(?P<title>[a-zA-Z0-9_\.!,\-\?\:\w\+]+)$', views.title, name='title'), Any hint, how to solve this issue -
ImportError: cannot import name 'python_2_unicode_compatible' when running migrations for Django-Invitations
First, I might want to mention I'm a beginner with Django. I'm trying to install Django-Invitations on my app to send sign up invitations. I followed their README instructions. pip install django-invitations # Add to settings.py, INSTALLED_APPS 'invitations', # Append to urls.py url(r'^invitations/', include('invitations.urls', namespace='invitations')), # Run migrations python manage.py migrate I also pip installed all the requirements from their requirements file: coverage==4.5.4 flake8==3.7.9 freezegun==0.3.12 mock==3.0.5 pytest==5.2.2 pytest-django==3.6.0 pytest-cov==2.8.1 tox==3.14.0 But I keep getting the same error when I run migrations for the first time: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\maxim\Desktop\Web Development\Projects\admin\RentQ3\myEnv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\maxim\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\maxim\Desktop\Web … -
TemplateSyntaxError: Could not parse the remainder: '()' from 'size.toLowerCase()'
I am working through Python+Django on PythonAnywhere. I am attempting to AngularJS Options Groups to create dynamic web scripting that is dependent on drop down box selections. However, I am running into the error TemplateSyntaxError: Could not parse the remainder: '()'. Additionally, if I temporarily remove this trouble error in the html file to view the page, anything within brackets {{ }} does not show on screen. Why are these references not working? Does a Django web-app understand how to reference the .js file? I am using this sample tutorial as is. .html {% load static %} <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Option Groups</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic"><link rel='stylesheet' href='https://gitcdn.xyz/cdn/angular/bower-material/v1.1.20/angular-material.css'> <link rel='stylesheet' href='https://material.angularjs.org/1.1.20/docs.css'><link rel="stylesheet" href="./style.css"> </head> <body> <!-- partial:index.partial.html --> <div ng-controller="SelectOptGroupController" class="md-padding selectdemoOptionGroups" ng-cloak="" ng-app="MyApp"> <div> <h1 class="md-title">Pick your pizza below</h1> <div layout="row"> <md-input-container style="margin-right: 10px;"> <label>Size</label> <md-select ng-model="size"> <md-option ng-repeat="size in sizes" value="{{size}}">{{size}}</md-option> </md-select> </md-input-container> <md-input-container> <label>Topping</label> <md-select ng-model="selectedToppings" multiple=""> <md-optgroup label="Meats"> <md-option ng-value="topping.name" ng-repeat="topping in toppings | filter: {category: 'meat' }">{{topping.name}}</md-option> </md-optgroup> <md-optgroup label="Veggies"> <md-option ng-value="topping.name" ng-repeat="topping in toppings | filter: {category: 'veg' }">{{topping.name}}</md-option> </md-optgroup> </md-select> </md-input-container> </div> <p ng-if="selectedToppings">You ordered a {{size}} pizza with {{printSelectedToppings}}.</p> </div> </div> <!-- Copyright 2018 Google LLC. All Rights …