Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Empty page when creating data-url to download d3.js graph as svg
I am trying to download a graph that I created with D3.js to a png (any other format would do though), very much unsuccessfully. I am trying to create a data-url and then pass it to a function which should allow me to download it. Like so: First I want to create a function to create data-urls: function svgDataURL(argument) { var svgAsXML = (new XMLSerializer).serializeToString(argument.node()); return "data:image/svg+xml," + encodeURIComponent(svgAsXML); } Next I am saving my url with my svg as argument in a varaiable: var dataURL = svgDataURL(svg) console.log(dataURL) when debugging this outputs the following: data:image/svg+xml,%3Cg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20transform%3D%22translate(100%2C20)%22%3E%3Crect%20class%3D%22bar%22%20width%3D%225.244670050761421%22%20y%3D%22394.44444444444446%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%22526.3857868020305%22%20y%3D%22338.8888888888889%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2257.3502538071066%22%20y%3D%22283.3333333333333%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%22840%22%20y%3D%22227.77777777777777%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%225.116751269035533%22%20y%3D%22172.22222222222223%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2256.96649746192893%22%20y%3D%22116.66666666666666%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2260.079187817258884%22%20y%3D%2261.1111111111111%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2229.932994923857866%22%20y%3D%225.555555555555543%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Crect%20class%3D%22bar%22%20width%3D%2257.3502538071066%22%20y%3D%22172.22222222222223%22%20height%3D%2250%22%20fill%3D%22%23348496%22%2F%3E%3Cg%20transform%3D%22translate(0%2C450)%22%20fill%3D%22none%22%20font-size%3D%2210%22%20font-family%3D%22sans-serif%22%20text-anchor%3D%22middle%22%3E%3Cpath%20class%3D%22domain%22%20stroke%3D%22currentColor%22%20d%3D%22M0.5%2C6V0.5H840.5V6%22%2F%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0.5%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E0%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(85.77918781725889%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E2%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(171.05837563451777%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E4%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(256.33756345177665%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E6%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(341.61675126903555%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E8%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(426.8959390862944%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E10%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(512.1751269035533%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E12%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(597.4543147208122%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E14%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(682.7335025380711%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E16%2C000%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(768.0126903553299%2C0)%22%3E%3Cline%20stroke%3D%22currentColor%22%20y2%3D%226%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20y%3D%229%22%20dy%3D%220.71em%22%3E18%2C000%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3Cg%20fill%3D%22none%22%20font-size%3D%2210%22%20font-family%3D%22sans-serif%22%20text-anchor%3D%22end%22%3E%3Cpath%20class%3D%22domain%22%20stroke%3D%22currentColor%22%20d%3D%22M-6%2C450.5H0.5V0.5H-6%22%2F%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C419.44444444444446)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding1%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C363.8888888888889)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding2%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C308.3333333333333)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding3%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C252.77777777777777)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3ETradeCenter%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C197.22222222222223)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding13%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C141.66666666666666)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding8%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C86.1111111111111)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding7%3C%2Ftext%3E%3C%2Fg%3E%3Cg%20class%3D%22tick%22%20opacity%3D%221%22%20transform%3D%22translate(0%2C30.555555555555543)%22%3E%3Cline%20stroke%3D%22currentColor%22%20x2%3D%22-6%22%2F%3E%3Ctext%20fill%3D%22currentColor%22%20x%3D%22-9%22%20dy%3D%220.32em%22%3EBuilding6%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fg%3E I am assuming that this is the data link to my svg I want to create. But hey, it looks kinda long and wrong. So maybe I am already going the wrong way here. finally I call my download function and pass my URL function download(){ var dl = document.createElement("a"); document.body.appendChild(dl); dl.setAttribute("href", dataURL); dl.setAttribute("download", "graph.svg"); dl.click(); } Ok fail, it doesn't work. When I open the link or click on my download link I get an empty page. Has anyone an idea where I go wrong? Any help is very much appreciated. Here is my graph btw: var data = build // set the … -
Error on running django server: ModuleNotFoundError: No module named 'django_forms_bootstrap'
On trying to run the server for the following project https://github.com/hschafer2017/django-MultiUsers, I get this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_forms_bootstrap' I have installed requirements.txt and also tried: pip install boostrap3 and pip install django-bootstrap-form but the same error occurs. Does anyone have any suggestions as to how I could resolve this problem and run the server without any errors? -
Problem importing the right package with uwsgi and django
I have an error in my django app in deployment using uwsgi. import error ... profile is not a package I have a profile app listed in settings and sys.path.insert(0, project_base('apps/')) where the profile app is located. the profile app has a file init.py in it. the probleme is that localy I dont have this problem only in deployment. I have tried to install uwsgi with pip3 when I searched in python directory I found a profile module, I have a doubt that django is importing this module instead of my package. uwsgi --http :8000 --enable-threads --single-interpreter --disable-logging --socket /tmp/uwsgi.sock --die-on-term --ignore-sigpipe --master --http-keepalive --processes 4 --chdir /opt/app --wsgi-file project/wsgi.py --check-static /opt/public_assets --static-map /static=/opt/public_assets --static-map /favicon.ico=/opt/public_assets/favicon.png --buffer-size 62768 def project_base(f=''): return os.path.join(BASE_DIR, f) sys.path.insert(1, project_base()) sys.path.insert(0, project_base('apps/')) INSTALLED_APPS = [ 'djangocodemirror', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'school', 'profile', 'graphql_core', ..... ]``` ModuleNotFoundError - degree.models in <module> No module named 'profile.models'; 'profile' is not a package -
Return data via Ajax whenever Firestore real time update is fired in Django
Am trying to listen to real-time updates with firestore in three steps: 1) Invoking the listener via Ajax. 2) Listener invokes and executes. 3) The populated list is returned. The problem is: 1) The data is returned when the page is refreshed twice. 2) The listener 'modified' event is fired but data is not returned via ajax. The question is: 1)Why Ajax does not get the data each time Django returns? 2) How can I successfully get the data in Ajax every time Django returns? Here is my code views.py data_list = [] # on_snapshot listener def on_snapshot(col_snapshot, changes, read_time): request = HttpRequest() data_list.clear() try: for change in changes: if change.type.name == 'ADDED': val_list.append(change.document.id) val_list.append(change.document.to_dict()) data_list.append(val_list) elif change.type.name == 'MODIFIED': val_list.append(change.document.id) val_list.append(change.document.to_dict()) data_list.append(val_list) return get_data(request) except Exception as e: return JsonResponse("failed", safe=False) # returns data def get_data(request): return JsonResponse(data_list, safe=False) # invokes listener def invoke_listener(request): if request.method == 'POST': id_token = request.POST.get('idToken') decoded_token = auth.verify_id_token(id_token) uid = decoded_token['uid'] try: col_query = db.collection(u'cities').where(u'state', u'==', u'CA') query_watch = col_query.on_snapshot(on_snapshot) return JsonResponse('invoked successfully', safe=False) except Exception as e: return JsonResponse("failed", safe=False) else: return JsonResponse("failed", safe=False) Javascript file. Ajax code // listener invoked on page load via ajax document.addEventListener('DOMContentLoaded', function(){ firebase.auth().onAuthStateChanged(function(user) { firebase.auth().currentUser.getIdToken(true).then(function(idToken) { … -
How to apply django transaction to every celery task?
from celery.task import Task from django.db import transaction class MyTask(Task): # ... def run(self, *args, **kwargs): # doesn't work with transaction.atomic(): super().run(*args, **kwargs) celery_task = celery_app.task(ignore_result=True, base=MyTask) @celery_task # @transaction.atomic # this should work, but I want to add transaction through base task class def foo_task(): pass I need to add an atomic transaction to every task with celery_task decorator without using additional decorators. -
How to check if requested data exist
I have a problem with data support. I pass in template different names of variables. When I send one variable i've got error: Exception Type: MultiValueDictKeyError. I send to view variables named btn, delete and undo. I've done it in this way try: task = List.objects.get(id=data['undo']) except: try: task = List.objects.get(id=data['delete']) except..... And that is working properly but i've got a challange to do it in better way. But when i deleted my try-except block and pass to view for example only data['undo'] i've got error Exception Value: 'btn' Is there any way to check which variable exists in view and use it? -
ListView filter according to Model
I have a ListView and it works as follow Logged in user creates an Album (The parent class) Adds pictures (children) to the album Pictures show up when that particular Album is selected The ListView But my query is returning an empty value. Please help I don't know where I am going wrong with the query. My deadline is approaching in 2 days. model.py class AlbumData(models.Model): album_user = models.ForeignKey(User, on_delete=models.CASCADE) album_name = models.CharField(max_length=50) class AlbumPictures(models.Model): album_relation = models.ForeignKey(on_delete=models.CASCADE) pic_title = models.CharField(max_length=50) content_pic = models.ImageField(upload_to='Pictures', blank=False, null=False) View.py class AlbumPicturesList(ListView): model = AlbumPictures template_name='userfiles/AlbumPicsList.html' def get_queryset(self, *args, **kwargs): return AlbumPictures.objects.filter(album_relation_id = self.request.GET.get('AlbumData_id')) -
How can i find total number of login in Django application by user?
In Django User table we can check last_login, But i want to check total number of login in month by user. Is that any function where i can use directly in my system. OR Am i need make change on login view, when every-time user will login then i can create entry in Django Model? I want to data like this: Users JunLogin FebLogin Virat 10 30 Sachin 9 11 Please suggest me the best way. Thanks in Advance -
Trying to Post some info to DRF API but being met with 403 forbidden error using Python Requests
I am trying to GET access to my DRF API and I am trying to authenticate against my API but I cannot post my username/password (Data) as I get a 403 HTTP Error before I was getting a Forbidden (CSRF cookie not set.) error then I changed my view to a DRF Class based view now I am stuck on this error unable to POST anything to my API REQUESTS (Outside the Django Project) payload = {'username': 'user', 'password': '****'} r = requests.get('http://website/api/login/', data=payload) urls app_name = 'api' urlpatterns = [ url(r'^login/$', views.login_to_api.as_view(), name = "login_to_api"), Views class CustomerListAPIView(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerRetrieveAPIView(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class login_to_api(APIView): def post(self, request): if request.method == "POST": (logic) HTML <form id="login-form" method="post" action="{% url 'api:login_to_api' %}" > {% csrf_token %} <table class="table"> <tr> <td><label >Username</label></td> <td><input id="username" name="username" type="text" class="form-control"></td> </tr> <tr> <td><label >Password</label></td> <td><input id="password" name="password" type="password" class="form-control"></td> </tr> {%csrf_token%} </table> <input type="submit" value="Login" class="btn btn-primary pull-right" /> settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', #'rest_framework.authentication.SessionAuthentication', )#,'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } 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', ] Any Help would be … -
Save form data into Excell file send as msil
I have formset form with provided input. With click on button, an pop-up opens for user to enter email and after clicking submit, data of formset should mailed to given email Id. Can anyone help me for this. I have read django-import-export. I can send mail using python. I just need way to convert form data into Excell. Thanks in advance. -
ajax url append on current url on document ready and giving 302 error
current href is "http://127.0.0.1:8000/report-page/34" In back it should be /sort-list but it is appending after "/report-page" like "GET /report-page/sort-list HTTP/1.1" 302 0 Actually for some reason on previous request I have send id on url and I need that. $(document).ready(function() { $.ajax({ url: "sort-list", type: "GET", headers: { "X-CSRFToken": $.cookie("csrftoken") }, success: function(response){ } }); }); -
Best Practice for running Machine Learning Model
I am creating a bus arrival prediction app with the following architecture !Web App Architecture I will be pulling current data from weather, event APIs etc, as well as taking user input through react interface to choose a particular bus stop. I would then like to send this information to be run on the trained models I've created. I've previously done similar in a flask app sending the data to the backend using Ajax and then loading the appropriate pickle file with the data and returning the result. I'm wondering is there any better way of doing this, given the proposed architecture. I'm particularly interested in how this might work with the use of Apollo GraphQL. I've read some research on security risks using pickle, as well as options to run the models in the front end using TensorFlowJS. It would be great to generate a discussing here on best practices. Please keep in mind I am new to web development and so the more complete information you can share the better. -
graphql schema field need to return one of defined type
i got this problem. My Collection model consists of a multiple item and content_type. This content_type can be either Artist or Album. So i put my schema like following. Now i want to assign type. I tried union type but no luck. union CollectionItemsType = Album | Artist type Collection { id: ID! title: String! subtitle: String cover: String! thumb: String content_type: String items(first: Int, skip: Int): [CollectionItemsType] } PS: i am using this on Django with Ariadne graphql -
Django: Dots in slug don't work in DetailView
I'm modelling genome assemblies whose names often contain a dot (.) I wrote a DetailView which works for names without dots but noth names with dots. I get this error: 404 - Using the URLconf defined in genomeDBmanager.urls, Django tried these URL patterns, in this order: ... My model: class Assembly(models.Model): ... identifier = models.SlugField('unique identifier', max_length=50, unique=True) ... My view.py: class AssemblyDetailView(DetailView): slug_field = 'identifier' template_name = 'overview/assembly.html' model = Assembly context_object_name = 'assembly' My overview/urls.py: app_name = 'overview' urlpatterns = [ ... path('assembly/<slug:slug>/', views.AssemblyDetailView.as_view(), name='assembly-detail') ] This URL works: 127.0.0.1:8000/strain/SomeAssembly-1, this one doesn't: 127.0.0.1:8000/strain/SomeAssembly.2. -
How to fix URL data retrieval with drf-multiple-model module?
I'm trying to create an API using the drf-multiple-model module but it's creating a problem with the single instance URL, as in http://localhost:8000/categories/partner-spec-categories// is returning no data available. Where could the problem be? I'm running Python 3.6.5, Django 2.2.2, MySQL 8.0.16. As of now im only focusing on the ott.cat.master.viewset, that's why the other routers don't have a base_name. urls.py router = routers.DefaultRouter() router.register(r'general-categories', gen.cat_master_viewset.CatMasterView) router.register(r'gen-cat-settings', gen.cat_settings_viewset.CatSettingsView) router.register(r'partner-spec-catagories', ott.cat_master_viewset.CatMasterView,base_name='partner-spec-catagories') router.register(r'spec-cat-settings', ott.cat_settings_viewset.CatSettingsView) The viewset.py file I'm having problems with class CatMasterView(FlatMultipleModelAPIViewSet,viewsets.ModelViewSet): all_or_none_response = False def partner_id_filter(queryset,request,*args,**kwargs): global all_or_none_response final_queryset = queryset if PartnerMaster.objects.filter(partner_id=request.query_params.get('partner_id')).exists(): partner_to_get = request.query_params.get('partner_id') if partner_to_get == None: all_or_none_response = False else: all_or_none_response = True final_queryset = final_queryset.filter(partner_id=partner_to_get) if OttCategoryMaster.objects.filter(id=request.query_params.get('id')).exists(): id_to_get = request.query_params.get('id') if id_to_get == None: all_or_none_response = False else: all_or_none_response = True final_queryset = final_queryset.filter(id=id_to_get) if OttCategoryMaster.objects.filter(name=request.query_params.get('name')).exists(): name_to_get = request.query_params.get('name') if name_to_get == None: all_or_none_response = False else: all_or_none_response = True final_queryset = final_queryset.filter(name=name_to_get) return final_queryset def all_or_none_response_filter(queryset,request,response=all_or_none_response,*args,**kwargs): if response: pass else: queryset = None if PartnerMaster.objects.filter(partner_id=request.query_params.get('partner_id')).exists(): pass else: queryset = None return queryset querylist = [ {'queryset':OttCategoryMaster.objects.all(), 'serializer_class':ott_cat_master_serializer, 'label':'ott_categories', 'filter_fn':partner_id_filter,}, {'queryset':CategoryMaster.objects.all(), 'serializer_class':gen_cat_master_serializer, 'label':'gen_categories', 'filter_fn':all_or_none_response_filter} ] def get_serializer_class(self): return ott_cat_master_serializer Although filtering .../?id=1 works, using .../1/ doesn't which should essentially return the same thing. -
Retrieving attributes from a one to one related model's foreign key related field
So I have three models which are related to each other in different relations. First, the Parent model, which is related to the student using one to one relation also the student model is related to the attendance model using a foreign key relation. I want to create a serializer where I can retrieve the attendance of each parent's child separately. How can this be done? models.py class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None) child = models.ForeignKey(Student, on_delete=models.CASCADE) email = models.EmailField(null=True) def __str__(self): return self.user.firstName + ' ' + self.user.lastName class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, default=None) batch = models.ForeignKey(Batch, on_delete=models.CASCADE, null=True, related_name='students') age = models.IntegerField(blank=True) @property def remarks(self): return self.remark_set.all() @property def marks(self): return self.marks_set.all() def __str__(self): return self.user.firstName + ' ' + self.user.lastName class Attendance(models.Model): Subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=True) class_date = models.DateField(blank=True, null=True) student = models.ForeignKey(Student, related_name='student_today', on_delete=models.CASCADE, null=True) present = models.NullBooleanField(default=False) def __str__(self): return str(self.class_date) + '_' + str(self.student.user.username) + '_' + str(self.Subject.name) serilaizers.py class BasicUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('firstName', 'lastName') class BasicStudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('batch', 'age') class ParentSerializer(serializers.ModelSerializer): user = BasicUserSerializer(read_only=True, many=False) child = BasicStudentSerializer(read_only=True, many= False) class Meta: model = Parent fields = … -
Django formtools SessionWizardView repopulating form on validation error
I've a django-formtools SessionWizardView wizard which works fine when all data is input. However, I have form validation going on within each step of the form and if a step is represented I cannot get the entered data to redisplay in some instances. Here is a simple example. Required field description isn't entered byt field plan was entered. The validation error is reported and the form redisplayed. I'm creating the plan checkboxes in the template as below. {% for plan in PLANS %} <div class="col-6"> <span class="form-radio form-radio-xl"> <input type="radio" id="id_job-plan_{{plan.id}}" name="job-plan" value="{{ plan.pk }}" required {% if wizard.form.plan.value == plan.pk %}checked{% endif %}> <label for="id_job-plan_{{plan.id}}">{{ plan }} - {{plan.pk}} </label> </span> </div> {% endfor %} I expect {% if wizard.form.plan.value == plan.pk %}checked{% endif %} to be True in one instance and therefore checked. It isn't and I do not understand why not. If I do {{ wizard.form.plan.value }} the displayed result looks the same as {{ plan.pk }} -
How to upload a CSV file to a Django Rest API and how to access it?
I want to know how to upload multiple csv files to django rest api , how to access them and how to export csv files from django rest api. I have installed django-rest-framework-csv.I saw the example provided here is the link to the same link to the example.I installed and did all the migrations. This is the views.py from django.urls import reverse from rest_framework import viewsets, status from rest_framework.decorators import list_route from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework_csv.parsers import CSVParser from rest_framework_csv.renderers import CSVRenderer from example.serializers import TalkSerializer from example.models import Talk class TalkViewSet(viewsets.ModelViewSet): """ API endpoint that allows talks to be viewed or edited. """ queryset = Talk.objects.all() parser_classes = (CSVParser,) + tuple(api_settings.DEFAULT_PARSER_CLASSES) renderer_classes = (CSVRenderer,) + tuple(api_settings.DEFAULT_RENDERER_CLASSES) serializer_class = TalkSerializer def get_renderer_context(self): context = super(TalkViewSet, self).get_renderer_context() context['header'] = ( self.request.GET['fields'].split(',') if 'fields' in self.request.GET else None) return context @list_route(methods=['POST']) def bulk_upload(self, request, *args, **kwargs): """ Try out this view with the following curl command: curl -X POST http://localhost:8000/talks/bulk_upload/ \ -d "speaker,topic,scheduled_at Ana Balica,Testing,2016-11-03T15:15:00+01:00 Aymeric Augustin,Debugging,2016-11-03T16:15:00+01:00" \ -H "Content-type: text/csv" \ -H "Accept: text/csv" """ serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_303_SEE_OTHER, headers={'Location': reverse('talk-list')}) curl -X POST http://localhost:8000/talks/bulk_upload/ \ -d "speaker,topic,scheduled_at Ana Balica,Testing,2016-11-03T15:15:00+01:00 Aymeric … -
Access User’s value in model’s file
I would like to ask if is possible when I have something like this >>> from django.contrib.auth.models import User >>> u = User.objects.get(username='marcel4') >>> d = u.employee.department >>> print(d) >>> 経理部 To be able to access that ‘d’ for all Users in ‘models.py’ file. Because I want to be able to do ‘if’ statement depending on the ‘d’ -
How can I send the image to database with form initialized with model data?
I have my form GoodGet: class GoodGet(forms.ModelForm): class Meta: model = Good_Get Size = forms.ModelChoiceField(queryset = Good.objects.all()) fields = '__all__' widgets = { 'Name': forms.TextInput(attrs = {'type': 'hidden'}), } def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: obj = Good.objects.filter(id = good_id1) for good in obj: good_sizes = good.Size.all() self.fields['Size'].queryset = good_sizes I initialized this form with data from model "Good" in views.py: class Adding(View): def get(self, request, good_id): good = Good.objects.filter(id = good_id) good1 = Good.objects.get(id = good_id) form = GoodGet(initial = {'Photo': good1.Photo, 'Name': good1.Name, 'Price': good1.Price}, good_id1 = good_id) return render(request, 'HiPage/add_to_cart.html', context = {'form': form, 'good': good}) def post(self, request, good_id): good1 = Good.objects.get(id = good_id) form = GoodGet(request.POST, initial = {'Photo': good1.Photo, 'Name': good1.Name, 'Price': good1.Price}, good_id1 = good_id) if form.is_valid(): form.save() return redirect('/cart') good = Good.objects.filter(good_id1 = good_id) return render(request, 'HiPage/add_to_cart.html', context = {'form': form, 'good': good}) CharFields "Name" and "Price" are saved to database, but not ImageField "Photo"... On site I can see that, so initialization works well But when I click "submit" everything is saved except Photo... How can I fix it? Models "Good" and "Good_Get" if u need: class Good(models.Model): Name = models.CharField(max_length = 150) Type … -
How to get all pages details by filtering by cms page type?
I am new to django and I want to get all page details filtering by page type in django-cms. I used below def to display it in a template. def cms_detailed_view(request): all_pages = Title.objects.public().values() context= {'pages': all_pages} return render(request, 'node-detailed.html', context) It gives all pages. But I wants to filter it by page type. I don't know how to use filter method to filter by page type like all_pages = Title.objects.filter(type="pagetype") -
How can I make OR expression with django-filrers DRF?
I use Angular on frontend and django-rest-framework on backend. User want to use customer filter by city and region. One region include few cities. Filter code: class CustomerFilter(filterset.FilterSet): city = filters.ModelMultipleChoiceFilter(queryset=City.objects.all()) region = filters.ModelMultipleChoiceFilter(method='filter_regions', queryset=Region.objects.all()) class Meta: model = Customer fields = ['city'] def filter_regions(self, queryset, name, value): if not value: return queryset return queryset.filter(city__region__in=value) As result I want to see customers from specified cities OR reqions. For example: /api/customers/?city=32&region=10 Return customers who live inside intersection of cities region 10 and city 32, but I need all customers who live inside one of both sets. -
How to update different queryset objects with a ModelForm in Django
I have two models as follows class Professor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) faculty_id = models.IntegerField(primary_key=True) name = models.CharField(blank=True, max_length=50) family_name = models.CharField(blank=True, max_length=50) birth_date = models.DateField(blank=True, null=True) national_id = models.IntegerField(blank=True, null=True) .... And: class Journal(models.Model): professor = models.ForeignKey(Professor, on_delete=models.CASCADE) title = models.CharField(max_length=1000, null=True) title_english = models.CharField(max_length=1000, null=True) magazine_title = models.CharField(max_length=1000, null=True) magazine_title_english = models.CharField(max_length=1000, null=True) ... I have a view which lists all the journals the belong to a professor: def journals_update(request): professor = get_object_or_404(Professor, user__username=request.user) context = {"active_tab": "3-1", "active": "made-3", "journals": Journal.objects.filter(professor=professor)} return render(request, 'journals.html', context=context) I want to be able to change the fields related to different objects that are rendered in the journals.html and save the fields that are changed when the user post it. I have tried things like the following: def post(self, request): queryset = self.get_queryset() form = JournalModelForm(request.POST) if form.is_valid(): data = form.cleaned_data print(data) queryset.update(**data) But I realized queryset.update() updates the fields in with the same value. How can I go about this? I would very much prefer to to it with generic views. -
Uncaught TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': Failing to download an svg (created with D3.js) as png/pdf
I am trying to download a graph that I created with d3.js as an png (Any datatyp would do though), but I am failing gloriously. I followed various questions on Stackoverflow which address similar issues, but still can't get it to work. With different solutions I very often run into this error when debugging: Uncaught TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'. This is my code for my svg-graph: var data = build // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 100}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; // set the ranges var y = d3.scaleBand() .range([height, 0]) .padding(0.1); var x = d3.scaleLinear() .range([0, width]); // append the svg object to the body of the page // append a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select(".svg-net-area").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // format the data data.forEach(function(d) { d.buildings__net_leased_area = +d.buildings__net_leased_area; }); // Scale the range … -
Django: settings.DATABASES is improperly configured
I know I am not the first person to ask this question, but I still couldn't find an answer for my situation. I have a Django environment that works very well, I know I only have one (1) settings.py file and I know that my environment accesses it correctly. I recently added a new endpoint to my project. I defined its URL in urls.py urlpatterns = [ ... url(PREFIX + r"^v1/alerts/debug$", alerts_views_v1.debug_trigger_alert_notification), ... ] It is connected to a method that is in a the file alerts/views_v1.py but is not in any particular class: @api_view(["POST"]) def debug_trigger_alert_notification(request): """ Trigger an Alert. i.e. Create an Alertnotification. This function is meant to be called by the scheduler service. """ workspace_slug = request.data.pop("workspace") with in_database(workspace_slug, write=True): serializer = AlertNotificationSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() return Response() When I send a request to this URL, I receive the following 500 error: ImproperlyConfigured at /v1/alerts/debug settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. In my settings.py file, my DATABASES variable seems correct (though it is built in a roundabout way): DEFAULT_DATABASES = { "default": { # This DB is supposed to always have the latest version of the schema described …