Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix ajax call so i can hide my token?
i'm calling a ajax function in html file in which i have integrated python django URL in which i have to pass token for get something so the problem which i am facing is my token is showing while i do inspect page source in html page. i want to hide it using java-script or ajax how can i do that please look at my code below. $.ajax({ url : url, headers: {'Authorization': 'Token {{token}}'}, data : card_data, enctype : 'multipart/form-data', cache : false, contentType : false, processData : false, type : type, success : function(data, textStatus, jqXHR){ console.log(data); // Callback code if(data['status'] == 'error') { $("#lightbox").css({ 'display': "none" }); alert('error : ' + data['msg']); } else { $('#lightbox').find('h1').text('Saved, redirecting you to products page'); setTimeout(function(){ window.location.href = 'https://'+window.location.hostname+'/dashboard/destination/cards';}, 100); } } }); }); -
How to determine which button is pressed
I have a table in which I populate with data from the database. Some of this I have an extra feature of the delete button. But I can't understand how I get that what delete button is pressed in django <tbody> {% for i in list %} <tr> <td>{{i.id}}</td> <td>{{i.reason}}</td> <td>{{i.starting_date}}</td> <td>{{i.ending_date}}</td> <td>{{i.accept_or_not}}</td> {% if i.accept_or_not == 'pending'%} <td><input type="button" name="data_delete_{{i.id}}" value="delete"> </td> {%endif%} </tr> {% endfor%} </tbody> def profile_view(request): if 'data_delete_id' in request.POST: # i don't know how to determine the id in the button -
how to fix the error local variable 'ListQuery' referenced before assignment
i have a function in views.py that list all records and allow user to search for specific record where if filter the class "suspect" the problem that i got is once i tried to search the system crash and display the below error : local variable 'ListQuery' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/blog/list/ Django Version: 2.1.3 Exception Type: UnboundLocalError Exception Value: local variable 'ListQuery' referenced before assignment Exception Location: C:\Users\LT GM\Desktop\ABenvironment\myABenv\blog\views.py in listANDsearch, line 186 Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1 Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/blog/list/ Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'widget_tweaks', 'import_export'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\LT GM\Desktop\ABenvironment\myABenv\blog\views.py" in listANDsearch 186. elif ListQuery == []: Exception Type: UnboundLocalError at /blog/list/ Exception Value: local variable 'ListQuery' referenced before assignment views.py def listANDsearch(request): #deny anonymouse user to enter the list page if not request.user.is_authenticated: return redirect("login") else: queryset = suspect.objects.all() # return render(request,"blog/list.html", {"object_list":queryset}) #search query=request.GET.get("q") print("search … -
How to show successful message after edit and redirect to list view in django class based view?
I am having a list of 50 items showed in 5 pages(pagination), if i click edit button on an item in 3rd page. i will open a view to edit this item. After editing i need to go back to the same page(3rd one i this case) and show a success message there. Like update success. I have tired to show success message after the edit. But redirection is not possible. When i redirect success message is not possible. This is the way i redirect without having a success message list.html <td><a href="{% url 'test-app:edit-client-details' i.id %}?redirect_page={{ request.GET.page }}"><i class="fa fa-edit (alias) fa-fw" aria-hidden="true"></i></a></td> view.py def get_success_url(self): return '{0}?page={1}'.format(reverse_lazy('tayseer-admin:view-client-testimonials'),self.request.GET.get('redirect_page')) for showing success message in update view i used: def get_success_url(self): messages.add_message(self.request, messages.INFO, 'form updated success') return reverse("tayseer-admin:edit-client-testimonials", kwargs={'pk': self.kwargs['pk']}) in template i used. {% if messages %} <ul class="alert alert-success" id="msgclose"> {% for message in messages %} <ul{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }}</ul> {% endfor %} </ul> {% endif %} What i want is after editing the record, redirect to the exact page and show update was successful. Please help me get a solution for this. -
ConnectionRefusedError at /accounts/register/
When user enter email for password reset then error arise connection failure which is related to server failure error . raceback: File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\utils\decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\views.py" in dispatch 53. return super(RegistrationView, self).dispatch(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\views\generic\edit.py" in post 142. return self.form_valid(form) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\views.py" in form_valid 56. new_user = self.register(form) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\backends\default\views.py" in register 100. request=self.request, File "C:\ProgramData\Anaconda3\lib\site-packages\registration\models.py" in create_inactive_user 193. lambda: registration_profile.send_activation_email( File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\db\transaction.py" in exit 284. connection.set_autocommit(True) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\db\backends\base\base.py" in set_autocommit 409. self.run_and_clear_commit_hooks() File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\db\backends\base\base.py" in run_and_clear_commit_hooks 624. func() File "C:\ProgramData\Anaconda3\lib\site-packages\registration\models.py" in 194. site, request) File "C:\ProgramData\Anaconda3\lib\site-packages\registration\models.py" in send_activation_email 451. email_message.send() File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\mail\message.py" in send 291. return self.get_connection(fail_silently).send_messages([self]) File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\mail\backends\smtp.py" in send_messages 103. new_conn_created = self.open() File "C:\ProgramData\Anaconda3\lib\site-packages\django-2.2b1-py3.7.egg\django\core\mail\backends\smtp.py" in open 63. self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\ProgramData\Anaconda3\lib\smtplib.py" in init 251. (code, msg) = self.connect(host, port) File "C:\ProgramData\Anaconda3\lib\smtplib.py" in connect 336. self.sock = self._get_socket(host, port, self.timeout) File "C:\ProgramData\Anaconda3\lib\smtplib.py" in _get_socket … -
Django Models - how to pull data from 2 models and render
I'm building a survey-like app using Django. I have 3 models (Survey, Question, Answer). I need to query the Questions model and pull back the Questions PLUS the possible Answers for each question. Then, i need to display it on the html page as a single question, with the possible answers in a list or other element. Django==2.2.1 / Pillow==6.1.0/ pytz==2019.1/ sqlparse==0.3.0/ Python 3.7 I tried going from the Answers model but I end up with duplicate data and uncertain how to render. MODELS.PY class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question_sequence = models.IntegerField() question_to_ask = models.CharField(max_length=4000, unique=True) def __str__(self): return self.question_to_ask class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) possibleAnswer = models.CharField(max_length=4000) possibleAnswer_image = models.ImageField(blank=True, null=True) def __str__(self): return self.possibleAnswer VIEWS.PY def survey(request): q = [x for x in Question.objects.all().values()] questions_dict = {'questions': q} # a = [x for x in Answer.objects.select_related().all()] # answers_dict = {'answers': a} return render(request, 'survey_app/survey.html', context=questions_dict) .HTML <body> <div class=questions> {% if questions %} <h1> {% for q in questions %}</h1> <p> {{ q.question_to_ask }}</p> <p> {% for a in answers %}</p> <p> {{ a.question.question_to_ask }}</p> {% endfor %} {% endfor %} {% else %} <p> NO RECORDS SHOWN</p> {% endif %} </div> </body> My goals is … -
Access a form method from generic.UpdateView in Django
I have a view which is a generic.UpdateView, and I need to access a form method - get_hidden_fields(). How do I access it? I currently used self.form_class().get_hidden_fields() but I'm not sure if this is correct. I think it creates a new instance of the form and I want to use the current instance. def get_context_data(self, **kwargs): cd = super().get_context_data(**kwargs) cd.update({ 'matches_list': self.page.object_list, 'form_hidden_fields': list(self.form_class().get_hidden_fields()), }) return cd https://github.com/speedy-net/speedy-net/blob/staging/speedy/match/matches/views.py#L54 -
How to redirect after a success message in Django
I am creating a newsletter app and having issues with the redirect function working after a success message is displayed to the user. I have already tried various approaches to refactoring - [How to pass a message from HttpResponseRedirect in Django? [https://github.com/zsiciarz/django-envelope/issues/28] from django.conf import settings from django.contrib import messages from django.shortcuts import render, redirect, reverse from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import get_template """ Create views """ from .forms import CustomerSubscriptionForm from .models import CustomerSubscriptionUser def customer_subscribe(request): form = CustomerSubscriptionForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if CustomerSubscriptionUser.objects.filter(email=instance.email).exists(): messages.warning(request, "So you've already subscribe to us, so visit your email to see what we have in store for you!") return redirect('/experiment/subscribe') - **This is where the problem is** else: instance.save() messages.success(request, "We are excited that you're interested in being in our local dance community! We sent some more information to your email") subject = "Thank you for joining our community" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] subscription_message = "Hi, LET'S DANCE. If you want to unsubscribe got to http://127.0.0.1:8000/experiment/unsubscribe/ " send_mail(subject=subject, from_email=from_email, recipient_list=to_email, message=subscription_message, fail_silently=False) context = {'form': form} template = "experiment/subscribe.html" return render(request, template, context) Expected result - user is redirected to the form view after submitting … -
Django-admin how to disble change data on foriengkey. I want to be button for view only
How to add view button replace change button. in the Image below. How to view only not change. My code model class1 class Return_data(models.Model): request_product = ( ('select', 'Select'), ('TN', 'TN'), ('TX', 'TX'), ('MT', 'MT'), ) invoice_no = models.CharField(max_length=25, verbose_name='Invoice No.') etd_atg = models.DateField(verbose_name='ETD ATG') eta_amgt = models.DateField(verbose_name='ETA AMGT') product = models.CharField( max_length=20, choices=request_product, default='select') q_ty = models.IntegerField(verbose_name="Q'ty (pcs)") listemail = ( ('select', 'Select'), ('chanaphon.chommongkhon@agc.com', 'chanaphon'), ('jeerawan.pongkankham@agc.com', 'jeerawan'), ) liststatus = ( ('select', 'Select'), ('pending', 'Pending'), ('finish', 'Finish'), ) attached = models.FileField(upload_to='file',verbose_name='Attached file') emailto = models.CharField(max_length=30, choices=listemail, default='select',verbose_name='Email Send To') emailcc = models.CharField(max_length=30, choices=listemail, default='select',verbose_name='Email CC') pc_status = models.CharField(max_length=20, choices=liststatus, default='select',verbose_name='PC Status') How to view only in foreign key detail : #model class2 class Return_QA(models.Model): liststatus = ( ('select', 'Select'), ('pending', 'Pending'), ('finish', 'Finish'), ) invoice_noqa = models.ForeignKey(Return_data, on_delete=models.CASCADE,verbose_name='Invoice No') object_lot = models.CharField(max_length=20,verbose_name='Objectlot') qa_status = models.CharField(max_length=10, choices=liststatus,default='select',verbose_name='QA Status') -
How to import file into django without abstract link, not using statics
My Django project need to show some pdf files in web page. Files are stored out of my project. I can get their abstract link, but when I try to import them into my project, it doesn't work. When I copy file to my statics folder and change code with static, it worked. But there is a plenty of files, I can't download all of them to statics folder in my project. What should I do? -
How to fix 500 error after deploying when DEBUG = False, ALLOWED_HOSTS=['*']
I am getting a 500 error when I run the server on digital ocean and have set DEBUG = False in Settings.py of my django app. I am running the Django server on port 8000, and have had the same issue when using gunicorn. No errors show up when DEBUG = True, and my ALLOWED_HOSTS = ['*']. I have a custom 404 template and handler. The error shows up on any page I attempt to load, except the Django admin page. Please let me know if you have any ideas!!! Exact error message: "GET /accounts/login/ HTTP/1.1" 500 27 settings.py file: import os from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '**********' MAILMAN_PASSWORD = "*********" DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'mysite', 'webapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dashboard_db', 'USER': 'dashboard_db_admin', 'PASSWORD': '**********', 'HOST': 'localhost', 'PORT': '', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': … -
Can't display another Highcharts chart on my HTML page
Been looking at Highcharts doc and also "Integrating Django and Highcharts" by simpleisbetterthancomplex. I'm not sure what went wrong with my codes, that the second charts ain't display. I'm using Django views.py to retrieve data from the database. <div class="carousel-inner"> <div class="carousel-item active"> <div class="border" id="container" style="min-width: 100px; height: 400px; margin: 0 auto;"></div> <script src="https://code.highcharts.com/highcharts.src.js"> </script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> Highcharts.chart('container', {{ chart|safe }}); </script> </div> <div class="carousel-item"> <div class="border" id="container2" style="min-width: 100px; height: 400px; margin: 0 auto;"></div> <script src="https://code.highcharts.com/highcharts.src.js"> </script> <script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script> <script> Highcharts.chart('container2', {{ chart2|safe }}); </script> </div> <div class="carousel-item"> <div class="carousel-caption" > <h3>Currently Unavailable</h3> </div> </div> </div> Expected two charts to be display on two different panel of the carousel -
How to display the formset in django with TemplateResponseMixin
I keep getting Method Not Allowed: /2/module/ message error when i try to access this page. How can I access the view from this custom class based views. forms.py from django import forms from django.forms.models import inlineformset_factory from core.models import ( Course, Module ) ModuleFormSet = inlineformset_factory(Course, Module, fields = [ 'title', 'description'], extra=2, can_delete=True) views.py class CourseModuleUpdateView(TemplateResponseMixin, View): template_name = 'core/manage/module/formset.html' course = None def get_formset(self, data=None): return ModuleFormSet(instance=self.course, data=data) def dispatch(self, request, pk): self.course = get_object_or_404(Course, id=pk, owner=request.user) return super(CourseModuleUpdateView, self).dispatch(request.pk) def get(self, request, *args, **kwargs): formset = self.get_formset() return self.render_to_response({'course':self.course,'formset':formset}) def post(self, request, *args, **kwargs): formset = self.get_formset(data=request.POST) if formset.is_valid(): formset.save() return render('core:manage_course_list') return self.render_to_response({'course': self.course,'formset': formset}) template.py {% extends "base.html" %} {% block title %} Edit "{{ course.title }}" {% endblock %} {% block content %} <h1>Edit ""{{ course.title }}"</h1> <div class="module"> <h2>Course modules</h2> <form action="" method="post"> {{ formset }} {{ formset.management_form }} {% csrf_token %} <input type="submit" class="button" value="Save modules"> </form> </div> {% endblock %} urls.py path('<int:pk>/module/', views.CourseModuleUpdateView.as_view(), name='course_module_update') I am not sure where the problem is coming from as I tried to use PDB to check on everything. Any assistance will be much appreciated. -
Element of my django forms.py is not defined?
I've got a problem with django with handling forms : I created a form with 2 fields, and I associated it to my view, but it tells me that my fields are undefined. Could you explain me please ? I created a form in my index.html : <form action="/addUser" method="post"> {% csrf_token %} <label> Name of the Employee : <input type="text" name="employeeName", id="employeeName"/> </label> <label> Email of the Employee : <input type="email" name="employeeEmail", id="employeeEmail" /> </label> <button class="btn btn-primary" type="submit">Add User</button> </form> Then I created in views.py def addUser(request): if request.method == 'POST': form = CreationUserForm(request.POST) newEmployee = Employee() newEmployee.name = form[employeeName] newEmployee.email = form[employeeEmail] newEmployee.save() return HttpResponseRedirect(reverse('app:home')) And then I created in forms.py class CreationUserForm(forms.Form): employeeName = forms.CharField(label='employeeName', max_length=254) employeeEmail = forms.CharField(label='employeeEmail', max_length=254) So I don't understand why I get this error : name 'employeeName' is not defined For my point of view it is... I tried with form.employeeName too, but it considered as a non existant attribute. Thank you for helping :) -
Vuetify v-data-table doesn't fully load data: blank rows
I am using example data of Vuetify 1.5.16 documentation: https://v15.vuetifyjs.com/en/components/data-tables The table is shown correctly and I can edit it using props. The only problem is that data is not fully loaded. There is exactly the same number of lines in table as there is objects in array. When I enabled prop "loading", it is all the time true. {% extends 'base.html' %} {% block title %}Page name{% endblock %} {% block custom_style %} <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@1.5/dist/vuetify.min.css" rel="stylesheet"> <!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"> --> {% endblock %} {% block content %} <v-app id="app-name"> <template> <v-data-table dark loading no-data-text :headers="headers" :items="desserts" class="elevation-1"> <template v-slot:items="props"> <td> {{ props.item.name }}</td> <td class="text-xs-right">{{ props.item.calories }}</td> <td class="text-xs-right">{{ props.item.fat }}</td> <td class="text-xs-right">{{ props.item.carbs }}</td> <td class="text-xs-right">{{ props.item.protein }}</td> <td class="text-xs-right">{{ props.item.iron }}</td> </template> </v-data-table> </template> </div> </v-app> {% endblock %} {% block custom_js_back %} <!-- development version, includes helpful console warnings --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vuetify@1.5/dist/vuetify.js"></script> <script> var vueData = new Vue({ delimiters: ["<%", "%>"], el: '#app-name', data: { // example data headers: [ { text: 'Dessert (100g serving)', align: 'left', sortable: false, value: 'name', }, { text: 'Calories', value: 'calories' }, { text: 'Fat (g)', value: 'fat' … -
In Django REST Framework, how to make SerializerMethodField work for html template?
I made a serializer that uses SerializerMethodField that grabs some foreign fields from models other than the base model defined in Meta class, because I would like these fields to be displayed on the html page. However, calling these foreign fields in html doesn't seem to work. The html (character_list.html): {% block content %} <table> {% for character in characters %} <tr> <td><b>{{ character.name }}</b></td> <!-- This can be correctly shown --> <td>{{ character.primary_description_title }}</td> <!-- The foreign field that doesn't show --> <td>{{ character.primary_description_content }}</td> <!-- The foreign field that doesn't show --> </tr> {% endfor %} </table> {% endblock %} urls.py (relevant part only): ... path('description_list/<int:character_id>/', views.CharacterDescriptionListView.as_view(), name='description_list'), ... views.py (relevant part only): # It has a hell bunch of hierarchy, # But tldr, the serializer it would take is CharacterSerializer in this case class NovelCharacterListView(CharacterViewMixin, CustomNovelListCreateView): template_name = 'polls/character_list.html' def get_filter_object(self): return get_object_or_404(Novel, id=self.kwargs['novel_id']) def get_queryset(self): novelObj = self.get_filter_object() return Character.objects.filter(novel=novelObj) # All the relevant superclasses class CharacterViewMixin(object): _model_class = Character _writable_serializer = CharacterSerializer _read_only_serializer = CharacterReadOnlySerializer _data_name_single = 'character' _data_name_plural = 'characters' class CustomNovelListCreateView(CustomNovelListMixin, generics.ListCreateAPIView): class Meta: abstract = True def get_filter_object(self): raise NotImplementedError('Class %s.get_filter_object is not implemented.' % self.__class__.__name__) # def get_serializer_class(self): # return self._writable_serializer … -
Can't get Django settings inside of my view
I'm trying to pull stripe settings from my cookiecutter base.py, and it's not working. I'm not sure if I have not set my view correctly, or what. I'm testing all of this locally, and I have installed stripe via pip and added it to my installed apps (not sure if I needed to do that) here is my urls.py for the payment view path("payment/", TemplateView.as_view(template_name="pages/Payment.html"), name="payment") And here is my views.py class PaymentView(TemplateView): template_name = 'Payment.html' def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context I've got the following in my base.py STRIPE_SECRET_KEY = 'sk_test_xxxx' STRIPE_PUBLISHABLE_KEY = 'pk_test_xxxxx' I feel my issue isn't that I have the keys in the wrong place. I may just have my view class not named correctly. Any help? Thanks! -
How can I send this variable from django view to html using ajax on key up?
I am making and app that send data in realtime to the user in the html and I want to update the paragraph tag every time the users releases a key. My HTML: <form method="POST"> {% csrf_token %} <p id="amount_word" class="amount_word" style="text-align:center">{{ amount_words }}</p> </form> My javascript ('texteditor' is a textarea that I have): $("#texteditor").keyup(function(event){ data = {'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val()}; $.ajax({ type:'POST', url:'/write/', datatype: 'JSON', data: data, success: function(data) { console.log(data) // check out how data is structured $('.amount_word').contents()[0].textContent = data.amount_words } }) }) My python view: def write_view(request, *args, **kwargs): if request.is_ajax() and request.method == "POST": def send_text(): texteditor = request.POST['TextEntered'] amount_words = "Amount of words: " + texteditor print(amount_words) texteditor = request.POST.get('TextEntered') if texteditor == 'NoneType': print("NoneType here") else: send_text() return JsonResponse({'amount_words': amount_words}) return render(request, "write.html") else: return render(request, "write.html") The template is write.html, and the URL is /write -
Django tutorial error: "TypeError at /admin/ - 'set' object is not reversible"
I am going through an official Django tutorial called "Writing your first Django app" and am currently at part 2. Here is the URL: https://docs.djangoproject.com/en/2.2/intro/tutorial02/ When trying to access the admin panel at http://127.0.0.1:8000/admin/, as per the instructions, I receive the following error: Environment: Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 2.2.4 Python Version: 3.7.3 Installed Applications: ['polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 213. if request.path == reverse('admin:logout', current_app=self.name): File "/usr/local/lib/python3.7/site-packages/django/urls/base.py" in reverse 58. app_list = resolver.app_dict[ns] File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in app_dict 512. self._populate() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in _populate 463. url_pattern._populate() File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py" in _populate 446. for url_pattern in reversed(self.url_patterns): Exception Type: TypeError at /admin/ Exception Value: 'set' object is not reversible I am on a Mac with Python 3 installed. I looked up all other similar questions for this … -
How to change text of dropdown button after selecting dropdown item?
I'm having some trouble to getting my javascript to work, I was wondering if anyone could give me some guidance on where I can put the javascript code directly in my html file. Is this the correct way of doing it? This is how it looks right now on my screen. Thank you!! -
How do I retrieve a field from a Many-To-Many table?
I need to retrieve a value from a Many-To-Many query. Let's say I have 3 models: Toy, Part, and ToyParts ToyParts has a field called "part_no". I need to be able to get the value of this. class Toy(models.Model): parts = models.ManyToManyField(Part, through="ToyParts") class Part(models.Model): pass class ToyParts(model.Model): toy = models.ForeignKey(Toy, ...) part = models.ForeignKey(Part, ...) part_no = models.CharField(...) I've tried using: Toy.parts.all().first().part_no which obviously doesn't work as Part does not have a field called "part_no" I've also tried just simply using: ToyParts.objects.filter(toy=...,part=...) but that adds additional queries. How would I be able to get part_no without querying ToyParts directly? -
Django ModelFormSet clicking "Submit" saves form but does not update to database
Background: I'm building a personal dictionary web-application, and have a queryset of terms and definitions. In my web app, I have an edit page, where I want to show a ModelFormSet that allows the user to edit any/all entries, and delete them if needed - the form has a delete button for each row and a submit button to save changes to the form. The current issue is that when I click on a set to edit, the formset shows up correctly, and when I change a term and hit "Submit" the form updates to show the change. However, when I go back to my "View Set" page, the term hasn't been updated, which I assume means the change didn't go through to the actual database - the form itself was simply submitted. This is what I would like to currently fix, and I also want to make it so that the delete button deletes the entry. What I've Tried: I've gone through every StackOverflow question I could find relating to the topic, and various solutions were: add an instance parameter when passing in "request.POST", re-initialize the formset after saving, change the "action" url in the HTML page, etc., but … -
I need my Django get_absolute_url to do two different things
So I have a small issue with one of my models when I want to fire get_absolute_url. When someone create's an article on my site I would like it to return them to the 'under-review' page to tell them that there page is currently under review. But the issue is that my sitemap is showing that every article comes up as www.example.com/under-review/ instead of www.example.com/post/example-slug I would normally use return reverse('post-detail', kwargs={'slug': self.slug}) for that which fixes the problem. But then brings up the issue that when someone creates the article, it takes them straight to the page instead of the under-review page. Model: def get_absolute_url(self): # return reverse('post-detail', kwargs={'slug': self.slug}) return reverse('under-review') Ideally I would have it so when someone posts a post, it takes them to the under-review page up at the same time serves the return reverse('post-detail', kwargs={'slug': self.slug}) so it shows up correctly in my sitemap. Thanks. -
django url pattern problem 'NoReverseMatch'
I have 'url(r'^topics/(?P\d+)/$', views.topic, name='topic')' in urls.py but when I try to go to localhost:8000/topics/1 it tells me that it tried one pattern: 'topics/(?P\d+)/$' I would think it would be '*topics/(?P***d+)/$' I'm using a book called The Python Crash Course (1st edition)(ch. 18). This is a local server using Django 1.11 with Python. I've tried a lot of reformatting on the url pattern but I am new at this so I don't know what else to do. ... urlpatterns = [ url(r'^$', views.index, name='index'), # Show all topics. url(r'^topics/$', views.topics, name='topics'), # Detail page for a single topic. url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), ] I expected it to pop up with the correct page but it always says 'NoReverseMatch at /topics/01/' -
django-rest-framework, passing a foreign key field as url parameter for lookup
I am trying to search for all serial numbers with a specific sales_order(foreign key) field by providing the sales order as a url parameter to its viewset. I'm not sure why my queryset isn't being displayed by a GET request This is a new system I am developing, and as a django newbie I am having some trouble getting everything working the way I'd like it too. Currently, I have configured my routes so that 127.0.0.1:8000/api/serialWSales/ just displays all serial numbers, and I want to have 127.0.0.1:8000/api/serialWSales/(<sales_order>)/ to display only the serial numbers with the sales order number given. I was able to get and print the desired queryset based on the sales_order key, but am having difficulty displaying the queryset with a GET request. I am unsure why the queryset isn't being displayed and the "display: Not Found" exception is being given. Relevant models # Model for Sales table class Sale(models.Model): sales_order = models.CharField(max_length=70, blank=False) model = models.ForeignKey(Model, null=True, on_delete=models.SET_NULL, related_name='sales') quantity = models.IntegerField(blank=False, default=1) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='sales') sale_id = models.IntegerField(default=1, unique=True, primary_key=True) class Meta: unique_together = [['sales_order', 'model']] verbose_name = 'Sale' verbose_name_plural = 'Sales' db_table = 'tbl_sales' def __str__(self): return self.sales_order def save(self, *args, **kwargs): …