Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there any plugin for implement drag and drop image upload?
I wish to implement image upload using drag and drop, may somebody already implemented it. $echo -
Can't load second Highcharts diagram from my Django View
Can't seem the load my second chart diagram on my another carousel page. I'm doing it via response/request from views.py. I was able to display my first diagram but not the second. No errors were displayed when loaded Looked at "How to integrate Django and Highcharts" doc but i don't know how to implement two charts on one page class dashboard_view(View): template_name = 'accounts/dashboard.html' def get(self, request, *args, **kwargs): dataset = Profile.objects \ .values('is_active') \ .annotate(is_active_count=Count('is_active', filter=Q(is_active=True)), not_is_active_count=Count('is_active', filter=Q(is_active=False))) \ .order_by('is_active') categories = list() is_active_series_data = list() not_is_active_series_data = list() for entry in dataset: categories.append('%s Active' % entry['is_active']) is_active_series_data.append(entry['is_active_count']) not_is_active_series_data.append(entry['not_is_active_count']) is_active_series = { 'name': 'Active user', 'data': is_active_series_data, 'color': 'green' } not_is_active_series = { 'name': 'Inactive user', 'data': not_is_active_series_data, 'color': 'red' } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Active user on Current Platform'}, 'xAxis': {'categories': categories}, 'yAxis': { 'title': { 'text': 'No.of users'}, 'tickInterval': 1 }, 'plotOptions': { 'column': { 'pointPadding': 0.2, 'borderWidth': 0 } }, 'series': [is_active_series, not_is_active_series] } dump = json.dumps(chart) return render(request, self.template_name, {'chart': dump}) def post(self, request, *args, **kwargs): dataset = Department.objects \ .values('department') \ .annotate(IT_count=Count('department', filter=Q(department="IT")), Sales_count=Count('department', filter=Q(department="Sales")), Admin_count=Count('department', filter=Q(department="Admin")), HR_count=Count('department', filter=Q(department="HR"))) \ .order_by('department') categories = list() IT_series_data = list() Sales_series_data = list() … -
Django how to implement pagination if I have data only for a page and total pages num
In my app I have data only for current page and total pages num. I can request data from any page but only for one. How to implement Django pagination in that case? -
Django : IndexError: list index out of range
Getting exception : IndexError django.db.models.sql.compiler in apply_converters IndexError: list index out of range in djagno queryset I am doing this object =Info.objects.get(is_active=False,device_id=device_id) here device_id is long text type in database schema and it is indexed object =Info.objects.get(is_active=False,device_id=device_id) -
My download function saves a file with fixed name
I'm using Django 1.8 with Python 3.6. When I use my download function below, it saves the file with a name fixed to local download directory. But I really want to keep the original name. I can change the browser to open a download manager, but I want to know how to fix this filename to the original one. def download(request): path = "test.jpg" # Original filename that I intend to give. file_path = os.path.join(settings.MEDIA_ROOT,path) print("file_path :", file_path) if os.path.exists(file_path): readFile = open(file_path,"rb") response = HttpResponse(readFile.read()) response['Content-Disposition'] ='attachment; filename'+os.path.basename(file_path) response['Content-type'] = 'image/jpg' return response When I download the file, it is autosaved with a name 'Download.jpg', which is the browser's default directory name. -
Reverse for 'add-subject' with arguments '('',)' not found. 1 pattern(s) tried: ['result\\/add\\-subject$']
i try to show book list of a register class, but i found error. views.py files def subject_list(request): form = ClassSelectForm(request.GET or None) select_class = request.GET.get('select_class', None) if select_class: cls = ClassRegistration.objects.get(id=select_class) subjects = SubjectRegistration.objects.filter(select_class=cls) print('subjects=', subjects) context = {'subjects': subjects} return render(request, 'result/subject-list.html', context) context = {'form': form} return render(request, 'result/subject-list.html', context) models.py files class SubjectRegistration(models.Model): select_class = models.ForeignKey(ClassRegistration, on_delete=models.CASCADE, null=True) subject_name = models.CharField(max_length=45) subject_code = models.IntegerField(unique=True) marks = models.IntegerField() pass_mark = models.IntegerField() add_date = models.DateField(auto_now_add=True) def __str__(self): return self.subject_name -
Django-m2m-using through filter only existing objects
I have two model, Route, Point. between these models I have many-to-many relationship and also for sequencing points on route, I have also another model RoutePointSequence then I could have a m2m with "through". I want restricte this "through" available items to that points, which already exists on a route Second question: Also I need to describe some information about a single part of a route between two point, e.g. distance-btn-points; I made another model for that, but any chance to mix these two "trough" models? -
How to migrate existing django database model(SQLite3) to MYSQL?
How can I migrate my existing database data from default django db - SQLite3 to MYSQL. I'm currently using SQLyog and I want to display all my current data in it. I tried following this solution from What's the best way to migrate a Django DB from SQLite to MySQL?: 1) python manage.py dumpdata > datadump.json 2) Change settings.py to your mysql 3) Make sure you can connect on your mysql (permissions,etc) 4) python manage.py migrate --run-syncdb 5) Exclude contentype data with this snippet in shell python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() 6) python manage.py loaddata datadump.json ....but this doesnt seem to work. Any suggestions? Im getting this error as well: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") -
Docker/Python/Django astimezone seems to be using DST from past year
I'm converting UTC datetimes to America/Santiago tz using dt.astimezone(my_tz) through a Django manage.py command, but it seems to be using DST from past year. This code shows that DST changes at 12/08/2019, from -4 to -3, but this year this should be happening at 08/09/2019 (https://www.timeanddate.com/time/zone/chile/santiago) import pytz import datetime tz = pytz.timezone("America/Santiago") dt4offset = datetime.datetime.strptime(''.join('2019-08- 10T10:00:00+00:00'.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z') dt3offset = datetime.datetime.strptime(''.join('2019-08- 12T10:00:00+00:00'.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z') now = datetime.datetime.now() print('Now %s' % now) print('UTC: %s -> America/Santiago: %s' % (dt4offset, dt4offset.astimezone(tz))) print('UTC: %s -> America/Santiago: %s' % (dt3offset, dt3offset.astimezone(tz))) It prints: Now 2019-08-08 05:46:27.102422 UTC: 2019-08-10 10:00:00+00:00 -> America/Santiago: 2019-08-10 06:00:00-04:00 UTC: 2019-08-12 10:00:00+00:00 -> America/Santiago: 2019-08-12 07:00:00-03:00 Both of the tz convertions should have an offset of -4, but the second one changes acoording to the DST from 2018. I've coded this in Repl.it and it works as its supposed to: https://repl.it/@alejandrocarrasco/LightcyanHideousFlatassembler I'm running this script from docker-compose exec command. I thought my docker container was outdated but it is ok: docker-compose exec container date Prints 'Thu Aug 8 05:52:25 UTC 2019' (and now() from the code above is also ok). So, I think there is a problem with my server/django config. Both Ubuntu and Docker container have correct dates. … -
How to display username at login link in navbar after user has logged in
I want the login link in navbar to change and display the username of the logged user, Please help how would I achieve that views.py def login_request(request): if request.method == "POST": user_form = AuthenticationForm(request, data=request.POST) if user_form.is_valid(): username = user_form.cleaned_data.get("username") password = user_form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("loststuffapp:IndexView") else: messages.error(request, "Invalid username or password") user_form = AuthenticationForm() return render(request, "loststuffapp/login.html", {"user_form":user_form} ) login.html {% extends "loststuffapp/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{user_form.as_p}} <p><button class="btn" type="submit" >Login</button></p> <p>If you don't have an account, <a href="/register <strong>register</strong></a> instead</p> {% endblock %} -
Error with "input file" in Django. Does not recognize the file
I have problems working with django images, when selecting an image in the django manager everything works correctly, but when creating my own form it does not work. That is, filling the entire form correctly, selecting the file normally, at the time of submitting the form, does not send it and deselects the file you select, and tells me that said field is required. It makes no sense, I select the image, send the form and tell me that the field is required, and the image I chose is deselected. Here my model: class Course(models.Model): instructor = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 200) image = models.ImageField(upload_to = 'course') description = models.TextField() users = models.ManyToManyField(User, related_name = 'get_users') created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['title', 'created'] Here my view: class CourseCreateView(CreateView): model = Course fields = '__all__' template_name = 'courses/course_form.html' success_url = reverse_lazy('home') More explicit example of the problem: Fill in the form correctly: I click on the "Crear"/Create button, and the following happens: It tells me that the field is required and appears in the "I don't choose the file" input, what is happening? -
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 :)