Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load content on page scroll via Django & pure JS
I need to load content, when user reaches bottom of the page, with pure JS and Django. JS: window.onscroll = function() { if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { // Insert your genius code (that will do the thing) here. } }; Django's View: class Index(View): def get(self, request): objects = Paginator(Object.objects.all(), 10) if request.<define that is javascript request here>: # Do the thing # Return rendered html that could be appended to already renderd html. else: page = objects.get_page(0) # How to get last page? context = { 'objects': page, } return render(request, 'main/index.html', context) HTML: {% extends "base.html" %} {% block content %} {% for object in objects %} ... {% endfor %} {% endblock %} -
Django AttributeError: 'Cursor' object has no attribute '_last_executed'
I have an error when run migration file in Django 1.5.12 with python 2.7.10 and South 0.8.4 My models.py from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) My commands ./manage.py schemamigration polls --initial -> It will create the initial migration file ./manage.py migrate polls -> Error here . Do you know how to fix that? -
django admin conditional relation
I got such legacy DB: class CarParamType(models.Model): name = models.CharField(max_length=50) unit = models.CharField(max_length=10) class CarParam(models.Model): car = models.ForeignKey(Car) car_param_type = models.ForeignKey('CarParamType') value = models.CharField(max_length=20) class DriveType(models.Model): name = models.CharField(max_length=20) class Car(models.Model): vin = models.CharField(max_length=20) And such admin site: class CarParamAdmin(admin.TabularInline): model = CarParam @admin.register(Car) class CarAdmin(CustomModelAdmin): inlines = [ CarParamAdmin, ] CarParamType is populated with names like weight, width, color and most important there is 'drive' record with related to DriveType id in CarParam value field. It is possible to get something like: if car_param_type.name == 'drive': form = forms.ModelChoiceField(queryset=DriveType.objects.all()) ..inside my TabularInline ? -
Issue with Cloud sql connection on App Engine for django project
I am trying to deploy my django project on Google App Engine following the documentation https://cloud.google.com/python/django/appengine. But I cannot establish proxy connection with sql server. Here is my database credentials from settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/x-reviews:us-central1:x-reviews-stage', 'NAME': 'x_reviews_stage', 'USER': 'root', 'PASSWORD': 'my-password', 'PORT': '3306', } } I use following query to connect to proxy server ./cloud_sql_proxy -instances="x-reviews:us-central1:x-reviews-stage"=tcp:3306 To start mysql instance, there are 2 ways- TCP based connection and UNIX based connection as mentioned in the link https://cloud.google.com/sql/docs/mysql/connect-admin-proxy When I try TCP based connection using below query, connection is established mysql --host 127.0.0.1 --user root --password When I try UNIX based connection using below query, I receive the error mysql -u root -p -S /cloudsql/x-reviews:us-central1:x-reviews-stage ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/cloudsql/x-reviews:us-central1:x-reviews-stage' (2) Similarly, I receive the error when I try to run django project django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/cloudsql/x-reviews:us-central1:x-reviews-stage' (2)") Searched the Internet, Read the Google documentation multiple times but I am stuck here for 2 days. How do I establish connection with SQL server? My goal is to deploy the project. As per the documentation, I need to create database by running … -
Pythonic way to read the large number of text files from a Directory
I'm working on a project using Python(3.6) and Django(2) in which I need to read all the text files from a directory one by one, I have write the code but it is reading only 28 files from a folder which has 30 text files at the moment for testing purpose and return an error. From views.py: for path, name in get_txt_files(obj.textPath): print(path) sa_response = nlp_text_manager(path, name) here's the function to read the files: def nlp_text_manager(text_path, name): text = text_path txt = Path(text_path).read_text(encoding='cp1252') # then use the files below that..... And it returns this error after reading 28 files: v = self._sslobj.read(len, buffer) socket.timeout: The read operation timed out [11/Dec/2018 07:16:20] "POST / HTTP/1.1" 500 16416 The number of files in the provided folder can be very large may the folder has the size in GBs, So, what is the efficient pythonic way to read a large number of files from a directory? Thanks in advance! -
Django - annotate latest child's column value to query
I have a Trade, which is the parent of TradeLeg. I am now querying the trade and I need to annotate the "date" of the latest TradeLeg added to this query. Here's my models: class Trade(models.Model): name = models.CharField( default='', max_length=50, blank=True, ) date = models.DateField( default='', blank=True, null=True, ) Class TradeLeg(models.Model): trade = models.ForeignKey( Trade, on_delete=models.CASCADE ) date = models.DateField( default='', blank=True, null=True, ) Here's my erroneous query: trades = Trade.objects.all().annotate(latest_leg_date='tradeleg__date__first') -
Django testing throws 'the data didn't validate'
I am testing form_save but the form didn't valid. I am using session data. In forms.py [![enter code here][1]][1] In views.py [![enter code here][1]][1] In tests.py valid_data = { 'password1': 'secret%1234', 'terms': 'on' } kwargs = { 'email': 'hello@test.com' } def test_with_valid_data(self): session = self.client.session session['email'] = self.kwargs['email'] session.save() form = CustomCreationForm(data=self.valid_data) form.save(commit=False, email=session['email']) form['email'] = self.session['email'] u1 = form.save() self.assertTrue(form.is_valid()) self.assertEqual(repr(a1), '<User: hello@test.com>') The erro is User could not be created because the data didn't validate. -
auto assign ForeignKey to CBV Create View?
I have two models ProductionProcess and ProductsMaster When I use {{ object.ProductName }} it comes with all ForeignKey Data. but i want to select only one which pk comes with url Here in Models.py ProductionProcess has ProductsMaster forwignKey models.py class ProductsMaster(models.Model): Name = models.CharField(max_length=40) SalesPrice = models.FloatField() FabricCode = models.CharField(max_length=30) SizeType = models.CharField(max_length=30) RequiredFabric = models.CharField(max_length=30) def __str__(self): return self.Name class Meta: verbose_name_plural = "ProductsMaster" class ProductionProcess(models.Model): ProductName = models.ForeignKey(ProductsMaster,on_delete=models.CASCADE) Name = models.CharField(max_length=30) PerformAtProduction = models.BooleanField() def __str__(self): return self.Name class Meta: verbose_name_plural = "ProductionProcess" In Viwes get method override for getting pk Views.py class ProductionProcessCreateView(CreateView): model = ProductionProcess form_class = ProductionProcessForm ExampleFormSet = formset_factory(ProductionProcessForm,) template_name="master/productionprocess_form.html" def get_success_url(self): return reverse_lazy('tailoring-products') def get(self, request, *args, **kwargs): product = get_object_or_404(ProductsMaster, pk=self.kwargs['pk']) print(self.kwargs['pk']) context={'ProductionProcessForm':self.ExampleFormSet(),'id':product} return render(request,self.template_name,context) def post(self,request,*args,**kwargs): ExampleFormSet = self.ExampleFormSet(self.request.POST) product = get_object_or_404(ProductsMaster, pk=self.kwargs['pk'],) # product_id = self.kwargs['pk'] # print(product_id) if ExampleFormSet.is_valid(): for docs in ExampleFormSet: # docs.Name = docs.cleaned_data['Name'] # docs.ProductName = docs.cleaned_data['ProductName'] # docs.PerformAtProduction = docs.cleaned_data['PerformAtProduction'] docs.save(commit=False) docs.instance.ProductName_id = self.kwargs.get('pk') # print(docs.instance.ProductName_id) docs.save() return HttpResponseRedirect(self.get_success_url()) else: context={ 'ExampleFormSet':self.ExampleFormSet(), # 'form':form } return render(request,self.template_name,context) HTML <th class="column-title">ProductName </th> <th class="column-title">PROCESS NAME</th> <th class="column-title">PERFORM AT PRODUCTION</th> <th class="column-title">Action </th> </tr> </thead> <tbody > {% for object in ProductionProcessForm %} {{ ProductionProcessForm.management_form }} … -
Target WSGI script cannot be loaded as a python module and ImportError: No module named 'django'
I'm try to deploy virtual host my django project into apache2 via mod_wsgi WSGIDaemon method, i'm using ubuntu 16.04 and i'm getting following error. From apache2 error log: [Tue Dec 11 11:55:31.748517 2018] [wsgi:error] [pid 14231:tid 139821891782400] [remote ::1:44748] mod_wsgi (pid=14231): Target WSGI script '/var/www/html/rasa_django/rasa_django/wsgi.py' cannot be loaded as Python module. [Tue Dec 11 11:55:31.748570 2018] [wsgi:error] [pid 14231:tid 139821891782400] [remote ::1:44748] mod_wsgi (pid=14231): Exception occurred processing WSGI script '/var/www/html/rasa_django/rasa_django/wsgi.py'. [Tue Dec 11 11:55:31.748639 2018] [wsgi:error] [pid 14231:tid 139821891782400] [remote ::1:44748] Traceback (most recent call last): [Tue Dec 11 11:55:31.748657 2018] [wsgi:error] [pid 14231:tid 139821891782400] [remote ::1:44748] File "/var/www/html/rasa_django/rasa_django/wsgi.py", line 12, in [Tue Dec 11 11:55:31.748662 2018] [wsgi:error] [pid 14231:tid 139821891782400] [remote ::1:44748] from django.core.wsgi import get_wsgi_application [Tue Dec 11 11:55:31.748677 2018] [wsgi:error] [pid 14231:tid 139821891782400] [remote ::1:44748] ImportError: No module named 'django' [Tue Dec 11 11:55:31.787336 2018] [wsgi:error] [pid 14231:tid 139821849777920] [remote ::1:38604] mod_wsgi (pid=14231): Target WSGI script '/var/www/html/rasa_django/rasa_django/wsgi.py' cannot be loaded as Python module. [Tue Dec 11 11:55:31.787379 2018] [wsgi:error] [pid 14231:tid 139821849777920] [remote ::1:38604] mod_wsgi (pid=14231): Exception occurred processing WSGI script '/var/www/html/rasa_django/rasa_django/wsgi.py'. [Tue Dec 11 11:55:31.787447 2018] [wsgi:error] [pid 14231:tid 139821849777920] [remote ::1:38604] Traceback (most recent call last): [Tue Dec 11 11:55:31.787465 2018] [wsgi:error] [pid 14231:tid 139821849777920] … -
Cannot Import Model Name Django with User Model and Informational Model
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x105de5048> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/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 "/Users/Name/Desktop/ProjectDevCode/Restructured/mysite/seasons/models.py", line 2, in <module> from users.models import User File "/Users/Name/Desktop/ProjectDevCode/Restructured/mysite/users/models.py", line 11, in <module> from seasons.models import Seasons ImportError: cannot import name 'Seasons' I randomly got this error in my recent django app. I am not sure why. The models import in other apps/files in my project. Any help is appreciated. -
Orig_iat missing from payload when implementing customing JSONWebTokenSerializer
I am implementing a custom JSONWebTokenSerializer. It's working fine so far but I need to enable token refresh but I when I do and try to refresh the token, I get the validation error orig_iat field is required. On inspecting the payload returned from jwt_payload_handler, there isn't any orig_iat field attribute. class CustomJWTSerializer(JSONWebTokenSerializer): @property def username_field(self): return "username_or_email_or_phone" def validate(self, attrs): username = attrs.get('username_or_email_or_phone', None) credentials = { 'username': username, 'password': attrs.get('password') } if all(credentials.values()): user = authenticate(**credentials) if user: if not user.is_active: raise serializers.ValidationError( 'This user has been deactivated.' ) payload = jwt_payload_handler(user) return { 'token': jwt_encode_handler(payload), 'user': user } else: raise serializers.ValidationError( 'A user with this credentials was not found.' ) else: msg = _('Please provide an (username or email or phone number) and password.') raise serializers.ValidationError(msg) Here is are my JWT_AUTH setting: JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_RESPONSE_PAYLOAD_HANDLER': 'common.utilities.auth.jwt_response_payload_handler', 'JWT_AUTH_HEADER_PREFIX': 'Bearer', 'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler', 'JWT_ALLOW_REFRESH': False, } -
django restful api - how to serialize foreign keys
I'm using django 1.8 with djangorestframework==3.6.3. I took the model examples from the documentation: https://www.django-rest-framework.org/api-guide/relations/#stringrelatedfield Here are my serializers: from rest_framework import serializers from .models import * class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration', 'album') and here is how I call the serializer: def index(request): if Track.objects.all().count() == 0: album = Album.objects.create(album_name='something', artist='John') Track.objects.create(album=album, order=1, title='something', duration=1) print TrackSerializer(instance=Track.objects.all()[0]).data return render(request, 'index.html') The print statement give me: {'duration': 1, 'album': 1, 'order': 1, 'title': u'something'} Why is it not giving me all the field data for the corresponding album? -
Provide REST endpoint to list unique values of model field
Let's say I have a Cat model with these fields: name: free text size: enumerate value, BIG / MEDIUM / SMALL I can get the list of cats in the following endpoint: /api/v1/cat The client has no knowledge about the sizes. Is there an accepted DRF method of providing a REST endpoint to list the possible values of a certain model field? My first idea would be to offer the following endpoint: /api/v1/cat/size Replying with something like: ["BIG", "MEDIUM", "SMALL"] But what model should I use for the response? Is there an standard way of providing this information with DRF? -
django: Extending user model using One-to-one error: User has no Profile
I have a basic Django application, wherein along with the User model I have extended the Profile model using One-to-one field. Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='customer_profile_images/%Y/%m/%d/', null=True, blank=True, verbose_name="Profile Picture") phone_number = models.CharField(null=True, blank=True, max_length=10) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() # if not created? @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() def __str__(self): return f'{self.user.first_name} {self.user.last_name}' In admin.py I have registered the Profile model as follow: class ProfileAdmin(admin.ModelAdmin): list_display = ('profile_picture', 'phone_number') admin.site.register(Profile, ProfileAdmin) And at the time of creating a new account for a user in views.py class CustomerSignUpView(View): def post(self, request): name_r = request.POST.get('customer_username') password_r = request.POST.get('customer_password') email_r = request.POST.get('customer_email') contact_number_r = request.POST.get('customer_contact_number') profile_picture_r = request.FILES['customer_profile_picture'] if checkemail(email_r): c = User.objects.create_user(username=name_r, password=password_r, email=email_r) c.save() # this is how i am saving contact number, profile picture inside Profile model Profile.objects.create(user=c, phone_number=contact_number_r, profile_picture=profile_picture_r) Profile.save() return render(request, 'catalog/customer_login.html') else: return render(request, 'catalog/customer_signup.html') def get(self, request): return render(request, 'catalog/customer_signup.html') However, when I access the admin panel, I encounter the following error: Now, I have user create_or_update_user_profile() and save_user_profile() methods in my Profile model. I think the error occurs because for existing users there is no Profile available. I am not sure … -
Django 2.13: NoReverseMatch at /basic_app/user_login/
I've almost completed the course on Udemy on web development but stumbled at the very last step. I really hope someone will be able to help me out as this seems to be a very simple thing that I'm struggling with. The problem seems to be with HttpResponseRedirect(reverse('index')) that is triggered when a user clicks on the Log In link. Thank you very much! Error is triggered at http://127.0.0.1:8000/basic_app/user_login/ NoReverseMatch at /basic_app/user_login/ Reverse for 'basic_app/user_login' not found. 'basic_app/user_login' is not a valid view function or pattern name. Error during template rendering In template /Users/maxa/Dropbox/workspace/2018/projects/python-django-udemy-bootcamp/myplayground/Django_level_5/learning_users/templates/basic_app/base.html, error at line 6 Project's urls.py: from django.contrib import admin from django.conf.urls import url, include from django.urls import path from basic_app import views urlpatterns = [ url(r'^$',views.index, name='index'), path('admin/', admin.site.urls), url(r'^basic_app/',include('basic_app.urls')), url(r'^logout/$',views.user_logout,name='logout'), ] App's urls.py (basic_app/urls.py): from django.conf.urls import url from basic_app import views # TEMPLATE RULES app_name = 'basic_app' urlpatterns = [ url(r'^register/$',views.register,name='register'), url(r'^user_login/$',views.user_login,name='user_login'), ] App's views.py (basic_app/views.py): from django.shortcuts import render from basic_app.forms import UserForm, UserProfileInfoForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required # Create your views here. def index(request): return render(request,'basic_app/index.html') def register(request): registered = False if request.method == "POST": user_form … -
Pushing to Github on Mac returns error everytime
Every time I try to push to Github I get an error that says this. I have tried installing git on different paths and nothing works. I am using a MacBook Air running Mojave. Thank you for reading. -
ImportError: Could not import 'core.auth.api.TokenAuthentication'
I can't for the life of me figure out what is causing this. I have a small Django project using django-rest-framework. I am attempting to modify the token keyword from Token to Bearer for token auth. It cannot for some reason though find my class that inherits from rest_framework.authentication.TokenAuthentication. The file is properly found though, so I am sure it is not a path problem. The relevant part in settings; REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 20, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'core.auth.api.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } The api.py file; from rest_framework.authentication import TokenAuthentication as RestFrameworkTokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken as RestFrameworkObtainAuthToken from rest_framework.response import Response class ObtainAuthToken(RestFrameworkObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'username': user.username }) class TokenAuthentication(RestFrameworkTokenAuthentication): keyword = 'Bearer' The errors; Project structure; -
Django testing raises the user does not exist
I am testing a user creation with session input but it raises the user does not exist. valid_data = { 'email': 'hello@test.com', 'password1': 'password', 'terms': 'on',} def test_with_valid_data(self): session = self.client.session session['email'] = self.valid_data['email'] session.save() response = self.client.post(reverse('create_user'), data=self.valid_data) self.assertEqual(response.status_code, 200) response = self.client.post(reverse('create_user'), data=self.valid_data) user = User.objects.get(email=self.valid_data['email']) ^--- not User doesn't exist error It seems that User.objects.get cannot retrieve the user, which means the .post couldn't create a user but returning 200. What's missing? -
Django: Rows with 4 elements each
I need to a grid that has 4 elements in each row. I've tried this answer: django template to populate bootstrap rows and columns But grid was not aligned because some of the elements names are longer than others making them not aligned: <div class="row"> {% for product in products %} {% if forloop.first %}<div class="row">{% endif %} <div class="col-xs-4"> <div class=""> <a href="{{ product.get_url }}"><img class="" src="{{ product.image.url }}" alt="{{ product.name }}"></a> </div> <span class="text-center">{{ product.name }}</span> </div> {% if forloop.counter|divisibleby:4 %}</div> <div class="row">{% endif %} {% if forloop.last %}</div>{% endif %} {% endfor %} </div> Giving this result: 2) Then I've tried using Ul and li elements: <div class="row"> <ul class="my_products_list list-inline"> {% for product in products %} <li class="text-center list-inline-item my_margin_right"> <div class="text-center"> <a href="{{ product.get_url }}"><img class="my_image_medium" src="{{ product.image.url }}" alt="{{ product.name }}"></a> </div> <span>{{ product.name }}</span> </li> {% endfor %} </ul> </div> But didn't work out and gave me this result: -
Doubts regarding Django views
I am building a website using django and mongodb. I am having some doubts regarding django views. I am new in django and I till now understood that views can be mapped with urls in django. But I am confused that if I have a mongodb document like this: { "articles":{ "Mercedes":"path of this article", "BMW":"path of this article", "Jeep":"path of this article", } } and I want the user should see the article name in the address bar like: mydomain.com/mercedes... But in django, we map the views in urls.py, so do I need to write a function(view) for each article and need to map in urls.py like this: from django.contrib import admin from django.urls import path from my1app import views from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('articles/mercedes',views.viewMercedesArticle, name='viewMercedesArticle') ] or this can have a single view which can show multiple articles and urls of article name in address bar of user? -
Getting a total value from two element using JS in Django
I know this question has being done here a lot but I looked and tried a lot of answers, wasn't able to retrieve what i need. First, I pass a value from an item using django forms through the view. In this example, the template receive the value of "900" because I use the default {{form.price}} in HTML . <input type="text" name="price" value="900" readonly="readonly" id="id_price"> Inside the same HTML i have a field to manually insert a quantity: <input type="text" name="quantity" id="quantity"> And the final input to show to multiplication between those two <input type="text" name="total" id="total"> As a script I used this (saw the answer in a question but i wasn't able to recreate the result in my "total" input) SCRIPT <script> $(document).ready(function () { $('').keyup(function () { var multiplyAndShow = function () { var val1 = parseFloat($('#id_price').val()) var val2 = parseFloat($('#quantity').val()) val3 = val1 * val2 || "Some Text" $("#total").html(val3) } $("#id_price").keyup(function () { multiplyAndShow(); }); $("#quantity").keyup(function () { multiplyAndShow(); }); }); }); The script is not been used because when I set a quantity it doesn't make a thing. The price value is readonly so i don't know if that's the problem. I'm a newbie in javascript … -
Django many-to-many add having inconsistent effect in functions, works on console
I'm creating a lesson planning tool. Each lesson covers multiple syllabus points, and has associated resources. When you save a lesson, I want to make sure that the syllabus points for the lesson are also saved to the resources. I've tried using both signals and overiding the save method to make this work, but keep getting weird results. models.py class Lesson(models.Model): lessonslot = models.ForeignKey(TimetabledLesson, on_delete=models.CASCADE) classgroup = models.ForeignKey(ClassGroup, null=True, blank=False, on_delete=models.SET_NULL) status = models.CharField(max_length=20, null=True, blank=True) syllabus_points_covered = models.ManyToManyField(SyllabusPoint, blank=True) lesson_title = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) requirements = models.TextField(null=True, blank=True) sequence = models.IntegerField(null=False, blank=True) date = models.DateField(null=True, blank=True) syllabus = models.ForeignKey(Syllabus, blank=True, null=True, on_delete=models.SET_NULL) class Meta: unique_together = ( ("lessonslot", "date"), ("classgroup", "sequence")) class LessonResources(models.Model): lesson = models.ForeignKey(Lesson, blank=True, null=True, on_delete=models.SET_NULL) resource_type = models.CharField(max_length=100, choices=RESOURCE_TYPES, null=False, blank=False) resource_name = models.CharField(max_length=100, null=True, blank=False) link = models.URLField(blank=True, null=True) students_can_view_before = models.BooleanField() students_can_view_after = models.BooleanField() available_to_all_classgroups = models.BooleanField() syllabus_points = models.ManyToManyField(SyllabusPoint, blank=True) def set_syllabus_points(self): if self.lesson: points = self.lesson.syllabus_points_covered.all().order_by('pk') for point in points: self.syllabus_points.add(point) return self signals.py from timetable.models import LessonResources, Lesson from django.db.models.signals import post_save, m2m_changed from django.dispatch import receiver @receiver(m2m_changed, sender=Lesson.syllabus_points_covered.through) def post_update_lesson_syllabus_pts(sender, instance, **kwargs): """ After adding a syllabus point to a lesson, update its resources""" resources … -
React + Django Axios Issues
I have a react application linked to a Django backend on two separate servers. I am using DRF for django and I allowed cors using django-cors-headers. For some reason when I curl POST the backend, I am able to get the request out. However when I use axios POST the backend, I get and error. The status of the POST request from axios is failed. The request and takes more than 10 seconds to complete. My code was working locally (both react and django codes), but when I deployed to AWS ec2 ubuntu, the axios requests stopped working. Console error logs OPTIONS http://10.0.3.98:8000/token-auth/ net::ERR_CONNECTION_TIMED_OUT { "config": { "transformRequest": {}, "transformResponse": {}, "timeout": 0, "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN", "maxContentLength": -1, "headers": { "Accept": "application/json, text/plain, */*", "Content-Type": "application/json;charset=UTF-8", "Access-Control-Allow-Origin": "*" }, "method": "post", "url": "http://10.0.3.98:8000/token-auth/", "data": "{\"username\":\"testaccount\",\"password\":\"testpassword\"}" }, "request": {} } Here is my request code axios.post('http://10.0.3.98:8000/token-auth/', JSON.stringify(data), {headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", }}, ).then( res => ( console.log(JSON.stringify(res)), ) ).catch( err => ( console.log(JSON.stringify(err)) ) ); my curl code that worked curl -d '{"username":"testaccount", "password":"testpassword"}' -H "Content-Type: application/json" -X POST http://10.0.3.98:8000/token-auth/ -
path('direct/',DirectView.as_view(),name='direct'), AttributeError: type object 'DirectView' has no attribute 'as_view'
here is my views.py code class DirectView(mixins.CreateModelMixin): serializer_class=DirectSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self,request,*args,**kwargs): return self.create(request,*args,**kwargs) and my urls.py path('direct/',DirectView.as_view(),name='direct'), but whenever i tried to run the server i get an error as AttributeError: type object 'DirectView' has no attribute 'as_view' i don't understand what the issue is ? -
Django override slugify globally
I've encountered a problem with Django's built-in slugify function. I'm building a website using Django framework. The site must have a forum app. After a bit of searching, I've found one. It works great, however, it's using the slugify function heavily on the topic titles to create "human readable" links to its pages. The problem is, we are writing in Russian, so as the result, it generates non-ASCII URLs which look like an unreadable mess of unicode data when trying to copy the link from the browser (and also throws an exception when trying to log them). Is there a way to override the Django's django.utils.text.slugify globally for the whole project so I don't need to include half of the third party library only to change the import statements in their models.py ?