Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PySpark as a runtime for Django instead of a regular python env?
Is it possible to use PySpark as a runtime for Django instead of a regular python environment? Since Django is just running Python tasks, could these tasks not be parallelized in Spark? Here in python3 manage.py shell_plus --notebook, I have imported pyspark and ran a query using the ORM. It runs clean. import findspark findspark.init() import pyspark import pyspark.sql sc = pyspark.SparkContext(appName="Django") patients = Patient.nodes.all() print(patients) sc.stop() [1]: #returned the data from my model I suppose this would work for Flask and Pyramid too? -
How to re-render a view in Django with an updated context from listener or callback function?
I've been trying hard to find a solution to this problem. My Django project uses Firebase Admin SDK. Everything works fine but I have a page view which has this piece of code in it def my_view(request): def on_snapshot(doc_snapshot, changes, read_time): print('Data changed!') return render(request, 'xxxxx.html', context) # 'db' is the Firestore object initialized using firebase admin SDK doc_ref = db.document(....) res = doc_ref.get().to_dict() doc_ref.on_snapshot(on_snapshot) context = { 'result': res, ......... ......... } return render(request, 'xxxxx.html', context) The problem is it works fine when the view is first loaded but when the data in the location of doc_ref is changed from the web browser in the Firebase console, the listener function on_snapshot gets called and the message Data changed! gets printed in the console but the return render(.....) never gets triggered. I don't know why this is not working, I've searched online for solutions, many of them are suggesting to use ajax. If the event is triggered by the user in the front-end then ajax is helpful, but in my case, the event is triggered by the listener function. Please help me to get through this. What I want to have realtime updates on my front-end. But this is not … -
django FloatField - how do I retrieve the value
I have a model made like this class SnpsPfm(models.Model): snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True) # Field name made lowercase. pfmid = models.ForeignKey(Pfm, models.DO_NOTHING, db_column='PFMID') # Field name made lowercase. start = models.PositiveIntegerField() strand = models.PositiveIntegerField() type = models.CharField(max_length=8) scoreref = models.FloatField(db_column='scoreRef', blank=True, null=True) # Field name made lowercase. scorealt = models.FloatField(db_column='scoreALT', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'SNPs_PFM' unique_together = (('snpid', 'pfmid', 'start', 'strand'),) def __str__(self): return str(self.snpid + self.pfmid + self.start + self.strand) And i need to do this operation a = SnpsPfm.objects.filter(snpid=qset[0]) score = a[k].scorealt - a[k].scoreref Problem is that it won't let me do that giving me could not convert string to float: 'ARNTL.SwissRegulon I tried to cast them as float but it's obviously not the solution. I even tried to add def __float__(self): return float(self.scoreref) to SnpsPfm but still won't work -
How to route with django and react
I am using django and react together but I dont know how to handle the routing. from . import views from django.conf import settings urlpatterns = [ path('',views.index), ] That is my urls.py when it loads the html, good and fine it does that well but when I refresh my page in another url (which is in react app) it throws a 404, I want to this in a way that I will still have my static assets and admin accessible from django. -
Deploying Django using Nginx Docker Container
Situation: I have a Django Application that I want to deploy, the tools I use for this one are Nginx, Gunicorn, and all of them are inside a docker container Problem: I'm able to view the django app locally using the IP of my docker, IP of my machine, and Loopback IP. However when I try to access it from my laptop, I can't access it. My Machine: Windows 10, I have already enable the expose of port 80 in the windows firewall inbound and outbound. My docker-compose file version: '3' services: dashboard: build: . volumes: - .:/opt/services/dashboard/src - static_volume:/opt/services/dashboard/src/static networks: # <-- here - nginx_network nginx: image: nginx:1.13 ports: - 0.0.0.0:80:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/dashboard/src/static depends_on: - dashboard networks: # <-- here - nginx_network networks: # <-- and here nginx_network: driver: bridge volumes: static_volume: # <-- declare the static volume My dockerfile # start from an official image FROM python:3.6 # arbitrary location choice: you can change the directory RUN mkdir -p /opt/services/dashboard/src WORKDIR /opt/services/dashboard/src # install our two dependencies RUN pip install gunicorn django requests jira python-dateutil # copy our project code COPY . /opt/services/dashboard/src # # expose the port 80 # EXPOSE 80 # define the … -
Getting the information after finishing payment with PayPal using Django
I'm using django-paypal for managing payments on my website and it works well with the money transfer part but I can't get the user information to input into my database. I looked at some stuff online and what people do is just getting the requset.POST and request.GET data and the information is there but somehow it's not working for me. Here is my view: def index(request): paypal_dict = { "business": "testmail@gmail.com", "amount": "10.00", "currency_code": "USD", "item_name": "Donation", "invoice": randomString(20), "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('pay_app:completed')), "cancel_return": request.build_absolute_uri(reverse('pay_app:canceled')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, "pay_app/donation.html", context={'form': form}) @csrf_exempt def paypal_return(request): context = {'post': request.POST, 'get': request.GET} return render(request, 'pay_app/complete-pp.html', context=context) It's probably something simple but I just can't figure it out. -
How to concatenate string and variable in django view.py?
i want to concatenate string and variable in views.py file. i tried {{}} but this is not working on views.py file. try: filename= file.cv #file name comes from db path = "media/" filename return FileResponse(open("path, 'rb'), content_type='application/pdf') except FileNotFoundError: raise Http404() i need to save a string in path variable like "media/cv.pdf" or "media/mycv.pdf" but can't do that. -
Django redirection after login
I have an app where I'm trying to allow login by username alone. I've been doing this: @login_required(login_url='/login') def index(request): # bunch of queries to provide to the add_rule.html via context return render(request, "index.html", context=context) def user_login(request): if request.method == 'GET': return render(request, 'registration/login.html') else: username = request.POST.get('username') user = authenticate(username=username) # custom function login(request, user) # somehow return the above previous index() function with the request that has updated login/username information I'm not exactly sure how I can render the index.html template with the request that now has the login information. The docs are not clear on how things get redirected after login. I apologize if there is not enough information. -
Importing and using an Npm Package for Draggable Components in a Django template using Script Tags
I have a conceptual question that I would like some help answering. I am currently building a Django app, and I would like to use React in a very basic way to add interactivity to my website. I have a piece of information that gets displayed on on my web page that I would like the user to be able to move around freely on the page by clicking and dragging. I found this React plugin called React Draggable that looks like it would do the trick perfectly: https://www.npmjs.com/package/react-draggable. Previously, I followed a guide and added a react component to my Django template (albeit a simple one) using simply script tags so I know it may be possible (see guide here:https://medium.com/@to_pe/how-to-add-react-to-a-simple-html-file-a11511c0235f). Is there a way to successfully import React Draggable using a tag such that I would not need to actually install npm and Node and have it live alongside my Django app. I tried making a textfile of the code and putting into my static folder and used a script tag to import it, but it did not work. I did notice that React Draggable has two dependancies. Could this be the problem? Anyway, is what I am trying … -
Django: model form decimal field not validating
I have a simple model form to create a new product. I show some fields in the template for the user to choose and set other fields in the view. It works fine until I add a decimal field to the form. Then, it seems like the form is not validating because it doesné run the related code. I don´t really know if it has something to do with the field being Decimal or something else. Thanks in advance. The model class PedidosK(models.Model): producto = models.ForeignKey(ProductosBase, help_text="", blank=True, null=True, on_delete=models.CASCADE) comprobante = models.CharField(max_length=200, help_text="", blank=True, null=True) cliente = models.ForeignKey(Contactos, help_text="", blank=True, null=True, on_delete=models.CASCADE) vendedor = models.ForeignKey(User, help_text="", blank=True, null=True, on_delete=models.CASCADE) lista = models.ForeignKey(Marcas, help_text="", blank=True, null=True, on_delete=models.CASCADE) prod_nombre = models.CharField(max_length=200, help_text="", blank=False, null=True) uds = models.IntegerField(help_text="", blank=True, null=True) boxes = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) vu = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) subtotal = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) bonif = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) bonif_categoria = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) bonif_linea = models.DecimalField(help_text="", decimal_places=2, max_digits=100, blank=False, null=True) pedido_minimo = models.IntegerField(help_text="Units por Inner box", blank=True, null=True) def __str__(self): return str(self.producto) The form that works fine class FormularioLineaPedidoKProductoExtra(forms.ModelForm): class Meta: model = PedidosK fields = ['prod_nombre', 'uds', 'vu', 'cliente', … -
How do i host my fullstack application built with {django & react} on Google cloud
I created my portfolio website with django and react. I would like to host on Google cloud free account. Any doc or tutorials link ? In local host to run python server, we do python manage.py for js we do npm run dev. When we host it in Google cloud. How do these two work. Looked for tutorials in youtube. -
Embed ESRI map widget in extended djando template html file
I am trying to embed an ESRI map widget in an HTML template that is extended from another master HTML file. The master is called a layout.html and uses JQuery and Bootstrap with a block for content. The layout.html file has a script section with a $(document).ready(fn(){..}) defined. The extended page only I cannot get the ESRI widget for a map to render anywhere on the page. I have tried to put the script at the start of the extended file, then in the body in the extended file and then at the end of the script(s) block in the layout.html file to no avail. <script src="https://js.arcgis.com/4.12/"></script> I get the error: dojo.js:24 Error: multipleDefine at r (dojo.js:5) at Ia (dojo.js:21) at dojo.js:22 at f (dojo.js:4) at Sa (dojo.js:22) at b (dojo.js:21) at HTMLScriptElement.<anonymous> (dojo.js:23) On moving the said scripts to the footer, I get an error message stating that $().mask is not defined when I do have the jquery.mask.js included. The layout.html file has the following inclusions at the end of the file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script> <script type="text/javascript" src="{% static 'home/js/bootstrap.min.js' %}"></script> <script type="text/javascript" src="{% static 'home/js/custom/register.js' %}"></script> <script type="text/javascript" src='https://www.google.com/recaptcha/api.js'></script> <script type="text/javascript" … -
Unable to Login to Django Admin/webapp login using valid credentials on remote server
I have just finished building my web app and migrated it to digital ocean droplet. When running on my local machine I am able to successfully authenticate the user/view dashboard etc... python3.6.8 & Django 2.2.1 I have gone through the process of setting up Gunicorn and NGINX after several days of debugging I came to the conclusion my issue is Django specific. To verify this conclusion I have ran. manage.py runserver 0.0.0.0:8000 I am able to make GET requests and POST requests (and switch between landing page, signup, homepage etc) and attempt to login if my credentials are wrong. As soon as I try to login with the correct credentials. Then Django will receive the POST request and hangup indefinitely. ufw (firewall is disabled) allowed_hosts = [*] all nonessential security settings in settings.py are disabled as well. I am able to authenticate using manage.py shell by running: python3 manage.py shell >>> from django.contrib.auth import authenticate >>> u = authenticate(username="user", password="pass") >>> u.is_staff True >>> u.is_superuser True >>> u.is_active True Here is my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ #django builtin Imports 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
Bypass the ordering inside the Meta class
I have two models: class Member(models.Model): course_member = models.ForeignKey(CourseMember, on_delete=models.CASCADE class Meta: db_table = 'member' ordering = ['-id'] class CourseMember(models.Model): name = models.CharField(max_length=30) When I try running. Member.objects.values('course_member').aggregate(Count('id')) I keep getting the wrong order_by. instead of grouping by course_member, it keeps grouping by member_id. The Django docs warn about this issue, see link. I'm trying to see if there is a solution to bypass this issue instead of just waiting for Django 3.1 -
How do I tell POpen to use/set certain environment variables?
I'm using Python 3.7 and Django. I use the below to run a command I would normally run in the shell ... out = Popen([settings.SELENIUM_RUNNER_CMD, file_path], stderr=STDOUT, stdout=PIPE) t = out.communicate()[0], out.returncode his dies with the error b'env: node: No such file or directory\n' What I'm trying to figure out is how to give my Python environment access to the normal environment variables I have access to, or figure out a way to set them before I run my Python command. Normally "node" is easily found when I check as myself davea$ which node /usr/local/bin/node But I don't know how to tell Python to use the same PATH that I have access to. -
Django model form field: use disabled but still pase (calculated) values to form.is_valid()
Assume I have a model class A with a mandatory text field b (and other fields). I want to create a model form where under certain circumstances (determined in the form's __init__) the value for b is calculated and not shown in the form. It seems that setting disabled is the way to go, which, according to this docs entry, will ignore any value passed but instead use "the form’s initial data". However, the following does not do what I hoped it would do: class A(models.Model): b = models.TextField() c = ... class MyForm(forms.ModelForm): class Meta: model = A fields = ('b', 'c', 'd') def __init__(self, *args, **kwargs): if complicated_test(*args, **kwargs): field = self.fields['b'] field.disabled = True field.initial = 'Bla' This does disable the field, but seems to ignore the manually given value Bla, which in my case will make form.is_valid() fail (as my model really expects Bla to be in there). Questions: Is field.initial = 'Bla' really supposed to fail in this situation, or it this a weird bug in my setup? If no bug: Can I set "the form’s initial data" in some other way? What alternatives are recommended? In my case, I do not see a natural … -
django-heroku installation giving an error
I'm trying to deploy my app to heroku but after executing pip install django-heroku it gives me an error. I'm running Python 3 with Django 2.2 on a mac. The error message recommended to install psycopg2-binary, which I did but after the installation I still see the same error. Thank you for help. The error message: ERROR: Complete output from command python setup.py egg_info: ERROR: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/6z/cqmvjcds4_s2pz_8zb28s_v40000gn/T/pip-install-28adny1a/psycopg2/ -
Elasticsearch create index error on Heroku
I have a django application that uses elasticsearch with the django-elasticsearch-dsl package as an integration. Locally I'm using docker compose to host my django and elasticsearch services and after some setup everything is working fine. I'm hosting the app on heroku with the bonsai add-on and am getting the following error when running ./manage.py search_index --rebuild to create the index on the heroku bonsai elasticsearch instance. elasticsearch.exceptions.RequestError: RequestError(400, 'mapper_parsing_exception', 'Root mapping definition has unsupported parameters: [receiver : {type=text}] [sender : {type=text}] [created_at : {type=date}] [id : {type=integer}] [text : {type=text}] [source : {type=text}] [title : {type=text}]' ) I've played around with my local elasticsearch version and flavor to get it to be as similar as possible to the deployed instancem, but can't get the error to reproduce to debug it. The only fields that are different are name and cluster_name, all other fields are the exact same. { name: "7OgSp1I", cluster_name: "docker-cluster", cluster_uuid: "ZOXfnHeJTrK-nF7GEKON3A", version: { number: "6.5.4", build_flavor: "oss", build_type: "tar", build_hash: "d2ef93d", build_date: "2018-12-17T21:17:40.758843Z", build_snapshot: false, lucene_version: "7.5.0", minimum_wire_compatibility_version: "5.6.0", minimum_index_compatibility_version: "5.0.0" }, tagline: "You Know, for Search" } Both local and deployed have the same version of django-elasticsearch-dsl installed through the Pipfile. Not sure what else to … -
Django passing a parameter from a site to another
I have two different django project hosted on two different domains. I would from a view of a project1 redirect traffic to a page with a form of a project 2 passing a value for fill a field of the form. In my project1 view i do: @login_required def go_ccredit(request, lic_num=None, **kwargs): return HttpResponseRedirect('https://www.project2.ai/goform') i would to pass lic_num variable in my HttpResponseRedirect, and in my project2 goform page check if there is in request a variable named lic_num and in case fill the field with id=license with it's value. I hope to be clear enough So many thanks in advance -
Grabbing the data from the post request for create model view set override django rest framework
I have a django rest framework project with a model view set. I want to override the create method of the viewset. With the override, I want to grab data from the post request and data from the url arguments. Now i can grab the url arguments as I am expecting. I am having trouble trying to get the post request data informaiton in order to set all the correct data before submitting the create request. This is what I have..: I am having an issue with the request.data['version'] & request.POST['version'] & request.data.version @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): # print(request) namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":self.request.user, 'version':request.data['version'], 'namespace':namespace, 'path':request.data['path'], 'value':request.data['value'], 'user_id':request.user.id, } return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':request.data['version'], 'namespace':namespace, 'path':path, 'value':request.data['value'], 'user_id':request.user.id, } return super().create(data) -
Django join different tables
This is what i got in the models class SFE(models.Model): snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True) # Field name made lowercase. elementid = models.ForeignKey(Functionalelement, models.DO_NOTHING, db_column='ElementID') # Field name made lowercase. celllineid = models.ForeignKey(Celllines, models.DO_NOTHING, db_column='CELLLINEID') # Field name made lowercase. countexperiments = models.PositiveIntegerField(db_column='countExperiments') # Field name made lowercase. filetype = models.CharField(db_column='fileType', max_length=10) # Field name made lowercase. class Meta: managed = False db_table = 'SNPs_FunctionalElement' unique_together = (('snpid', 'elementid', 'celllineid', 'filetype'),) def __str__(self): return str(str(self.snpid) + str(self.elementid) + str(self.celllineid) + str(self.filetype)) class Functionalelement(models.Model): elementid = models.AutoField(db_column='ElementID', primary_key=True) # Field name made lowercase. name = models.CharField(unique=True, max_length=55) class Meta: managed = False db_table = 'FunctionalElement' def __str__(self): return str(self.elementid) class Snps(models.Model): snpid = models.AutoField(db_column='SNPID', primary_key=True) # Field name made lowercase. rsid = models.CharField(unique=True, max_length=20) chrom = models.CharField(max_length=5) pos = models.PositiveIntegerField() ref = models.CharField(max_length=1) alt = models.CharField(max_length=1) maf1000genomes = models.FloatField(blank=True, null=True) maftopmed = models.FloatField(db_column='mafTOPMed', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'SNPs' def __str__(self): return str(self.snpid) Now i want to join FunctionalElement with SFE in order to retrieve the field FunctionalElement.name given a specific SFE.snpid. I tried with SFE.objects.select_related('elementid__name') but i know it's wrong and i can't understand how to work with django ORM -
Custom ordering on a many to many relationship
I'm trying to implement a model that represents sorted lists of items, without having to specify the sort order every time I'm unable to find a way to customize the get_queryset() method of the forward many-to-many relationship manager from django.db import models class Item(models.Model): name = models.CharField(max_length=50) class Meta: ordering = ['name'] class List(models.Model): name = models.CharField(max_length=50) items = models.ManyToManyField(Item, through='Listing')) class Listing(models.Model): list = models.ForeignKey(List, on_delete=models.CASCADE) items = models.ForeignKey(Item, on_delete=models.CASCADE) index = models.SmallIntegerField() class Meta: ordering = ['index'] I would like Item.objects.all() to be sorted by name (working), and List.objects.get(pk=1).items to be sorted by listing.index (not working; also sorted by name) -
Django - How to retrieve columns in template automatically from a query in views.py?
There is a module with 30 columns. I query this table in the views.py to get the last record (last row). To get the data in template (index.html), I have to write each column and in front of it, its value. I have to do it 30 times! is there anything like {{form}} to get all the columns and their value automatically or at least by using {% for ... %}? in views.py def articlesindex(request): data = Articles.objects.all().last() return render(request, 'Articles\index.html', {'articles':data}) in index.html {{ articles }} (does not work) {{ articles.a_table }} (does not work) {% for k,v in articles %} (does not work) <tr> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endfor %} -
Can Email Validators overwrite clean() method?
Problem: I am attempting to write a clean() method on my Django forms class and for the most part, it is working (Password validation is working but not email?). My goal is to compare two email fields and two password fields to each other and raise a validation issue if they do not match. I have tried using the raise forms.ValidationError() as detailed in the Django docs here, however I would prefer to display the validation error on both fields so I am trying to use the self.add_error('field', msg) method instead as detailed on the same page. My attempt: forms.py class userRegistrationForm(forms.Form): # field definitions here def clean(self): cleaned_data = super(userRegistrationForm, self).clean() email1 = cleaned_data.get('email') email2 = cleaned_data.get('emailConfirm') password1 = cleaned_data.get("password1") password2 = cleaned_data.get("password2") if password1 != password2: msg = 'Your Passwords do not match...' self.add_error('password1', msg) self.add_error('password2', msg) elif email1 != email2: msg = 'Your emails do not match...' self.add_error('email', msg) self.add_error('emailConfirm', msg) Exact error: What ends up happening, is the first email field validates with no errors no matter what and if there is a mismatch, the error only shows up on the second field, unless I type out the full correct email address, then that field also … -
Django-allauth, how do I change the url in my email confirmation email?
friends. Used Django-allauth package for authorization in django project. The project is located in the Docker container (with parameter -p 8002:8001) on the server with the domain(testsite.com). When I run the container on the command line, I run the python command manage.py runserver 0.0.0.0:8001. In the admin panel specify the domain of the site. The problem is that django-allauth sends an email to confirm the email type - http://127.0.0.1:8002/accounts/confirm-email/MQ:1hjJgA:XFqIW130fMBQ5_blim_KVxYsVXg/. In the package code found that the url is used to build the site.domain - but when the variable is output to the console - get the correct domain of the form - testsite.com ahhh! I can not understand what variable to override or how to make to get the desired url of the form - http://testsite.com/accounts/confirm-email/MQ:1hjJgA:XFqIW130fMBQ5_blim_KVxYsVXg ahhh! Can who knows as solve this question?