Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Send CSRF token to ajax request Using Django?
i Want to Send csrf token in Ajax Request in Django.i don't know how to do that .i have following Code. in My html File, i am having one button <div class="col-md-6 col-sm-12 text-right" id="button_div"> <a href="#" id="add_data" class="btn btn-primary">Add</a> </div> <div id="dynamic_table"> /*some html*/ </div> When i Click on "Add" button,i Empty "dynamic_table" and i Append my contact form code into "dynamic_table" div. Contact Form code is <form> <input type="text" name="fname"> <input type="text" name="lname"> <input type="button" name="send" value="send"> </form> for that i am Using following Code $(document).on('click','#add_ajax',function(){ $("#dynamic_table").empty(); $("#dynamic_table").append('<form><input type="text" name="fname"><input type="text" name="lname"><input type="button" name="send" id="form_save" value="send"></form>'); }); till now, its working fine but When i CLick on "form_save" button from my contact form $(document).on('click','#save_btn',function(){ alert('hello') }) i am Getting following Error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST … -
matching query does not exist , Django error
** Item matching query does not exist.** -
Django Self Foreign Key......why we need to use them?
I have a question.i have seen people tend to use "self foreign-key" while structuring hierarchy , like, Category > Sub Category > Sub-Sub... > .... And to put all category,sub category,brand names in one model field.(In one database column). Isn't it easier to arrange them in different model fields and using foreign-key to each other and not pointing to self?? Which is more relatable?? -
Django: How to authenticate users for multiple app in Django?
I created a Login and signup app in Django Now I created another app for the profile page but I am unable to inherit user information that app. I used Django built-in Authentication and User models for that. Plz, Help. -
Django channels, AttributeError
I'm trying to learn how to send messages over a websocket using channels 2. I'm trying just to send a simple message when a client connects but I keep getting Attribute Errors: class CameraOnlineConsumer(JsonWebsocketConsumer): def connect(self): self.accept() return self.send({ "type": "websocket.accept", "send": {'a': "Hi"} }) raises: self.sendMessage(content.encode("utf8"), binary) AttributeError: 'dict' object has no attribute 'encode' WebSocket DISCONNECT /ws/camera_online/connect [127.0.0.1:36006] changing to: return self.send({ "type": "websocket.accept", "send": "Hi" }) for example, returns the same error. -
How to create Likes button on wagtail
Now, I am developing the website for studying Japanese and want to create Likes button on my website by wagtail. However it's so confusing me. Anyway, This is the core code. I coded them while I saw a couple of website about Like button in Django as my reference. However, This is for Django, is not completely same with wagtail, and while repeating finding out website and add codes, the code is awful disorder and I didn't know where I am, so, I really need your help. What I did Defining Article and Like on Blocks.py Inheriting that and modeling Articles and Like as a class (Folder:Articles) although I wrote urls.py and Views.py, how to write path is incorrect, perhaps. Following code is a model class about Like. #url.py from articles import views from articles.views import ( LikeButton, ) url(r'like/', views.LikeButton, name="like_page"), #url(r'^(?P[\w-]+)/like/$', LikeButton.as_view(), name='like_api'), -
Unable to connect to Amazon RDS Postgres Database from my Django Web Application
I am trying to deploy a website using elastic beanstalk and connect it up to a Postgres Database. When trying to makemigrations in django I am getting an error. I have been able to successfully set up a local Postgres database. I have been trying for a while with no luck. This is the Error Log (venv) C:\Users\dania\Development\Cliquefit>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "cliquefit.c8lfjtthzko9.ap-southeast-2.rds.amazonaws.com" (13.239.177.165) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle loader.check_consistent_history(connection) File "C:\Users\dania\Development\Cliquefit\venv\lib\site-packages\django\db\migrations\loader.py", … -
django- onclick function do not works in for loop of django
I have Created a button which onclick creat a another button , The code is like that <li ><button type="button" class="btn btn-danger" onclick="showdel();">Delete Photo</button></li> and in div where id is del the other button created , code id below {% if images %} <div class="row gallery-filter mt-4"> {% for image in images %} <div class="col-lg-4 col-sm-6 mix crossfit workout"> <div class="gallery-item"> <img src="http://127.0.0.1:8000{{ image.cover.url }}" alt=""> <div class="gi-hover-warp"> <div class="gi-hover"> <a href="{{ image.cover.url }}" class="image-popup"><i class="fa fa-search-plus"></i></a> <h6>Time to Try a Bodyweight Workout <h6> </div> </div> </div> <div id="del"></div> </div> {% endfor %} {% else %} <center><h3 class="text-white ">No Images</h3></center> {% endif %} and code of java script function showdel(){ var div = document.getElementById('del'); div.innerHTML = '<center><button class="btn btn-danger">DELETE</button></center>'; } above photo is of the output. but I want that the button should create in below all the pictures -
How to solve CORS with Django and VueJs?
How to solve CORS with Django and VueJs? I have made some settings, but I can't solve it. Could anyone help? INSTALLED_APPS = [ .... 'rest_framework', 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True Axios axios.defaults.headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' } Access to XMLHttpRequest at 'https://api.novosite.com/api/token' from origin 'https://novosite.vip' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
Can't save changes to my settings.py file in django
Whenever I make any changes in settings.py file , and try to save it , I get an alert saying UNABLE TO SAVE:PERMISSION DENIED. First I thought it is because as I am not the owner of the folder . But after changing settings and gaining ownership I am still getting the same alertenter image description here -
Digg-style pagination limit page number showing in template
I am using django-el-pagination package and trying to implement digg-style pagination on my home template. I am displaying it with.. {% get_pages %} {{ pages.get_rendered }} and it is showing like this <1234567> which is fine but I want to add some css or class to change the way it look. It will be good if it only display 5 page number like <12345> instead of showing all page numbers. -
What will be the most efficient way to filter the objects in django
I am working on a basic ecommerce website.I have created a superuser page in which I would like to see all the orders as well as the order details like customer who ordered, their address etc. These are my models.py: class ShippingAddress(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True) address=models.CharField(max_length=200,null=False) email=models.EmailField(null=False) class Customer(models.Model): user=models.OneToOneField(MyUser,null=True,blank=True,on_delete=models.CASCADE) email=models.CharField(max_length=100) class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True,blank=True) complete=models.BooleanField(default=False,null=True,blank=False) class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,) And this is my views.py: def superuser(request): user=User.objects.all() customer=Customer.objects.all() order=Order.objects.filter(complete=True) items=OrderItem.objects.all() shipping=ShippingAddress.objects.all() return render(request,"superuser.html",{'order':order,'items':items,'customer':customer,'shipping':shipping}) Currently in my template I am unable to iterate over the above context such that I can get all the orders and with the every order I can print their orderitems as well as shipping details as well as customer details. I tried in one way which was really in efficient that was to iterate over all orders then iterate over all orderitems and check if orderitem.order.id was equal to order.id . Please tell me what is the best method to pass the objects in context which are the most efficient for my need . And how to iterate over them in my template. Thanks -
Remove bullet points in RadioSelect Widget in django
I have a form that inherits from a model in Django that is rendered with a RadioSelect widget. I would like to remove the bullet points. Mi form is like this: class FormFromModel(forms.ModelForm): c1 = [(1, 'Answer 1'), (2, 'Ans2'), (3, 'Ans3'), (4, 'Ans4'), ] q1 = forms.IntegerField(label='Question.... ?', widget=forms.RadioSelect(choices=c1), initial=4) And in the HTML I'm doing: <table> <tr> <td><b> 1. {{Inputs.q1.label}}</b></td> </tr> <tr> <td> {{Inputs.q1}}</td> </tr> </table> I have something like: What currently have And I will like: What I want Any help is appreciated, Thanks -
The test outputs 2 errors I can't figure out where they came from
Guys I need help and then I'm racking my head everything seems to be correct but the code outputs an error I will be grateful for your help and if you share information and experience from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import WebDriverException import time MAX_WAIT = 10 class NewVisitorTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() def tearDown(self): self.browser.quit() def wait_for_row_in_list_table(self, row_text): start_time = time.time() while True: try: table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertIn(row_text, [row.text for row in rows]) return except (AssertionError, WebDriverException) as e: if time.time() - start_time > MAX_WAIT: raise e time.sleep(0.5) #def test_can_start_a_list_and_retrieve_it_later(self): #self.browser.get(self.live_server_url) #header_text = self.browser.find_element_by_tag_name('h1').text #self.assertIn('To-Do', header_text) #inputbox = self.browser.find_element_by_id('id_new_item') #self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item') #inputbox.send_keys('buy knife') #inputbox.send_keys(Keys.ENTER) #self.wait_for_row_in_list_table('1: buy knife') #inputbox = self.browser.find_element_by_id('id_new_item') #inputbox.send_keys('Сделать мушку из павлиньих перьев') #inputbox.send_keys(Keys.ENTER) #self.wait_for_row_in_list_table('1: buy knife') #self.wait_for_row_in_list_table('2: Сделать мушку из павлиньих перьев') #table = self.browser.find_element_by_id('id_list_table') #rows = table.find_element_by_tag_name('tr') #self.assertIn('1: buy knife', [row.text for row in rows]) #self.assertIn('2: Сделать мушку из павлиньих перьев', [row.text for row in rows]) def test_can_start_a_list_for_one_user(self): self.wait_for_row_in_list_table('2: Сделать мушку из перьев') self.wait_for_row_in_list_table('1: buy knife') def test_multiple_users_can_start_lists_at_different_urls(self): self.browser.get(self.live_server_url) inputbox = self.browser.find_element_by_id('id_new_item') inputbox.send_keys('buy knife') inputbox.send_keys(Keys.ENTER) self.wait_for_row_in_list_table('1: buy knife') edith_list_url = self.browser.current_url self.assertRegex(edith_list_url, '/lists/.+') self.browser.quit() self.browser = webdriver.Firefox() self.browser.get(self.live_server_url) page_text … -
What is the relationship with the variable user in Django with the User model?
I've noticed throughout my time studying Django that when I want to reference a users attributes I can do so by saying something like user.username etc. Obviously my assumption thus far has been that this variable "user" referencing the User model in Django but I haven't been able to find it anywhere officially. Can someone verify this to me so I can put this thought behind me? Thank you! -
Cannot assign "''": "IncomeExpense.username" must be a "User" instance
I hope all are fine and safe. I am working on this below code, trying the add data to the table by getting the values from the form. I have also marked where i am getting the error with "#" Please help me with this and let me know if you have any clarification required from this i have pasted views.py, models.py and createentry.html codes below.What might be the reason why i am getting this error and also explain me what can i change to get rid of this error. #views.py def create_entry_form(request): if request.method=='POST': entry_type=request.POST.get("expensetype") amount=request.POST.get("amount") details=request.POST.get("entrydetails") capture_date=time.strftime('%Y-%m-%d') entry_username=request.POST.get("entryusername") entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username) #getting_error_in_this_line entry.save() user_balance = UserBalance.objects.filter(username=username).values_list('balance', flat=True)[0] if entry_type=="income": total_balance = user_balance + amount else: total_balance=user_balance - amount update_balance=UserBalance.objects.get(username=username) update_balance.value=total_balance update_balance.save() return render(request, "homepage.html", {'name':username, 'balance':total_balance}) else: return redirect("www.google.com") #createentry.html <form action="{% url 'create_entry_form' %}" method="post"> {% csrf_token %} <div class="container register-form"> <div class="form"> <div class="note"> <p>Create Entry Form</p> </div> <div class="form-content"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <select name="expensetype" id="expensetype" class="form-control"> <option value="expensetype">Select Expense Type</option> <option value="income">income</option> <option value="expense">expense</option> </select> </div> <div class="form-group"> <input type="text" name="amount" id="amount" class="form-control" placeholder="Enter the Amount" value=""/> </div> </div> <div class="col-md-6"> <div class="form-group"> <input type="text" name="entrydetails" id="entrydetails" class="form-control" placeholder="Enter the … -
How to use to make custom decorators in Django?
I am absolutely beginners in python, django framework. I don't know how to make custom decorators in django. I am trying to, if user's profile is 100% completed they can apply job, else they can shows the warning message "your profile is nit completed, please first of all complete your profile then apply this job" I have following this code models.py class profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True) random = models.CharField(max_length=50) image = models.ImageField(upload_to="profile_pics") def __str__(self): return f'{self.user.username} profile' def get_absolute_url(self): return reverse('jobseeker:profile_count') @property def percentage_complete(self): percent = { 'random': 50, 'image': 50} total = 0 if self.random: total += percent.get('random', 0) if self.image: total += percent.get('image', 0) return total decorators.py def complete_profile_required(view_func): def wrapper_func(request, *args, **Kwargs): if request.user.profile.percentage_complete == 100: print(request.user.profile.percentage_complete) return redirect('jobseeker:apply_job') else: return view_func(request, *args, **Kwargs) return wrapper_func views.py @login_required @jobseeker_required @complete_profile_required def apply_job(request): return render(request, 'apply_job.html') urls.py path('apply_job', views.apply_job, name='apply_job') it will returns the this error -
why onlick function in button tag not working properly
I have created a delete Photo button which works as if we click on it a another delete button appear in somewhere in code , the code is <button type="button" class="btn btn-danger" onclick="showdel()">Delete Photo</button> after that I created div element where that delete button should be created . <div id="del"></div> and function for this is . function showdel(){ var div = document.getElementById('del'); div.innerHTML = '<center><button class="btn btn-danger">DELETE</button></center>'; } But it is not working , please help -
TemplateDoesNotExist at /student/student_form/
When i try "http://127.0.0.1:8000/student/student_form/" it gives an error like TemplateDoesNotExist at /student/student_form/ Please help me to resolve these issues and thanks in advance This is my templates code in settings.py file TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] This is my views.py file def student_list(request): return render(request,"student_list.html") def student_form(request): return render(request, "student_form.html") def student_delete(request): return This is my url.py files urlpatterns = [ path('admin/', admin.site.urls), path('student/', include('student_reg.urls')) ] urlpatterns = [ path('student_form/', views.student_form), path('student_list/', views.student_list), ] This is my project structure ├── CRUD │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ ├── settings.cpython-35.pyc │ │ ├── urls.cpython-35.pyc │ │ └── wsgi.cpython-35.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── student_reg ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-35.pyc │ └── __init__.cpython-35.pyc ├── models.py ├── __pycache__ │ ├── admin.cpython-35.pyc │ ├── __init__.cpython-35.pyc │ ├── models.cpython-35.pyc │ ├── urls.cpython-35.pyc │ └── views.cpython-35.pyc ├── templates │ ├── base.html │ ├── student_from.html │ └── student_list.html ├── tests.py ├── urls.py └── views.py -
'AnonymousUser' object has no attribute 'user_type'
I am trying to display data on my base.html file so I decided to use context processor to achieve that below is my code def meeting_notifications(request): if request.user.user_type == 'CDA Admin': n = Meetings.objects.filter(meeting_class='CDA Admin') context = {'notifications':n} return context elif request.user.user_type == 'CDA Member': n = Meetings.objects.filter(meeting_class='CDA Member') context = {'notifications':n} return context But below is the error I get 'AnonymousUser' object has no attribute 'user_type' When I added @login_required and check if the user is authenticated as seen in the code below @login_required(login_url='/backoffice/') def meeting_notifications(request): if request.user.is_authenticated: if request.user.user_type == 'CDA Admin': n = Meetings.objects.filter(meeting_class='CDA Admin') context = {'notifications':n} return context elif request.user.user_type == 'CDA Member': n = Meetings.objects.filter(meeting_class='CDA Member') context = {'notifications':n} return context I now have a new error when I tried to load my page. I will appreciate it if I get help from someone. dictionary update sequence element #0 has length 0; 2 is required -
How can I fix this paginator problem in python
in my views I defined the paginator function to show only 2 posts per page, but the thing is that every time I add a new post the pagination in the bottom changes, but it still shows all the posts instead of two, I'm going to share my code so you can check if I'm doing any mistakes. views.py def StockView(request, sym, ): stock_posts = Post.objects.filter(stock__symbol=sym) stock_sym = get_object_or_404(StockNames,symbol = sym) post_list = Post.objects.filter(stock__symbol=sym) paginator = Paginator(post_list, 2) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'app1/stockview.html', {'page':page,'posts':posts,'stocks':stock_posts, 'stock_sym':stock_sym, 'sym':sym }) models.py class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) urls.py app_name = 'app1' urlpatterns = [ path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'), path('stock/<str:sym>/', views.StockView, … -
Django Rest Framework - customize default list view to show unique values for ManyToMany fields
My models are bound with multiple fields using ManyToMany and "through" property something like this: class KLA(): version = ForeignKey("Version", on_delete=CASCADE) stages = ManyToManyField('Stage',through='KlasOutcomes', blank=True) objectives = ManyToManyField('Objective', through='KlasOutcomes', blank=True) outcomes = ManyToManyField('Outcome', through='KlasOutcomes', blank=True) class KlaSerializer(SerializerCacheMixin, ModelSerializer): version = VersionSerializer(many=False, read_only=True) class Meta: model = KLA list_serializer_class = CachedListSerializer fields = ('outcomes', 'version', 'stages') I am trying to return unique values for a specific field that is otherwise repeated due to combination of other fields in the table like this: In other word, "stages" should have only one entry 23 in the list. I tried using following to return unique stages for my model: @property def stages(self): return self.stage_set.all() But it doesn't help, gives following error: -
Django CMS, there is a piece of HTML in the include, how to include this piece twice on one page and so that you can change different content?
There is a template in the include / skver_cards folder {% load cms_tags %} {% load static %} <div class="cards"> <div class="card__item"> <div class="card__top"> {% placeholder 'card__top_c1' %} </div> <div class="card__foot"> {% placeholder 'card__foot_c1' %} </div> </div> ......... </div> I connect this piece on one page twice, is it possible somehow that one include had one content, and the other has another ???? it just turns out if I change something in the first, then it changes in the second, what can be done ??? {% include './include/cards.html' %} <br><br> {% include './include/cards.html' %} -
XMLHttpRequest - url not found
I am making a quiz app, and I want each answer to be submitted without a page refresh. So for this I am using the following script: window.onload = initial; var saveAnsButton; function initial(){ saveAnsButton = document.getElementsByClassName("save_ans")[0] saveAnsButton.onclick = saveans; } function saveans(){ var ans = $("input:radio[name=choice]:checked").val() alert("Answer: "+ans+" submitted"); var req = new XMLHttpRequest(); var url = '/save_ans?ans='+ans req.open("GET", url, true); req.send(); } The relevant parts of my html: {% for q in question_list %} {{q}} <br> {% for choice in q.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.answer }}"> <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br> {% endfor %} {% endfor %} {% if page_obj.has_next %} <a class='btn btn-warning save_ans' href="?{% param_replace page=page_obj.next_page_number %}">Save answer</a> {% else %} <a class='btn btn-warning save_ans' href="#">Save answer</a> <br> <br> <a class='btn btn-success submit_ans' href="{% url 'quizzes:song_results' 1 %}">Submit Answers</a> {% endif %} <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> This works to the extent that I get the alert and the selected answer. However, I get the following error in the console: Cannot set property 'onclick' of undefined at initial And I also get the following in the console: Not Found: /save_ans I've tried all … -
can't authenticate user in django
I create authentication link to email the user and this is the error I get: Reverse for 'activate' with keyword arguments '{'uidb64': 'MzA', 'token': 'a8o36j-51326a9d14c0ebf00a88a9a8c4983014'}' not found. 1 pattern(s) tried: ['activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] urls.py: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate'), line from views.py: message = render_to_string('main/acc_active_email.html' activate function in views.py: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') acc_active_email.html: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'main:activate' uidb64=uid token=token %} {% endautoescape %} Now it may be because I copied it from an article that refrences an older version of django. any help is apperciated!