Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve key error in nested representation of a model in django
This is my model: class MyModel(models.Model): ID = models.ForeignKey(OtherModel,related_name='NewModel', on_delete=models.CASCADE) start = models.BigIntegerField() duration = models.BigIntegerField(default= 30) value = models.IntegerField() where OtherModel has 2 fields, biginteger and foreignkey. I am trying to create an instance of the MyModel and it gives me a key error. The serializer is as below: class ModifyReadingSerializer(serializers.Serializer): duration = serializers.IntegerField() start = serializers.IntegerField() class OriginalSerializer(serializers.ModelSerializer): timePeriod = ModifyReadingSerializer(source = '*') class Meta: model = MyModel fields = ('timePeriod', 'value',) And the view to create it shown below: class RegisterValues(generics.ListCreateAPIView): ''' GET/POST urltemp/{ID = pk}''' queryset = MyModel.objects.all() serializer_class = OriginalSerializer def post(self, request, *args, **kwargs): s1 = OtherModel.objects.get(mRID=kwargs["pk"]) a_temp = MyModel.objects.create( ID=s1, value=request.data["value"], duration=request.data["duration"], start=request.data["start"],) return Response(data=OriginalSerializer(a_temp).data) I get the following error KeyError at /urltemp/1 'duration'. I understand why I am getting the error but not sure how to fix it while maintaining the nested representation. And I can see the error is in the line where I am creating duration (I can see it in the terminal). -
Restrict Admin/ access to anonymous users and not admins django
I have a new app: newApp with 3 users [admin, user1, user2] and a login page (not from /admin/). Is it possible to restrict/redirect access to django's Admin login? i want to just get into the admin/ path if the user logged IS and admin, That means it should not work if im not logged nor logged as normal user. -
Facebook Messenger Webhook not sending get request
I'm creating a bot app via Python and Django. I want to add webhook to my messenger app but when I fill all the fields Webhook doesn't go green, it's just closing the popup and I don't get any errors. Then I can change "Edit Events" but when I'm clicking save nothing happens. I'm using ngrok for my server but I don't get any GET request or anything, and facebook does not provide any error. Thanks in advance. -
What is the best way to serve css for a django production site?
After using collectstatic, my css files are hosted on AWS like all of my media files, which means manually uploading an updated file every time I have changes. There must be a better way, right? -
Django filter data in a form to another page
I can't seem to get this right, and I have viewed almost every like post. And now I have no clue what my code is doing. I have an index page, that has a small form. I just want to use this form to query my db and filter the results. I used django-filters on another page, and it works perfectly, but I can't seem to pass the data from my index page's form to the next view. Here is my code: urls.py from django.urls import path from .views import IndexView from . import views urlpatterns = [ path('', IndexView.as_view(), name='index'), path('search/', views.search, name='search'), ] views.py from django.db.models import Max, Min from django.shortcuts import render from django.views.generic import FormView from .filters import ProductFilter from .forms import ProductSearchForm from .models import LengthRange, Hull, PowerConfiguration, SpeedRange, Product class IndexView(FormView): template_name = 'index.html' form_class = ProductSearchForm success_url = "search/" def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['length_ranges'] = LengthRange.objects.all().order_by('pk') context['hull_types'] = Hull.objects.all().order_by('pk') context['power_configs'] = PowerConfiguration.objects.all().order_by('pk') context['speed_ranges'] = SpeedRange.objects.all().order_by('pk') context['price'] = Product.objects.all().aggregate(Min('price'), Max('price')) return context def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. # form.send_email() # print "form is valid" return … -
Django: set Foreignkey on new form after original form is complete
I am have multiple forms that are all linking back to a main Property. What I want to happen is that the user creates a Property and gets redirected to a page that has all the other forms shown on a sidebar. The user then selects what additional forms they then want to fill out. I am trying to figure out how to make it so that the remaining forms already have as their ForeignKey the Property that was created instead of having them select it through the dropdown menu. Really appreciate it. forms.py class Property(forms.ModelForm): class Meta: fields = ('name','address','city','state','zipcode') model = models.Property class TenantForm(forms.ModelForm): class Meta: fields = ('tenant_name') model = models.Tenant def create_view(request, **kwargs): if request.method == "POST": aaa = resolve(url).kwargs form = TenantForm(request.POST) if form.is_valid(): tenant = form.save(commit=False) tenant.property_name = aaa tenant.save() return reverse('dashboard:tenant', kwargs={'pk':self.pk}) models.py class Property(models.Model): name = models.CharField( max_length=255, unique=True) address= models.CharField(max_length=255,blank=True) city = models.CharField(max_length=255) state = models.CharField(max_length=255) zipcode = models.CharField(max_length=255) slug = models.SlugField(allow_unicode=True,unique=True, default=uuid.uuid1) def __unicode__(self): return "%s %s" % (self.name, self.city) def __str__(self): return self.name def save(self,*args,**kwargs): self.slug=slugify(self.name) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('dashboard:property_added', kwargs={'slug':self.slug}) class Tenant(models.Model): property_name= models.ForeignKey( Property, on_delete=models.CASCADE, ) tenant_name = models.CharField(max_length=255, unique=True, default='') urls.py path('property/',views.CreateProperty.as_view(),name='property'), path('property/<slug>/',views.ModifyProperty.as_view(),name='property_added'), path('tenant/',views.CreateTenant.as_view(),name='tenant'), -
Where do I create python files in a virtual environment
I created and activated a virtual environment and installed Django. Then I created an apps directory and ran django-admin.py startproject foo. When I run python manage.py runserver everything is fine and I see the default 'Congratulations' page Next I want to replace the default pages with my views.py etc. If I put them in apps\foo (where I run manage.py runserver), they don't show up in my browser. Are they actually supposed to go somewhere in virtualenvs\foo rather than apps\foo? If so, where? Everything in there looks to be related to Python, Django and PIP -
Save related child model fields from parent - Django
I have these models: class MyModel1(models.Model): field1 = models.CharField(max_length=128, blank=True, null=True) fieldrelated1 = models.OneToOneField('MyModel2', max_length=128, blank=True, null=True, related_name='mymodel2') fieldrelated2 = models.OneToOneField('MyModel3', max_length=128, blank=True, null=True, related_name='mymodel3') fieldrelated3 = models.OneToOneField('MyModel4', max_length=128, blank=True, null=True, related_name='mymodel4') class MyModel2(models.Model): field2 = models.CharField(max_length=128, blank=True, null=True) test = models.CharField(max_length=128, blank=True, null=True) class MyModel3(models.Model): field3 = models.CharField(max_length=128, blank=True, null=True) test = models.CharField(max_length=128, blank=True, null=True) class MyModel4(models.Model): field4 = models.CharField(max_length=128, blank=True, null=True) test = models.CharField(max_length=128, blank=True, null=True) What I need, is when I save a record from MyModel1, create automatically an object on MyModel2, MyModel3 and MyModel4. With some filled fields with data from the parent. So far, I have this: def create_child_records(instance, created, rad, **kwargs): if not created or rad: return if not instance.fieldrelated1_id: fieldrelated1, _ = MyModel2.objects.get_or_create(field1=field2) instance.fieldrelated1 = fieldrelated1 if not instance.fieldrelated2_id: fieldrelated2, _ = MyModel3.objects.get_or_create(field1=field3) instance.fieldrelated2 = fieldrelated2 if not instance.fieldrelated3_id: fieldrelated3, _ = MyModel4.objects.get_or_create(field1=field4) instance.fieldrelated3 = fieldrelated3 instance.save() models.signals.post_save.connect(create_child_records, sender=MyModel1, dispatch_uid='create_child_records') But when I try to save from parent it throws me: name 'field2' is not defined This method is at the end of the parent model, unindented, if I indent it, it throws: ValueError: Invalid model reference MyModel1. String model references must be of the form 'app_label.ModelName' If I enclose the sender model … -
When i make post via admin page in Django it doesnt show up
Literaly like title say...check the picture. When i try to make new Post it says i made it but it wont show up on admin page nor in detail.html. http://prntscr.com/n0pfrv here is my code for post model from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(help_text="A short label, generally used in URLs.",default='', max_length=100) image = models.ImageField(default='default.jpg', upload_to='profile_pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date_posted'] def save(self): slug = self.title def get_absolute_url(self): return reverse('detail', kwargs={'slug':self.slug}) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): list_display = ['title', 'slug', 'date_posted', 'author'] list_filter = ['title', 'date_posted'] prepopulated_fields = { 'slug': ('title',)} admin.site.register(Post, PostAdmin) views.py in app called blog were i have model Post also from django.contrib import messages from . models import Post from django.core.mail import send_mail from django.views.generic import DeleteView, ListView def index_view(request): return render(request, 'blog/index_view.html') def blog_view(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/blog_view.html', context) class PostDetailView(DeleteView): model = Post template_name = 'blog/detail.html' context_object_name = 'post' If you need any other of my code im gonna post it -
Pass QuerySet object id to model to get self
I am trying to trigger a method in my models to run by hitting a url.When it hits it returns and error saying "unsupported operand type(s) for -: 'datetime.datetime' and 'NoneType'". views.py from django.shortcuts import render from rest_framework import viewsets from .serializers import EntrySerializer from .models import Entry class EntryView(viewsets.ModelViewSet): serializer_class = EntrySerializer queryset = Entry.objects.all() entryId = Entry.objects.filter(end_time__isnull=True).values('id') # returns <QuerySet [{'id': 8}]> for id in entryId: entryIdNum = id['id'] #returns 8 entry = Entry() def ToggleView(request): entry.toggle_paused() entry.save() models.py from django.db import models from django.db.models import F, ExpressionWrapper, fields from django.utils import timezone from dateutil.relativedelta import relativedelta from decimal import Decimal class Entry(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField(blank=True, null=True, db_index=True) seconds_paused = models.PositiveIntegerField(default=0) pause_time = models.DateTimeField(blank=True, null=True) comments = models.TextField(blank=True) date_updated = models.DateTimeField(auto_now=True) hours = models.DecimalField(max_digits=11, decimal_places=5, default=0) def _str_(self): return self.TUID @property def total_hours(self): """ Determined the total number of hours worked in this entry """ total = self.get_total_seconds() / 3600.0 # in case seconds paused are greater than the elapsed time if total < 0: total = 0 return total @property def is_paused(self): """ Determine whether or not this entry is paused """ return bool(self.pause_time) def pause(self): """ If this entry is not paused, pause … -
How do I write a Django join query in which the join is based on a function?
I'm using Django and Python 3.7 (and PostGres 9.5). In my Django models.py file, I have two types of models, Articles and Labels. There is no explicit join between these tables. I would like to run a Django query that does an inner join based on a function. In PostGres, it's written like so ... select distinct a.id FROM myapp_article a inner join myapp_label l on position(lower(l.name) in lower(a.label))> 0; How would I write the Django query? Basically this question is how do you write a Django query in which the join is based on a function. -
Inconsistencies when running vue dev mode vs production
I am working on a django project where we use Vue js in some of our templates. When I run Vue in production everything works as excepted. When I switch over to the development version of Vue I encounter all sorts of errors, not warnings but actual errors. It appears that all the errors seem to be with importing functions/objects from other files. For instance, we have a vuex store declared in another file which can not be found in the main instance of Vue when running in development but works fine in production. The same happens with functions located in a utils file. What really confuses me is that this all used to work in development at some point. I have collected static, I have cleared browser cache, have set debug to True, and doubled checked the imports. Has anyone else had this problem or have any ideas on how to go about fixing it? -
Tinymce - An invalid form control with name='text' is not focusable
When submitting a form in Django I get: An invalid form control with name='text' is not focusable. The reason it isn't working is because 'Chrome wants to focus on a control that is required but still empty so that it can pop up the message 'Please fill out this field'. However, if the control is hidden at the point that Chrome wants to pop up the message, that is at the time of form submission, Chrome can't focus on the control because it is hidden, therefore the form won't submit.' - An invalid form control with name='' is not focusable But I am really not sure how to do this in TinyMCE or Django and was wondering if anyone knew. HTML: {% block content %} <div class="container"> <div class="form-create"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn btn-success" value="Publish"> </form> </div> </div> {% endblock %} {% block script %} tinyMCE.init({ selector: '#id_text', }); {% endblock %} Views: class PostCreateView(LoginRequiredMixin, PostEdit, CreateView): fields = ['title', 'text', 'category', 'image', 'sub_description'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Python how to generate qrcode
I'd like to generate a qr-code which will contain all informations concerning a user with django. can you help me please....even with a link or a code...or with a github project ;) thanks -
debugging django's mysql strict mode
When I run Django's migrate command on MySQL, I get a warning: $ ./manage.py migrate System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-sql-mode When I look at that URL, they recommend adding 'init_command' in DATABASE['OPTIONS'] (also noted here and here). So I did: DATABASES['default']['OPTIONS'] = { # Set MySQL strict mode. 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", } But the warning doesn't go away. Any suggestions of how to debug this further? -
Return data format like default DRF
I have spent too much time trying to figure out how to format a queryset and have drf return it like how its default GET request looks like. ex. get request looks like, a list of objects: [{ "id": 1093, "manytomanyrelation": [ 108793, 108792, 108791 ], "count": 3, }, { "id": 1092, "manytomanyrelation": [ 108793, ], "count": 5, }] My post request which needs to return a list of objects just like above: code: @list_route(methods=['post']) def mymethod(self, request, *args, **kwargs): data = MyModel.objects.filter(**params) response = serializers.serialize('json', list(data)) return HttpResponse(response, content_type='application/json') But this returns objects with pk, model, fields format: [{ fields:{ "manytomanyrelation": [ 108793, 108792, 108791 ], "count": 3, } model: "app.mymodel" pk: 1093 }, { fields:{ "manytomanyrelation": [ 108793, ], "count": 5, } model: "app.mymodel" pk: 1092 }] I stripped some fields and names so sorry if there something inconsistent in the data. Is there any way to format the response object to look like the drf default GET? -
Data is not add in DOM Tree /dynamically to table
Problem I am trying to make a Dyanamic(CURD operation) DataTable in Django But when I am Dynamically Add / Delete / Update Data it is not add to DOM/ Datatable. i am using Ajax,JQuery. please help, thank you view.py from music.models import serviceDb from music.forms import serviceForm from django.http import JsonResponse from django.template.loader import render_to_string def service_account(request): print('sulabh kumar') service_account = serviceDb.objects.all() context ={ 'service_account': service_account } print(len(service_account)) return render(request, 'service_account.html',context) def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True service_account = serviceDb.objects.all() data['service_account'] = render_to_string('service_account_list.html', {'service_account':service_account}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) def service_account_create(request): if request.method == 'POST': form = serviceForm(request.POST) else: form = serviceForm() return save_all(request,form,'service_account_create.html') def service_account_update(request,id): service_account= get_object_or_404(serviceDb,id=id) if request.method == 'POST': form = serviceForm(request.POST,instance=service_account) else: form = serviceForm(instance=service_account) return save_all(request,form,'service_account_update.html') def service_account_delete(request,id): print("id",id) data = dict() service_account = get_object_or_404(serviceDb,id=id) if request.method == "POST": service_account.delete() data['form_is_valid'] = True service_account = serviceDb.objects.all() data['service_account'] = render_to_string('service_account_list.html', {'service_account':service_account}) else: context = {'service_account':service_account} data['html_form'] = render_to_string('service_account_delete.html',context,request=request) return JsonResponse(data) service_account_list.html {% for service in service_account %} <tr> <td>{{service.application }}</td> <td>{{service.get_environment_type_display }}</td> <td>{{service.startdate }}</td> <td>{{service.expiredate }}</td> <td> <button class="btn btn-warning show-form-update" data-url="{% url 'service_account_update' service.id %}"> <span class="glyphicon … -
cannot assign must be a user instance django
I have created a model for form submission which is working fine, I want to create a new model for the submission of documents based on the respective form using the Form id as Foreign Key in the documents model My documents model is as follow: class PHDDocument(models.Model): user = models.ForeignKey(HigherStudiesForms, on_delete=models.PROTECT, null=True, blank=True) admission_letter = models.FileField(blank=False, null=False) award_letter = models.FileField(blank=False, null=False) attested_degree = models.FileField(blank=False, null=False) cv = models.FileField(blank=False, null=False) travel_agent = models.FileField(blank=False, null=False) surety_bond = models.FileField(blank=False, null=False) attested_surety_bond = models.FileField(blank=False, null=False) guarantee_cnic = models.FileField(blank=False, null=False) study_leave = models.FileField(blank=False, null=False) objection_certificate = models.FileField(blank=False, null=False) hod_form = models.FileField(blank=False, null=False) rector_form = models.FileField(blank=False, null=False) def __str__(self): return str(self.admission_letter) view method respect to the following model is as below: class PHDFileView(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) lookup_field = 'pk' lookup_url_kwarg = 'form_id' serializer_class = PHDDocumentSerializer def get_queryset(self): queryset = PHDDocument.objects.all() return queryset def perform_create(self, serializer): serializer.save(user=self.request.user) when I am submitting the documents after the form submission through Angular Django is giving the following error "ValueError: Cannot assign "User: ahssu": "PHDDocument.user" must be a "HigherStudiesForms" instance." -
Problem configuring django-redis with ElastiCache Redis (cluster mode enabled)
I am working on Django project that currently uses ElastiCache Redis 3.2.6 with multiple nodes in a "master/slave" configuration using the "redis_cache.RedisCache" backend. This works fine currently. However, I am in the process of migrating the project to a new ElastiCache Redis 5.0.3 instance with cluster mode enabled turned on. I have been unsuccessful in finding any documented method of configuring a connection from Django to ElastiCache's configuration endpoint for a Redis cluster. The closest thing I've found is this comment on the django-redis GitHub but when I try that configuration I get an error that says: rediscluster.exceptions.RedisClusterException: Redis Cluster cannot be connected. Please provide at least one reachable node. Is there some better way to accomplish this that I'm missing? -
Django - ModelForm - initial value
I'm working with Modelforms and would like to set the initial value of the "feeder" field. I get the following Type Error: "invalid literal for int() with base 10: 'None'" What might be the problem? Many thanks all forms.py: class CashFlowForm(forms.ModelForm): class Meta: model = models.CashFlow fields = ['type', 'amount', 'description','date'] widgets = {'date': DatePicker()} views.py: def create_cashflow(request, fundslug): funddetail = Fund.objects.get(slug=fundslug) if request.method == 'POST': cf = CashFlowForm(request.POST) cf.feeder = funddetail.feeder if cf.is_valid(): instance_cf = cf.save() messages.success(request, 'Cash Flow successfully added!') return redirect('funds:create_cashflow', fundslug = fundslug) else: cf = CashFlowForm() return render(request, 'funds/create_cashflow.html', {'cf': cf}) -
How should a web application ensure security when serving confidential media files?
Question: Say a user uploads highly confidential information. This is placed in a third party storage server. This third party bucket uses different authentication systems to the web application. What is the best practice for ensuring only the user or an admin staff member can access the file url? More Context: A Django web application is running on Google App Engine Flexible. Google Storage is used to serve static and media files through Django. The highly confidential information is passports, legal contracts etc. Static files are served in a fairly insecure way. The /static/ bucket is public, and files are served through django's static files system. This works because there is no confidential or user information in any of our static files, only stock images, css and javascript, and the files are uglified and minifed before production. For media files however, we need user specific permissions, if user A uploads an image, then user A can view it, staff can view it, but user B & unauthenticated users cannot under any circumstances view it. This includes if they have the url. My preferred system would be, that GCP storage could use the same django authentication server, and so when a … -
Heroku ProgrammingError at tables
I finally got my Django app (sort of) working on Heroku. It shows the main admin page, but when I want to open any of the tables I get the following error: (I have debug = true just to show the errors) https://i.stack.imgur.com/uL0sX.png Could someone help me with this? I have been stuck with trying to get it working on Heroku for a couple of days now and I am getting a bit desperate. My code can be found here: https://github.com/nmooij/petrichor-rain-system -
Syntax error ,I have tried to load my django project on a production server
I have tried to load my project on a production server,I have the below syntax error for something that was working fine in test environment,any help here? I cant see why I have the error f'accounts/emails/{template}.html', context) ^ SyntaxError: invalid syntax here is the code def send_mail(to, template, context): html_content = render_to_string(f'accounts/emails/{template}.html', context) text_content = render_to_string(f'accounts/emails/{template}.txt', context) Error Traceback Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f00e7044158> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 396, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", … -
What am I doing wrong with this AJAX in django?
I am trying to implement AJAX in django. I have the following file login.html This file contains the form and ajax script {% extends 'services/base_visitor.html' %} {% block title %}Log In{% endblock %} {% block login_active %}active{% endblock %} {% block body %} <div class="container-fluid" style="position: absolute;top:20%;left:35%;width:30%;"> <div class="panel panel-default"> <h3>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspLog In</h3> <center> <div class="panel-body"> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <!-- action="{% url 'login_user'%}" --> <form class="form-horizontal" role="form" action="{% url 'login_user'%}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <!-- <label class="control-label col-sm-2" for="id_username"> </label> --> <div class="col-sm-10"> <strong><span class="glyphicon glyphicon-user"></strong>&nbsp&nbsp&nbsp <input id="id_username" maxlength="30" name="id_username" type="text" placeholder="USERNAME" style="font-family: Courier New;font-size: 15px;border: none; border-bottom: 2px solid black;"> <div id="data"></div></span> </div> </div> <div class="form-group"> <!-- <label class="control-label col-sm-2" for="id_password"> </label> --> <div class="col-sm-10"> <strong><span class="glyphicon glyphicon-asterisk"></strong>&nbsp&nbsp&nbsp <input id="id_password" maxlength="30" name="id_password" type="password" placeholder="PASSWORD" style="font-family: Courier New;font-size: 15px; border: none; border-bottom: 2px solid black;"></span> </div> </div> </center> <div class="form-group"> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="submit" class="btn btn-success">Submit</button> </div> </form> </div> <div class="panel-footer"> Don't have an account? <a href="http://localhost:8000/register/">Click here</a> to register. </div> </div> </div> {% endblock %} {% block javascript %} <script> $("#id_username").change(function(){ alert("The text has been changed."); }); $("#id_username").change(function () { var username = $("#id_username").val(); console.log(username); $.ajax({ type:"POST", url: '/ajax/validate_username/', data:{ str:username, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() … -
Uncaught ReferenceError: response is not defined
I was trying to use ajax for a simple like section in a django website. the like button on being clicked likes the post but the html isn't changed. If i refresh the page the html changes. the console shows the following error Uncaught ReferenceError: response is not defined at Object.success ((index):271) at u (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at k (jquery.min.js:2) at XMLHttpRequest. (jquery.min.js:2) the javascript is given below <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click','#like', function(event){ event.preventDefault(); var pk= $(this).attr('value'); $.ajax({ type:'POST', url:'{% url "like_post" post.id %}', data:{'blog_id':pk,'csrfmiddlewaretoken':'{{ csrf_token}}'}, dataType:'json', success: function(event){ $('#like-section').html(response['form']) }, fail:function(rs, e){ console.log(rs, responseText); }, }); }); }); </script> html of the section <div> <form action="{% url 'like_post' post.id %}"> {% csrf_token %} {% if is_liked %} <button id="like" type='submit' name='blog_id' value="{{ post.id }}" class="btn ">unlike</button> {% else %} <button id="like" type='submit' name='blog_id' value="{{ post.id }}" class="btn ">like</button> {% endif %} </form> </div> the below is the code of the html page <div id="like-section"> {% include 'blog/like_section.html' %} </div>