Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user ForeignKey and unique object name
class User: username = (unique=True) class Object: user = models.ForeignKey(settings.AUTH_USER_MODEL) name = () How can i have multiple Objects with the same name, but each user can only have one unique Object name. for example: user1 can only have one unique Object name of "dog", user2 can also only have one unique Object name of "dog", therefore there can be multiple Objects with the same name of "dog", but each user can only have one Object named "dog" through the ForeignKey. if user1 try's to create another object named "dog" then raise something like a forms validation error. -
Is there an easy way to code in a user defined (input) seed word for markovify, in python?
I'm trying to implement markovify into a web application I'm making. There will be a simple text box for user input to be sent, and I want to use this input, selecting a random word, to dictate the start word for markovify. Does anyone know if this is possible, and/or how to go about writing it in? The repository for markovify can be found in the link below. Any help is appreciated. https://github.com/jsvine/markovify -
"django.contrib.admin.sites.NotRegistered: The model User is not registered" I get this error when a want to register my Custom User.
I overwrite default model AbstractUse for authorization through email. applications.account.models.py # -*- coding: utf-8 -*- import datetime from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' USERNAME_FIELD = 'email' applications.account.admin.py And use my Custom user in admin.py file. I tried to unregistered default user model and register custom. # -*- coding: utf-8 -*- from django.contrib import admin from django.http import HttpResponseRedirect from django.contrib.auth.models import User from modeltranslation.admin import TabbedTranslationAdmin from applications.account.models import Profile, Phone, ShippingAddress, PartnerGC, Referral, Operation from applications.account.models import User as MyUser class UserInline(admin.StackedInline): model = Profile max_num = 1 can_delete = False class OperationInline(admin.StackedInline): model = Operation can_delete = True class PhoneInline(admin.StackedInline): model = Phone can_delete = True class PartnerGCInline(admin.StackedInline): model = PartnerGC max_num = 1 can_delete = True class ReferralInline(admin.StackedInline): model = Referral max_num = 1 can_delete = True class ShippingAddressInline(admin.StackedInline): model = ShippingAddress can_delete = True class ProfileAdmin(admin.ModelAdmin): list_filter = ["date_joined"] search_fields = ["=id", "first_name", 'last_name', "email"] list_display = ('id', "email", 'first_name', 'last_name', 'date_joined', 'last_login') actions = ['mark_active', 'mark_inactive'] inlines = [UserInline, PhoneInline, ShippingAddressInline, PartnerGCInline, ReferralInline, OperationInline] def user_email(self, instance): return instance.user.email user_email.short_description = u"E-mail" def user_active(self, instance): return instance.user.is_active user_active.short_description = u"Активен" user_active.boolean = True def user_staff(self, instance): … -
postgresql error: undefined symbol: GEOSClipByRect in django
when i migrate in djangothe django have return error below $ python manager.py migrate django.db.utils.InternalError: could not load library "/usr/lib/postgresql/9.6/lib/postgis-2.3.so": /usr/lib/liblwgeom-2.3.so.0: undefined symbol: GEOSClipByRect i researched many posts but not found any solution. Does anyone know the solution? my system info is below $ lsb_release -a Distributor ID: Ubuntu Description: Ubuntu 16.04.2 LTS Release: 16.04 Codename: xenial $ dpkg -l | grep postgres ii postgresql-9.6 9.6.2-1.pgdg16.04+1 amd64 object-relational SQL database, version 9.6 server ii postgresql-9.6-pgrouting 2.3.2+ds-2.pgdg16.04+1 amd64 Routing functionality support for PostgreSQL/PostGIS ii postgresql-9.6-pgrouting-scripts 2.3.2+ds-2.pgdg16.04+1 all Routing functionality support for PostgreSQL/PostGIS - scripts ii postgresql-9.6-postgis-2.3 2.3.2+dfsg-1~exp2.pgdg16.04+1 amd64 Geographic objects support for PostgreSQL 9.6 ii postgresql-9.6-postgis-2.3-scripts 2.3.2+dfsg-1~exp2.pgdg16.04+1 all Geographic objects support for PostgreSQL 9.6 -- scripts ii postgresql-client-9.6 9.6.2-1.pgdg16.04+1 amd64 front-end programs for PostgreSQL 9.6 ii postgresql-client-common 180.pgdg16.04+1 all manager for multiple PostgreSQL client versions ii postgresql-common 180.pgdg16.04+1 all PostgreSQL database-cluster manager ii postgresql-contrib 9.6+180.pgdg16.04+1 all additional facilities for PostgreSQL (supported version) ii postgresql-contrib-9.6 9.6.2-1.pgdg16.04+1 amd64 additional facilities for PostgreSQL $ dpkg -l | grep postgres ii postgis 2.3.2+dfsg-1~exp2.pgdg16.04+1 amd64 Geographic objects support for PostgreSQL ii postgis-doc 2.3.2+dfsg-1~exp2.pgdg16.04+1 all Geographic objects support for PostgreSQL -- documentation ii postgresql-9.6-postgis-2.3 2.3.2+dfsg-1~exp2.pgdg16.04+1 amd64 Geographic objects support for PostgreSQL 9.6 ii postgresql-9.6-postgis-2.3-scripts 2.3.2+dfsg-1~exp2.pgdg16.04+1 all Geographic … -
Add form to a django formset using only javascript (without jquery or ajax)
I'm working in a django application which allows to the user set some logic rules. In order to make this easy for the user, I would like to add a form to a formset using only javascript (without jquery or ajax). Any idea? Mi template: {% extends "navbar/navigator_devices.html"%} {% load staticfiles %} {% block title %}Taranis{% endblock %} {% block head %} <script> </script> {% endblock %} {% block content %} <div class="page-header"> <h1>Reglas para el usuario: {{ user }} {% if user.company %} ({{ user.company }}) {% endif %} </h1> </div> <form action="" method="post" class="row"> <table class="table table-striped" > <thead > <tr> <th class="hidden"></th> <th style="width: 25%;" > Rule </th> <th style="width: 25%;" > Delete </th> </tr> </thead> </table> {{ form.non_field_errors }} <div class="scrollable-table" > <table class="table table-striped" > <tbody> {% for form in formset.forms %} <!-- Es necesario añadir el form.id porque si no da un extraño error al hacer un save --> <!-- Django y sus oscuros problemas... --> <tr> {{ form.errors }} <th class="hidden"> {{ form.id }} </th> <th style="width: 25%;"> {{ form.rule_text.errors }} {{ form.rule_text }} </th> <th style="width: 25%;"> <a href="/delete/vehicle/{{ form.id.value }}" class="remove btn btn-default"><span class="glyphicon glyphicon-remove text-danger"></span> </a> </th> </tr> {% endfor … -
Django - Access field by iterating over field list
I am storing all many to many fields on an object using this - m2m_fields = list(model_source_obj._meta.many_to_many) I want to iterate over this list to make changes to another object of the same type. I have written the code for it as such - for field in m2m_fields: model_target_obj.field.add(**something) However, I keep getting the error model_target_obj class type has no attribute 'field'. How can I fix this? -
Looking for a framework or guide to building a wiki like openly editable page on my python Django web application?
I need to create a wiki-like open crowd editing page or platform on my python Django web application. Specifically, I have a lot of content on my site (videos, audios, documents, files) that is continuously updated but I also need to keep it organised, so I'm trying to include a contents page on my site, where any user or site visitor can help organize the content by simply editing the content table and saving it. When the edited version is saved, the new version appears to everyone who loads the page after that point in time. Something like a wiki. I might have the users login before being able to edit the contents page, but unsure yet. Anyways, I'm looking for a guide, framework, tutorial or a GitHub code or basically any help at all creating a openly editable contents page that organises the links to the site contents (urls available in my database). How do I proceed on this guys? Thanks -
Pycharm debugging using remote interpreter does not work
I am trying to debug a django project using remote interpreter (using SSH). I have setup environment variables and other parameters as well, running the project works fine but when I try to debug the project (Alt+Shift+F9), I get the following error. "error while loading shared libraries: libpython3.6m.so.1.0: cannot open shared object file: No such file or directory" I have already setup LD_LIBRARY_PATH and verified that project runs from pycharm with same configuration. The interpreter also works fine with command line. -
display edit button only if the logged in user is same as the user's page?
example: 1.example.com/username1 2.example.com/username2 i want to take to user to the edit profile page, i got all the permission working correctly and set the views accordingly. My Problem: i loggedin as username1 so i should not be able to access example.com/username2/edit/. i got this to work in the views by adding some permissions, but i dont want to display the edit button when the loggedin username1 views the page of username2. Now i use {% if user.is_authenticated %} and this results in display the edit button on page of username2 even though the loggedin user is username1. Any simple solutions that can be used in the templates directly? -
WebpackError at /ecom/saleor/
I am using saleor ecommerce site in django and I am faccing this issue WebpackError at / Error in Missing binding /home/saleor/node_modules/node-sass/vendor/linux-x64- 14/binding.node Node Sass could not find a binding for your current environment: Linux 64-bit with Node 0.12.x Found bindings for the following environments: - Linux 64-bit with Node.js 7.x This usually happens because your environment has changed since running `npm install`. Run `npm rebuild node-sass` to build the binding for your current environment. Please give me suggestion -
Framework selection for a new project?
Problem Context We have a set of excel reports which are generated from an excel input provided by the user and then fed into SAS for further transformation. SAS pulls data from Teradata database and then there is a lot of manipulation that happens with the input data & data pulled from Teradata. Finally, a dataset is generated which can either be sent to the client as a report, or be used for populating Tableau dashboard. Also the database is being migrated from Teradata to Google Cloud (Big Query EDW) as the Teradata pulls from SAS used to take almost 6-7 hours Problem Statement Now we need to automate this whole process, by creating front end for the user to upload the input files and from there on the process should trigger and in the end the user should receive the excel file or Tableau dashboard as an attachment in a mail. Can you suggest what technologies should be used in the front end & middle tier to make this process feasible is least possible time with google cloud platform as the backend? Can an R shiny front end be a solution given that we need to communicate with a … -
Use django template tag inside {{ verbatim }} and {{endverbatim}}
I have template containing lot of angular tags. So I put {{ verbatim }} at top of the html and {{ endverbatim }} at bottom of the html. Now somewhere between template I need to have one check where, I want to use django template's in-built tag. e.g. {% if user.group.name == "somename" %} Is it possible to escape that check? -
Django, IDLE slow loading page - 16s
As you can see from image, page loaded 16s, and most of time loaded IDLE. WTF??? I spent 2 month to dev., deployment by Heroku, learned git, AWS S3 - and when finished i notice this. I'm so sad T_T. Can you help me? i just don't understand how to fix it Image - timeline of my page -
django error on simple app while run the program
raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
django websocket send update from database without pooling
I am using django channels with redis for backend with mysql database, I push new data to mysql database and in consumers.py i send data through websocket to client. The problem is once the new data was pushed to the database the client has to send message in order to receive the new data. therefore i am using long pulling. the client send message every 2 second and gets the new data but it is very inefficient. Is there any other way to solve this problem so the client doesn't have to send message all the time? in consumers.py: def ws_message(message): livedata = serializers.serialize("json",testLiveData.objects.all()) Group(message.content['text']).send({ "text": livedata, }) in javascript: setInterval(function() { if (socket.readyState == WebSocket.OPEN) socket.onopen(); }, 2000); i followed tutorial on channels readthedocs -
SearchQuerySet().filter(content='content') returns results, but they don't show up in search.html
I can go into my shell and type sqs = SearchQuerySet().filter(content='content') len(sqs) and I get results. I have inspected them and when I type sqs[0] sqs[0].id sqs[0].text I get coherent results. However when I use the search form on my website, I get no results. I don't even define my own SearchView. It is the default one. On the template, I have tried {% for result in page.object_list %} {% for result in object_list %} {% for result in page_obj.object_list %} and still don't get any results. And the query did run because I can put stuff inside {% if query %} so that clearly works. What do I do? Thank you. -
How should i proceed to make a project that allow user to put their travel detail and keep track of hotel,airline,budget and schedule
As a database project, I want to make a system that allows users to put together their own little travel itinerary and keep track of the airline/hotel arrangements, points of interest, budget and schedule. -
parse and order csv file in django template
How to parse csv file into django template and sort them by: myfile.csv status, date, user, rating Registered, 12-10-2016, user1, 8.75 Registered, 22-05-2016, user2, 9.23 Registered, 19-11-2016, user3, 7.00 Currently i'm trying to do things like this: Views.py args = {} file_url = urllib2.Request("http://server.local:8000/static/myfile.csv", None, {'User-Agent': 'Mozilla/5.0'}) file_url_response = urllib2.urlopen(file_url) pre_reader = csv.reader(file_url_response) args['list'] = pre_reader return render_to_response('template.html', args) template.html {% for row in list %} <p> {% for item in row %} {{ item }} {% endfor %} </p> {% endfor %} Rendered HTML response is: status, date, user, rating Registered, 12-10-2016, user1, 8.75 Registered, 22-05-2016, user2, 9.23 Registered, 19-11-2016, user3, 7.00 But I want to do something like this: <table> {% for row in list %} <tr> <td> {{ row.status }} </td> <td> {{ row.date }} </td> <td> {{ row.user }} </td> <td> {{ row.rating }} </td> </tr> {% endfor %} </table> Also it would be great If I could order by values, so users can order results by date or by rating -
Error while running simple django app
knysys@kshahidLT ~/Desktop/firsrproject $ python manage.py runserver Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/knysys/Desktop/firsrproject/firsrproject/urls.py", line 22, in url(r'^', include('marcador.urls')), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/knysys/Desktop/firsrproject/marcador/urls.py", line 6, in name='marcador_bookmark_user'), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/init.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). -
Image is not uploaded from form django
My Views def apost(request): if request.method =='POST': form = APostForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.slug = slugify(form.title) form.save() return redirect('apost') else: form = APostForm() template_name = 'dadmin/form.html' items = Post.objects.all() context = {'title':'Add Post','form':form,'items':items} return render (request, template_name, context) My Form class APostForm(forms.ModelForm): class Meta: model = Post fields = {'title','photo','content'} Models photo = models.ImageField(upload_to='images') No Image uploaded is Accepted Photo is selected but when Click save. It shows this field is required error. I had searched through the questions here but request.FILES solves others problems but not mines. Whats wrong? -
Django-bootstrap tree click event
How to write a click event for a particular node of a bootstrap tree in django? if following is my treeview how to display a list while clickin the node 'processareafilter'? context = dict() organization = Organization.objects.all() orglocations = Orglocations.objects.all() locationprocessarea = Locationprocessarea.objects.all() processareaasset = Processareaasset.objects.all() processtaglink = Processareaassettaglink.objects.all() context["TreeStructure"] = [ { 'text': organizations.name, 'nodes': [ { 'text': orglocationss.name, 'nodes': [ { 'text': processarea.name, 'nodes': [ { 'text': processasset.name, 'nodes': [{ 'text': processareafilter.name, 'nodes': [{ 'text': taglink.name }for taglink in processtaglink.filter(areaassetid=processareafilter.id)] }for processareafilter in processareaasset.filter(parentassetid=processasset.id)] } for processasset in processareaasset.filter(processareaid=processarea.id).filter(parentassetid__isnull=True)] } for processarea in locationprocessarea.filter(locationid=orglocationss.id)] } for orglocationss in orglocations.filter(organizationid_id=organizations.id)] } for organizations in organization.filter(id=1)] return { "tree_view": context } -
Matching one-or-more keywords with Django's Postgres full-text searching
If I search on a website with multiple keywords (and no quotes) -- such as for red car -- my expectation is that items containing "red car" exactly should be first, followed by items containing both keywords (but non-sequentially), followed by items containing one of the keywords. (I believe this is the default behavior in Lucene-like systems, but it's been a while since I've used them, so can't say for sure.) My hope was that the Postgres full-text searching would automatically do this, but my early tests show this is not the case: ## ASSUME: items in database: <blue car>, <green car>, <red truck> keywords = "red car" items = ForSaleItem.objects.filter(name__search=keywords) ## RESULT: items is empty/None, whereas it should have each of ## the items since one keyword matches. The hack I'm seeing is to using Django's disjunction operator, but I'm hoping there is something less-hacky. I'm also pretty sure this hack wouldn't put exact matches at the top of the list. Here's the hack: from django.db.models import Q keyword_query = Q() for keyword in keywords.split(' '): keyword_query.add(Q(name__search=keyword), Q.OR) items = ForSaleItem.objects.filter(keyword_query) Is there some settings/API that I'm missing (or something implementable on the postgres side) that gets the functionality … -
Deploying Django Channels with Daphne + NGINX using SSL
I had a working configuration of nginx proxying to an upstream daphne server for django channels. However, when I moved my site to ssl, I started running into issues 403 errors with the websocket requests. This is from my error log: None - - [24/Apr/2017:02:43:36] "WSCONNECTING /pulse_events" - - None - - [24/Apr/2017:02:43:36] "WSREJECT /pulse_events" - - 2017/04/24 02:43:37 [info] 465#465: *10 client 69.203.115.135 closed keepalive connection And from the access log: - - [24/Apr/2017:02:48:54 +0000] "GET /pulse_events HTTP/1.1" 403 5 "-" "-" - - [24/Apr/2017:02:49:03 +0000] "GET /pulse_state/ HTTP/2.0" 200 1376 "-" "Pulse/1 CFNetwork/811.4.18 Darwin/16.1.0" My nginx config is as follows: upstream pulse_web_server { server unix:/home/pulseweb/run/gunicorn.sock fail_timeout=0; } upstream pulse_web_sockets { server unix:/home/pulseweb/run/daphne.sock; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name backend.com; return 301 https://$host$request_uri; } server { listen 443 http2 ssl; server_name backend.com; root /var/www/vhosts/backend.com; location ~ /.well-known { allow all; } include snippets/ssl-params.conf; ssl_certificate /etc/letsencrypt/live/backend.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/backend.com/privkey.pem; client_max_body_size 4G; access_log /var/log/nginx/pulse-access.log; error_log /var/log/nginx/pulse-error.log info; location /static/ { alias /var/www/vhosts/backend.com/static/; } location /pulse_events { proxy_pass http://pulse_web_sockets; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location / { proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host … -
HTTP Request Testing in Pytest
So I am very new to coding in general and I have written the following code to pass HTTP requests to Python/Django methods to test them with Pytest: import django django.setup() from login.views import delete_song, delete_playlist, create_song, logout_user, add_preferences, create_playlist, detail, login_user from django.shortcuts import render, get_object_or_404 from login.models import Playlist from django.test import TestCase from django.test import Client class test_songs(TestCase): def setUpClass(self): self.client = Client() self.post = ('POST /docs/index.html HTTP/1.1 Host: www.nowhere123.com Accept: image/gif, image/jpeg, / Accept-Language: en-us Accept-Encoding: gzip, deflate Content-Type: application/json User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) (blank line) {"foo": "bar"}') def test_login_pass(self): assert login_user(self) == render(self, 'index.html', {'playlists': Playlist.objects.filter(user=self.user)}) def test_login_fail(self): assert login_user(self) == render(self, 'login.html', {'error_message': 'Invalid login'}) def test_create_playlist(self): assert create_playlist(self) == render(self.post, 'create_playlist.html', context) def test_create_song(self): assert create_song(self,111) == render(self, 'detail.html', {'playlist': get_object_or_404(Playlist, pk=111)}) def test_add_preference(self): assert add_preferences(x, 111) == render(x, 'add_preferences.html', context) def test_delete_song(self): assert delete_song(x,111,222) == render(x,'detail.html', {'playlist': get_object_or_404(Playlist, pk=111)}) def test_detail(self): assert detail(self, 111) == render(self, 'detail.html',{'playlist': get_object_or_404(Playlist, pk=111), 'user': self.user}) def test_detail_not_auth(self): assert detail('nonuser', 111)== render('nonuser', 'login.html') def test_delete_playlist(self): assert delete_playlist(x, 111) == render(x, 'detail.html', {'playlist': Playlist.objects.get(pk=111)}) def test_logout_user(self): assert logout_user(x) == render(x, 'login.html', context) but I keep getting the error when running them: TypeError: setUpClass() missing … -
Django form in a base class
forms.py class search_form(forms.Form): options = categories.objects.all() category = forms.ModelChoiceField(options, initial={'All':'All'}, label='') search = forms.CharField(max_length=100, label='', required=False) This form is used for searching for items. And right now I have it implemented on the index page and it works as expected. The index (home) page has its own view that makes use of this form, but I have a base template (base.html) that every page on the site extends. The base template holds the menu bar and the footer of the site. I need to add the form to the base class and have it function in every template that extends it. Is there a way to do this?