Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django order_by cosine similarity faster
class Item(models.Model): vector_repr = models.TextField(..., verbose_name='jsonified vector representation') ... # My current solution: as_vector = lambda it: np.asarray(json.loads(other.vector_repr)) cosine_similarity = lambda other: np.dot(item_vect, as_vector(other)) item = Item.objects.get(...) item_vect = as_vector(item) db_items = Item.objects.exclude(id=item.id) similar_items = sorted(db_items, key=cosine_similarity) Basically i want to sort all the Items in the database applying the cosine similarity with a given item. The problem is that the vector that represents all the items (vector_repr) is very large, and the items in the database are a lot, so this method is really slow (~2min). How can i speed up this process? (Possibly without storing in my db the similarity of each pair of items) -
Unable to import Django within my virtual environment
I'm having trouble importing Django within my virtual environment, I keep getting the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/thecorp/django/olympus/virt_env/lib/python3.6/site-packages/django/__init__.py", line 3, in <module> from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils.version' This happens when I "python manage.py runserver" or when I just import Django in general. I've tried checking my installation and I can't find anything immediately wrong - Django shows up when I "pip freeze" and is included within my PATH. Any help or advice would be appreciated. Thanks! -
Django forms: i cant access the forms from the home page
When I click the login or signup buttons on the main page, it goes to the links but the forms are not coming. Pages are coming empty. No errors appear in console. When i remove the part {% extends "base_generic.html" %} from login.html , then i access the login page successfuly.I can't find out where I made a mistake. Thanks for your help. Sorry for my bad English. #models.py class MyUser(AbstractUser): is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) student_no = models.CharField(unique=True, max_length=9, help_text="student number") student_name = models.CharField(max_length=50, help_text="student name") student_surname = models.CharField(max_length=50, help_text="student surname") class Meta: permissions = (("can_upload_photo", "Upload Photo Permission"),) def __str__(self): return self.student_no # views.py class StudentSignUpView(CreateView): model = MyUser form_class = StudentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index.html') #forms.py class StudentSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = MyUser @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.save() return user #urls.py urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), path('accounts/signup/', views.SignUpView.as_view(), name='signup'), path('accounts/signup/student/', views.StudentSignUpView.as_view(), name='student_signup'), path('accounts/signup/teacher/', views.TeacherSignUpView.as_view(), name='teacher_signup'), ] #base_generic.html <div class="col-6 text-right"> {% if user.is_authenticated %} <p class="pt-3">Logged in as <strong>{{ user.username }}</strong>. <a href="{% … -
Passing content of a LaTeX file as string from Django to React
I am trying to display the content of a LaTeX file using React. The file gets loaded by Django, which passes it to an html file, that in turn passes it on to a javascript (React) file. However, for some reason I can only get the first line of the LaTeX file displayed. The python method, in views.py that loads the LaTeX file: def index(request): lines_list = [] with open(os.getcwd() + '/latexfiles/example.tex', 'r') as file: for line in file: lines_list.append(line) lines_string = ' '.join(lines_list) context = {'texfile': lines_string} return render(request, 'react.html', context) The html file, react.html: {% extends "base.html" %} {% block content %} <div id='root' data={{ texfile|safe }}></div> {% endblock content %} The App.js file, that is supposed to render the content: import React, { Component } from 'react'; import './App.css'; class App extends Component { render() { return ( <div>{this.props.message}</div> ); } } export default App; The LaTeX file, that I would like to display (as LaTeX code, not PDF): \documentclass[11pt,a4paper]{article} \author{Jeff Jefferson} \title{Test document} \begin{document} My name is Jeff! \end{document} If I run this code, only the first line of the example.tex is displayed, i.e. \documentclass[11pt,a4paper]{article} However, displaying the content of example.tex directly in react.html without calling … -
How to query for more than one content_type model from Django LogEntry?
I am able to query for one content type mode by doing this: LogEntry.objects.filter(content_type__model='foo') But what if I want all LogEntry objects that have content_type models foo and bar? I tried models_i_want = ['foo', 'bar'] LogEntry.objects.filter(content_type__model_in=models_i_want) But that fails like so: Traceback (most recent call last): File "<input>", line 1, in <module> File "/opt/sfo/sfo/env/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/opt/sfo/sfo/env/lib/python2.7/site-packages/django/db/models/query.py", line 781, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/opt/sfo/sfo/env/lib/python2.7/site-packages/django/db/models/query.py", line 799, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/opt/sfo/sfo/env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1260, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/opt/sfo/sfo/env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1286, in _add_q allow_joins=allow_joins, split_subq=split_subq, File "/opt/sfo/sfo/env/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1211, in build_filter raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) FieldError: Related Field got invalid lookup: model_in Thanks -
Cannot query 'PublisherQuerySet' attributes in Django
I am currently building a website in DjangoCMS and I want to query the Title model from cms and compare it against request.path. From there I will load a prefiltered version of the assets. Everything works up until I compare page_obj.title. I return the error 'PublisherQuerySet' object has no attribute 'title' but I have checked the model and it does have a title attribute. Is there a certain way I need to query that PublisherQuerySet object as opposed to a regular QuerySet so that it pulls it back? in the obj.name object directly before it worked just fine. Feels like I am missing something obvious. from django.shortcuts import render from django.http import HttpResponse from .models import * import os from cms.models import Title def AssetListView(request, *args, **kwargs): path = os.path.basename(os.path.normpath(request.path)) print(path) page_obj = Title.objects.filter(slug=path)[:1] print (page_obj) for obj in Tag.objects.all(): print (obj.name) if obj.name == page_obj.title: return HttpResponse('<h1>test HTML<h1>') -
Django - Multi-types model
I am a new user of Django, and I am trying to figure out how to created a model which can support multi type assignement For example, I have a class contract, and this class can contain many ContractElement A ContractElement has a title, a content and a type, this type can be "numeric", "text", "image" or "user" (the last one is a reference to an User object). In each cases, the type determine what the content is and how it will be processed by the rest of my application (including how it will be displayed on the HTML page). But I don't know what is the right way to declare the ContractElement class in order to support all these cases :( -
Configuring output of % static in django
I'm experimenting with django-distill (https://github.com/mgrp/django-distill) to generate a static site from a django project. i'm using django 1.10.8 . My main template contains: <!-- Bootstrap Core CSS --> {% load staticfiles %} <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet" /> <!-- Custom CSS --> <link href="{% static "css/landing-page.css" %}" rel="stylesheet" /> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css"/> The paths to the css and js files are correct when I run the project locally on my windows system. However when I look at the source html I see: on my windows system this works with a running sever, i.e. http://127.0.0.1:8000/static/css/bootstrap.min.css but it breaks with static files and I have to change these to http://127.0.0.1:8000/static/css/bootstrap.min.css <!-- Bootstrap Core CSS --> <link href="./static/css/bootstrap.min.css" rel="stylesheet" /> Is there any way to set % static to render to ./static/ instead of /static/ -
Django RuntimeError: Model class django.contrib.contenttypes.models.ContentType error
I am using Django 2. I am getting this error code, I have looked all over online and am not finding any answers to fix why it keeps giving me this error code. Traceback (most recent call last): File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/utils/functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "/home/matthew/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/matthew/mykoio/mykoio/urls.py", line 21, in <module> path('website/', include('website.urls')), File "/home/matthew/anaconda3/lib/python3.6/site-packages/django/urls/conf.py", … -
Django QuerySet from SQL Server Function
I have a function in sql server dbo.fnSearch() that takes 2 arguments. I have the models.py class set up to handle the query. I have been using this in my views.py: MyClass.objects.raw("SELECT * FROM fnSearch(%s,%s)",[var1,var2]).using('mydb') However, this looses some of the django QuerySet functionality. Is there a way to still utilize this function, while keeping my data in the django QuerySet format?? Note: My specific function should only return one row of data. I wanted to access each individual piece when rendering to html. The only way to do so with the .raw() method is through a for loop (or at least so I think), which is difficult for how I would like to utilize the data in the html page. I would like to just reference the individual elements. -
403 Forbidden Access to posting shares denied for Linkedin API using python-linkedin library
I'm new to working with the Linkedin API and I'm trying to post to LinkedIn using the python-linkedin library: https://github.com/ozgur/python-linkedin We use Auth0 for authentication. I can get profile information. However, I get a 403 error when trying to post using the Share API. Testing get profile in the shell works: In []: linkedin_api.get_profile() Out[]: {'firstName': '*my name*', 'headline': '*my headline*', 'id': '*my id*', 'lastName': '*my lastname*', 'siteStandardProfileRequest': {'url': 'https://www.linkedin.com/profile/view?id=*CONFIDENTIAL*&authType=name&authToken=*CONFIDENTIAL*'}} However when I try to post to linkedin: In []: linkedin_api.submit_share('Test posting ...: from the API I am working on using JSON' ...: , 'A title for your share', None, 'http: ...: //www.linkedin.com', 'http://d.pr/3OWS') This results in a 403 Client Error LinkedInForbiddenError: 403 Client Error: Forbidden for url: https://api.linkedin.com/v1/people/~/shares? oauth2_access_token=*CONFIDENTIAL*: Access to posting shares denied -
How to make login inclusion tag in Django?
I'm trying to get a template tag with login form. Simple user and password form built in authentification. {% login_form %} from django import template register = template.Library() from django.contrib.auth.forms import authenticate @register.inclusion_tag("userpanel/tags/login.html", takes_context=True) def login_form(context): request = context.get("request") address = request.session['address'] return {'address':address} -
Installation error in django with using pip
I'm new to the Django world and I want to install it from pip into my windows but I get this error when installing: C:\Users\xxxx>pip install django Collecting django **Could not install packages due to an EnvironmentError: Could not find a suitable TLS CA certificate bundle, invalid path: \ms4w\Apache\conf\ca-bundle\cacert.pem** -
How to print the result of a stored proc in template using pagination?
I used below code to run a stored proc in Django - cur = connection.cursor() cur.execute('exec [dbo].[usp_mytest] %s, %s, %s, %s,', (field1, difference, age, aginggrp)) queryset1 = cur.fetchall() cur.close() Now, I want to print the type of this queryset1 and did the below: return HttpResponse(queryset1[0][1]) - This gives me the value of the first field I am expected to get. I am doing it in a function in views.py. I want to use pagination against this queryset1 and writing below code: paginator = Paginator(queryset1, 25) try: page = int(request.GET.get('page', '1')) except: page = 1 try: type1 = paginator.page(page) except('EmptyPage', 'InvalidPage'): type1 = paginator.page(1) return render(request, 'index.html', { 'type1': type1, 'page_range': page_range, }) But it is giving error for page_range and as soon as I comment this page_rane line from render() and comment the above pagination code, it gives me blank page. Can someone please suggest me the way to do pagination here? -
How can I log the requests that my django server makes?
I know that I can use logging to log all the requests that my django server gets. However I would like to log the requests along with headers and body that my django server makes to other servers. How can I access this info? -
Creating table for test with raw SQL without forcing lowercase
I am working on a application that uses a legacy database, and since I can't manage the table, and changing meta attribute during setUp is a pain with postgres, I decided to create the table manually. I was able to do so, but the table name, and all its 78 fields, were wrote using CamelCase, and django forces it to go lowercase when I create it. I was looking for a way to make create the names as they are. The original name for the table is is ClientsCampaign, but django creates it as clientscampaing. The same goes for the fields. My setUp is like this def setUp(self): connection.cursor().execute("CREATE TABLE {} ({} integer NOT NULL)".format('ClientsCampaing', 'AccountId')) Any hint? -
How to print type of an object in which we are getting result of a stored proc in django?
I used below code to run a stored proc in Django - cur = connection.cursor() cur.execute('exec [dbo].[usp_mytest] %s, %s, %s, %s,', (field1, difference, age, aginggrp)) queryset1 = cur.fetchall() cur.close() Now, I want to print the type of this queryset1 and did the below: return HttpResponse(type(queryset1)) - But this is giving me error where as if I write: return HttpResponse(queryset1[0][1]) - This gives me the value of the first field I am expected to get. Where am I doing wrong? I am doing it in a function in views.py. I am trying to do the httpresponse on type() because I need to use it for pagination of the records. -
Normal method or property?
Should the below be a normal model method or a property? @property def num_used_licenses(self): return len(CompanyUser.objects.filter(company_id=self.pk, activated_on__isnull=False)) # why doesn't count() work here? Two points: It does do a DB query so it's not trial performance-wise to call. It will never take any parameters I was under the impress you would use a property if it's both trivial and doesn't take any parameters, but what should the above be, and why? -
Why doesn't FileResponse expect as_attachment as an argument?
I'm trying to get the Django example for using reportlab in a view and I'm getting the following error: TypeError at /datos/generarPDF init() got an unexpected keyword argument 'as_attachment' Request Method: GET Request URL: http://127.0.0.1:8000/datos/generarPDF Django Version: 2.0.6 Exception Type: TypeError Exception Value: init() got an unexpected keyword argument 'as_attachment' The code is the following: def generarPDF(request): buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(100, 750, "Hello world.") p.showPage() p.save() return FileResponse(buffer, as_attachment=True, filename='hello.pdf') I took the code from the Django docs (https://docs.djangoproject.com/en/2.1/howto/outputting-pdf/) Is there anything I'm missing? -
How do I get the www version of the site to work in Django Mezzanine
I use Django Mezzanine for my blog. I have altered the default code and have set the "blog" to replace the "home". Everything's fine except if I traverse the pages with "www" version. The side panels and footers get loaded but there are no signs of the body and navigation menus. I have added both 'domain.com" and "www.domain.com" to the allowed_host. What am I missing? -
Install of WeasyPrint on AWS failing
The bottom line: On AWS, after successfully installing dependencies, 'pip install weasyprint' fails with error message: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-gs8u357u/cairocffi/ Can anyone help me get past that? The details: I successfully executed the following instruction for installing on Fedora at https://weasyprint.readthedocs.io/en/latest/install.html: sudo yum install redhat-rpm-config python-devel python-pip python-setuptools python-wheel python-cffi libffi-devel cairo pango gdk-pixbuf2 Result: Updated: cairo.x86_64 0:1.14.8-2.amzn2.0.2 pango.x86_64 0:1.40.4-1.amzn2.0.2 python-devel.x86_64 0:2.7.14-58.amzn2.0.4 Dependency Updated: cairo-gobject.x86_64 0:1.14.8-2.amzn2.0.2 python.x86_64 0:2.7.14-58.amzn2.0.4 python-libs.x86_64 0:2.7.14-58.amzn2.0.4 While still in my virtual environment, I executed: pip install WeasyPrint Collecting WeasyPrint Using cached https://files.pythonhosted.org/packages/a5/3c/a7021bea33ef7515901d77b11cb0d356171068055591e9d813962a0092d8/WeasyPrint-0.42.3-py3-none-any.whl Collecting cairocffi>=0.5 (from WeasyPrint) Using cached https://files.pythonhosted.org/packages/62/be/ad4d422b6f38d99b09ad6d046ab725e8ccac5fefd9ca256ca35a80dbf3c6/cairocffi-0.9.0.tar.gz Complete output from command python setup.py egg_info: warning: no previously-included files found matching 'setup.pyc' warning: no previously-included files matching 'yacctab.*' found under directory 'tests' warning: no previously-included files matching 'lextab.*' found under directory 'tests' warning: no previously-included files matching 'yacctab.*' found under directory 'examples' warning: no previously-included files matching 'lextab.*' found under directory 'examples' zip_safe flag not set; analyzing archive contents... Traceback (most recent call last): File "/home/ec2-user/phrancko-project/myenv/lib64/python3.7/site-packages/setuptools/sandbox.py", line 154, in save_modules yield saved File "/home/ec2-user/phrancko-project/myenv/lib64/python3.7/site-packages/setuptools/sandbox.py", line 195, in setup_context yield [long traceback clipped] ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-gs8u357u/cairocffi/ -
What would be considered the root directory to a third party javascript in Django
When using Send Pulse they instruct you place a javascript in the head of your template. This javascript then refers to 2 other scripts that they instruct you to place in the root of you web site. Where can these be placed so that their javascript will automatically find them in the "web root"? -
Can anyone help me out with the unresolved static reference error in django
< img src="{{ STATIC_URL }}images/{{ item.image_name }}.png" alt="item icon" title="items"/ >. I have the images in database static_folder/images/image_name.png and keep getting this error when i try to get the image_name from the python file and try to get that particular image from static folder. Am i doing something wrong? I am new to django templates. -
Why do I get [CRITICAL] WORKER TIMEOUT gunicorn with Django Mezzanine?
I am using the Django Mezzanine blog engine. Today suddenly I started getting nginx 502 bad gateway error. I Viewed the error logs in which I had: File "/home/username/.virtualenvs/problog/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/username/.virtualenvs/problog/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 134, in init_process self.run() File "/home/username/.virtualenvs/problog/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 124, in run self.run_for_one(timeout) File "/home/username/.virtualenvs/problog/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 83, in run_for_one self.wait(timeout) File "/home/username/.virtualenvs/problog/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 35, in wait ret = select.select(self.wait_fds, [], [], timeout) TypeError: argument must be an int, or have a fileno() method. [2018-08-19 15:44:41 +0000] [766] [CRITICAL] WORKER TIMEOUT (pid:788) [2018-08-19 15:44:41 +0000] [766] [CRITICAL] WORKER TIMEOUT (pid:783) I tried fab deploy to check if it resolves the issue but I got the following error: $ kill -HUP `cat /home/username/mezzanine/problog/gunicorn.pid` -> [204.12.226.162] out: /bin/bash: line 0: kill: (677) - Operation not permitted [204.12.226.162] out: Fatal error: run() received nonzero return code 1 while executing! Requested: kill -HUP `cat /home/username/mezzanine/problog/gunicorn.pid` Executed: /bin/bash -l -c "kill -HUP \`cat /home/username/mezzanine/problog/gunicorn.pid\`" My questions are: what are the probable causes of this error in the first place? And how would you suggest me to fix it? -
How deny access to the previous page when a user have logged out in django?
I'm a newbie in django, im using the 1.8 version in a Ubuntu server, i made the log in and logout process successfully but when my users try to go to the previous page, they can see it as an anonymous user. How can i deny the access? I tried to use a if on my views.py but doesn't work: def login(request): if not request.user.is_authenticated(): return render(request,"base.html",{}) return render(request,"general.html",{}) @login_required def general(request): return render(request,"general.html") Hope someone can help me.