Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Building web dashboards using django
I want to build a web page that should contain some charts(bar, line, pie,etc.).I know the basics of Django. (i.e) how to create an app, model and other kinds of stuff. I have gone through Charts.js, fusion charts on google. But I cannot figure out how to build a dashboard with my data in MySQL database. Is it possible to create web dashboards using the data from the database (and also from excel files)? If so please guide me. Thanks -
Adding BooleanField to django model ,this field for existing items should be True, for new items it should be False
I am trying to add a setting checkbox to a Django model, for this reason, I am adding BooleanField to one of the existing django models, this boolean field should be True for all the existing rows in the database, However, the field should be False for new rows created. class FlagSetting(models.Model): name = models.CharField(max_length=10) flag = models.BooleanField(default=False)# by setting default to 'False' disabled the flag for the existing entries as well Any help with this is appreciated. Anything to do with overriding the save() method? -
How to create class based serializer and get data of two tables without foreign key?
The tables and its columns. cart_number same with both the tables. I have to filter on the basis of order_status and my rest API should contain above. If there are multiple items on the same cart_number it should show all the items in the inside of the cart on the above api. Orders order_id cart_number customer_name Cart id cart_number cart_item order status Requered output { order_id: "somevalue" cart_number: "somevalue" customer_name: "somevalue" cart{ id: "somevalue" cart_number: "somevalue" cart_items: "somevalue" order status: "somevalue" } } -
403 - Forbidden with Apache and Django on Windows with mod_wsgi
I have looked through numerous tutorials and posts related to Apache and Django on Windows to try to solve my issue. I can run the Django project via the development server and know that my Apache install is working. I know that my issue resides in the configuration of Apache to get it to work with Django. My configuration is shown below. I have made sure that the server project folder is accessible to Everyone with read and execute permissions. I have tried setting the paths with the "C:" and without. Setting the server's filesystem directory access to "Require all granted" (not recommended) does not help. What am I missing? Django settings.py ALLOWED_HOSTS = ['*'] WSGI_APPLICATION = 'INDmain.wsgi.application' STATIC_ROOT = os.path.join(BASE_DIR, "static/") httdp.conf Include conf/extra/httpd-vhosts.conf # "#" is removed from start of line. LoadFile "c:/users/user/appdata/local/programs/python/python36/python36.dll" LoadModule wsgi_module "c:/users/user/appdata/local/programs/python/python36/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIPythonHome "c:/users/user/appdata/local/programs/python/python36" WSGIScriptAlias / "C:/INDmain/main/wsgi.py WSGIPythonPath "C:/INDmain" <Directory "C:/INDmain/main"> <Files wsgi.py> Require all granted </Files> </Directory> httpd-vhosts.conf <VirtualHost *:80> ServerName localhost ServerAlias localhost Alias "/" "C:/INDmain/main" <Directory "C:/INDmain/main"> Require all granted </Directory> Alias "/static" "C:/INDmain/static" <Directory "C:/INDmain/static"> Require all granted </Directory> </VirtualHost> -
nester for loop in django template not working
I have a JSON rendered to the template page from json. The template looks like. the Json is named by no_of_line {'teamcenter_author': {'02/02/2019 11:50': {'server1': {'count': 1}}, '02/02/2019 11:55': {'server1': {'count': 1}}, '02/02/2019 12:00': {'server1': {'count': 1}}, '02/02/2019 12:05': {'server1': {'count': 1}}} i am using following forloop to access the count under each server of the each date. {% for timestamp in no_of_line.teamcenter_author %} {% for server in no_of_line.teamcenter_author.timestamp %} {{server.count}} {% endfor %} {% endfor %} But i get a blank output -
Extending django form with fields not in model, results in error that only lists can be concatenated, not tuples
I am completing an eCommerce application, and the final stage is implementing the order form and processing payments with stripe. I want to show one form to the user where they can input their customer details, as well as card details (card number, expiry dates and cvv) that will be sent to stripe, but will not be stored locally. Hence, there are no fields relevant to storing card numbers in the model I am using for my form. In looking for an answer to my query, I came across this question and answer, which seems to be the solution. However, when I attempt to extend my form in the same way, I get an error: fields = OrderForm.Meta.fields + ('card_num', 'exp_month', 'exp_year', 'cvc') TypeError: can only concatenate list (not "tuple") to list From what I can see, I am doing the exact same thing as proposed in the answer to that question, so I am unsure why I am getting this error. My forms.py that I am extending: class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'email', 'address', 'zipcode', 'city', 'state'] And my attempt to extend the form in my views.py: class OrderPayForm(OrderForm): card_num = forms.CharField(max_length=16) exp_month … -
django: how to prohibit DB access in a function
Context: our project has DRF serializers spanning ForeignKey relationships. So when I get a ListView of my objects I get an extra DB hit for every object, i.e. a list of 100 items gets me 100 extra DB queries. Not good. To fix this, I use select_related/prefetch_related in my views to do the necessary joins before serializing. Problem: It is hard to keep up with all the select_relateds in the views, especially when different developers work on the same features and serializers. So I was wondering if there is a way to prohibit access to DB in a function (be it view or serializer method etc). The first idea was to wrap it in a decorator that counts connection.queries but this counter is always empty in production (when DEBUG=False). So is there another way to count db queries when DEBUG is False? -
Django Form template not getting authenicated user name as post author
I am building a Django blog but created a template to post once a user signed. and the template working fine except an issue and that is, the post template show multiple author name, in this case, an authenticated user can post using any other user name. THe views.py below def create(request): if request.user.is_authenticated: form = CreateForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return redirect('index') return render(request, 'create.html', {'form': form}) else: redirect('user_login') And this Form.py file below class CreateForm(forms.ModelForm): class Meta: model = Article fields = [ 'author', 'title', 'body', 'image', 'category' ] I need only authenticated user name will be author name. Can anyone please fix me this issue? -
Why Django can't find the right templates
I try to learn Django CRUD from this tutorial: https://www.javatpoint.com/django-crud-example My Django version is 2.1.7 and my IDE is VisualStudio. When I run the project all the pages have an error. the error cames bellow. TemplateDoesNotExist at /index show.html Request Method: GET Request URL: http://localhost:52322/index Django Version: 2.1.7 Exception Type: TemplateDoesNotExist Exception Value: show.html Exception Location: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: E:\Django_Try\DjangoWebProject5\DjangoWebProject5\env\Scripts\python.exe Python Version: 3.6.6 Python Path: ['E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5', '', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\Scripts\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_64', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env', 'E:\\Django_Try\\DjangoWebProject5\\DjangoWebProject5\\env\\lib\\site-packages'] Server time: Tue, 5 Mar 2019 22:43:24 +0000 I added my Urls bellow: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from employee import views urlpatterns = [ path('index', views.show), path('admin/', admin.site.urls), path('emp', views.emp), path('show',views.show), path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), path('delete/<int:id>', views.destroy), ] View: from django.shortcuts import render, redirect from employee.forms import EmployeeForm from employee.models import Employee # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.all() return render(request,"show.html",{'employees':employees}) def edit(request, id): employee = Employee.objects.get(id=id) return render(request,'edit.html', {'employee':employee}) def update(request, id): employee = … -
Django - When [and why] use Vue.js?
I've developed with my team a large application that uses the classic django MVT lifecycle. The templates, are implemented with the classic Bootstrap + JQuery stack, using AJAX requests and so on... Everything works fine and it's quite easy to maintain. Today, i've had a briefing with my collegue, he saw the web-application templates and he told that: "Using the classic Django Template it's discouraged and it represent a big effort to maintain in some big projects..." Additionally, he gave me the advice to use Vue.JS for the templating...i've seen some examples and tutorial about Vue.JS...i've found that this templating framework it's quite complex and unuseful for my use case (The most complex templates builds a bunch of graphs and widgets) In conclusion, i'm a bit confused when and why a Django project needs to be scaled using a template framework or not. I suppose (...maybe wrong...) that this templating frameworks represents a temporary fashion way to achieve the same results... What is your idea on top of these considerations? -
Running migrations for a new added field which overrides save
I have been running a clinic management software where till now, I was having a patient registered by entering his details including age in years and months. This was stored in two IntegerFields. However I realized that next year if the same patient visits, his age would still be shown as the same. Hence I needed to create an approximate date of birth (I dont insist on patients giving their date of birth while registering.) So I implemented a function which would calculate approximate date of birth from current age. I overrode the save method so that if a patient didnt enter date of birth, a caculated date would be inserted in the database. My problem is creating this for existing customers. Once I updated my model with the new DateField, and the save method, on attempting to run makemigrations, I'm prompted to enter a default value, and I don't know how to make makemigrations use my function to update the records of existing patients. Do I just set the field to blank and null true, and then run a custom method to check if the field is blank, and update the field's data? Or can I make the makemigrations … -
How I can check in test if response get view with or without form?
Like in title, I don't know how I can test if in response is view with or without form because in my view user getting form only if request.user.is_authenticated. views.py def product_detail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug,) comments = product.comments.all() if request.user.is_authenticated: if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.product = product new_comment.nick = get_object_or_404(User, id=str(request.user.id)) form.save() return redirect('product_detail', id=product.id, slug=product.slug) else: form = CommentForm() return render(request, 'shop/product/Product_detail.html', {'product': product, 'form': form, 'comments': comments}) else: return render(request, 'shop/product/Product_detail.html', {'product': product, 'comments': comments}) I have view test to check if view loads but both authenticated and not authenticated users have acces to this view only difference is that not authenticated users are getting view without form and i dont know how to test this. test_views.py def test_call_view_loads(self): product = Product.objects.get(id=1) response = self.client.get(f'/shop/{product.id}/{product.slug}/') self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'shop/product/Product_detail.html') -
django download file link
Can someone help me. I have FileField for upload files like .doc or .pdf from admin panel. I can upload file like admin but I can't download this file like user. Download link don't work: models.py class Book(models.Model): """Model representing a book (but not a specific copy of a book).""" title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text="Введите краткое содержание книги") genre = models.ManyToManyField(Genre, help_text="Выберите жанр книги") language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True) specifications = models.FileField(upload_to='router_specifications') book_detail.html <p><strong>Download:</strong><a href="{{ book.specifications.url }}">Download</a></p> -
Django exclude a single url from adding slash
I've added 2 views to my Django urls config for SEO but when I view them on my site it redirects them to the url I setup but with an added slash. I know Django likes to tidy up URLs with a slash (and I like this) but is there a way to exclude a single url or a few urls from this feature? ... url(r'^robots\.txt/$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), url(r'^sitemap\.xml/$', TemplateView.as_view(template_name='sitemap.xml', content_type='text/xml')), ... These append slash to the urls resulting in robots.txt/ and sitemap.xml/ not robots.txt and sitemap.xml -
Why Django demands to set default fot MultiPolygonField?
when I try to makemigrate models with Geometry fields to postgres DB example of class with geometry: class ForestryKeys(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField(blank=True, null=True), geom = models.MultiPolygonField(verbose_name='geo',srid = 4326) class Meta: managed = True verbose_name = 'geo' verbose_name_plural = 'geos' class DistrForestKeys(models.Model): id = models.IntegerField(primary_key=True) df_names = models.TextField(blank=True, null=True) geom = models.MultiPolygonField(verbose_name='polygs',srid = 4326) forestry_id = models.ForeignKey(ForestryKeys, models.DO_NOTHING, blank=True, null=True) class Meta: managed = True verbose_name = 'ULV' verbose_name_plural = 'ULVs' etc. I face with next message: You are trying to change the nullable field 'geom' on allotment to non-nullable without a default; we can't do that (the database needs something to populate existing rows). Why I have to set default value? and how it do correct for multipolygon? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello
http://127.0.0.1:8000/hello ERROR: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/hello Using the URLconf defined in kalani.urls, Django tried these URL patterns, in this order: ^admin/ The current path, hello, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page testapp/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello(request): return HttpResponse('<h1>Hello world</h1>') kalani/urls.py from django.conf.urls import url from django.contrib import admin from testapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/', views.hello) ] kalani/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testapp' ] Django version=1.11 python version=3.6.5 kalani is project folder testapp is application folder please help with this code. i think my problem is in urls.py any help would be greatly appreciated -
How can i make category view to list out all the post with related category in django using class based view
I want to know how to make category page view using class based view I know how to make this in function based view by using get_object_or_404(category, slug=None) But i am confused how to do this it in class based i tried to google this But i am unable to find anything related to this in class view. I know I could have used function based view but i have used class based view in whole project so i thought to make this too. anyone help me to do this. my code models.py from django.db import models from django.utils import timezone from slugger import AutoSlugField from django.contrib.auth.models import User from django.urls import reverse # Create your models here. def upload_location(instance, filename): return "%s/%s" %(instance.slug, filename) class Category(models.Model): title = models.CharField(max_length= 60) slug = AutoSlugField(populate_from='title') parent = models.ForeignKey('self',blank=True, null=True ,related_name='children',on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) class Meta: verbose_name_plural = 'categories' def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self, slug=None): return reverse("posts-detail", kwargs={"slug": self.slug}) class Post(models.Model): title = models.CharField(max_length=120) slug = AutoSlugField(populate_from='title') image = models.ImageField( upload_to=upload_location, null=True, blank=True, ) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='postcategory') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering … -
DELETE request running twice
I'm running a site with Django and I only have access to the backend. When I delete an item through the web interface (an alert) the DELETE request is run twice: /alerts/[alert_id] Request Method: DELETE Status Code: 301 Moved Permanently then /alerts/[alert_id]/ Request Method: DELETE Status Code: 204 No Content Any thoughts as to where the issue could be or why it does this? Apparently the frontend only calls the request that ends with a slash (the second one) -
How to add download path in youtube-dl in django project
i am try to create a youtube to mp3 project in this project i am use this code html page : <form method="POST" action="/download/"> <input placeholder="Please Enter Url" name="yturl" /> <button type="submit" >Download</button> </form> this is my view for download mp3 song : def download(request): url = request.POST.get('yturl') ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) this view code is perfectly run but how i add usetr download folder path for download this song this view code is download song in my project how can i download and save this file in user download folder please tell -
How can i pass username and password in django to mysql database
1)I am working on a Django Full stack development project, while working i have created login and signup page. 2)I want the data stored or taken after signup should goto my mysql database and authenticate the same while login process. 3)We have django inbuilt login methods which is not required as per my requirement. 4)Signup parameters are username and Phone. 5)I am using xampp server here. Could someone help me on this -
reading a variable outside the function
I am trying reading an in memory file like this sttr=request.FILES['file_field'].read() now I want sttr to run unless the website is closed or for a specific time . I can't make it global coz it arise in a situation of data breach I don't want to store it in a database just read it and store it in a variable and pass that variable to another function in views.py and I can't use sessions coz I don't have specific key for session[key]. is there any other way to either fetch data from inmemory file from another views.py for example def mainpage(request): sttr=request.FILES['file_field'].read() def hh(request): print(sttr) without making sttr global -
Django User Model Require First and Last Names
I know there are many related questions on SO concerning the extension of the user model. In my case, I'm using django-allauth with a CustomUser model which inherits from AbstractUser. I would like to use all the functionality of the built in User model, since everything works well enough. I simply want to make the first_name and last_name fields required by overriding the existing blank = True on these model fields. Some suggestions I've seen include ignoring the built in fields and just use new ones in my custom model. That seems counter to the Python and Django way. My goal was to do this at DB/model level since that would cascade the validation through the existing forms. Is there a way to override blank=True for these two model fields? -
Django - Passing md5 hex encoded string to form
I am trying to integrate a payment gateway to my django site which uses hex-encoded strings (like \xe5\xf4\x94[\xd4) as form data input. For Flask, they have something along the line of - from string import Template ... html = '''\ <html> <head> <title>checkout page</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> </head> <body> <form id="xxx" method="post" name="redirect" action="<gateway_url>" > <input type="hidden" id="encRequest" name="encRequest" value=$encReq> <input type="hidden" name="access_code" id="access_code" value=$xscode> <script language='javascript'>document.redirect.submit();</script> </form> </body> </html> ''' fin = Template(html).safe_substitute(encReq=encryption,xscode=accessCode) return fin So my question is simple, what will be the equivalent in django? I tried passing the encrypted string as context variable to a similar template but it gives DjangoUnicodeDecodeError. Then I used the |safe filter but then the string became empty. -
Associate existing/created file with django model (without renaming the file) FileField
I've looked around a bit and have found solutions - but my case is slightly different. I'm created a calendar file (.ics) and it works fine. The .ics file is created, is valid and works wonderfully. When I try to save it to the django model - django creates a duplicate of the file with a random string appended to the end of the file name. In doing that - it changes the line endings inside the file, which makes the .ics file no longer valid based on RFC 5545. My model looks like this: class CourseDetail(models.Model): SESSIONS = ( ('AM', 'AM'), ('PM', 'PM'), ('AM/PM', 'AM/PM'), ) course = models.ForeignKey(Course, on_delete=models.PROTECT) location = models.ForeignKey(Location, on_delete=models.PROTECT) session = models.CharField(max_length=5, choices=SESSIONS) seat_count = models.IntegerField() limit_registrations = models.BooleanField(default=False) ics_file = models.FileField( upload_to='registrations/uploads/calendars/', validators=[FileExtensionValidator(['ics'])], null=True, blank=True ) The bit I have where I create the file and associate with the model is here: ...created calendar and added events... filename = f'{course_detail.session}-{location}-{course}.ics' # e.g. AM-location1-fishing.ics db_course_detail = CourseDetail.objects.get(id=course_detail.id) calendar = open( os.path.join( 'registrations/uploads/calendars/', filename ), 'a+b' ) # here we save the file to the model - where it gets renamed by django db_course_detail.ics_file.save(filename, File(calendar)) db_course_detail.save() # finish writing out and closing the file calendar.write(c.to_ical()) … -
celery Bad magic number in docker
I can run the celery beat normally using the command in the terminal, but when I go to run with docker I get the following error: [2019-03-11 11:46:27,327: INFO/MainProcess] beat: Starting... celery_beat_taxithe | [2019-03-11 11:46:27,489: ERROR/MainProcess] Removing corrupted schedule file 'celerybeat-schedule': error('Bad magic number',) celery_beat_taxithe | Traceback (most recent call last): celery_beat_taxithe | File "/usr/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ celery_beat_taxithe | return obj.__dict__[self.__name__] celery_beat_taxithe | KeyError: 'scheduler' celery_beat_taxithe | celery_beat_taxithe | During handling of the above exception, another exception occurred: celery_beat_taxithe | celery_beat_taxithe | Traceback (most recent call last): celery_beat_taxithe | File "/usr/local/lib/python3.6/site-packages/celery/beat.py", line 476, in setup_schedule celery_beat_taxithe | self._store = self._open_schedule() celery_beat_taxithe | File "/usr/local/lib/python3.6/site-packages/celery/beat.py", line 466, in _open_schedule celery_beat_taxithe | return self.persistence.open(self.schedule_filename, writeback=True) celery_beat_taxithe | File "/usr/local/lib/python3.6/shelve.py", line 243, in open celery_beat_taxithe | return DbfilenameShelf(filename, flag, protocol, writeback) celery_beat_taxithe | File "/usr/local/lib/python3.6/shelve.py", line 227, in __init__ celery_beat_taxithe | Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) celery_beat_taxithe | File "/usr/local/lib/python3.6/dbm/__init__.py", line 94, in open celery_beat_taxithe | return mod.open(file, flag, mode) celery_beat_taxithe | _gdbm.error: Bad magic number My settings of celery is: CELERY_BEAT_SCHEDULE = { 'driver_monitor_update_latlng': { 'task': 'api.tasks.driver.turn_offline_driver', 'schedule': 30.0 # a cada 30 seconds } }