Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run Django project locally for Heroku
I have a Django project and the structure is as following, Inside the Procfile, I have this code, web: gunicorn team-app.wsgi --log-file - This is the requirements.txt, appdirs==1.4.3 coreapi==2.3.0 coreschema==0.0.4 dj-database-url==0.4.2 Django==1.11 django-allauth==0.31.0 django-rest-auth==0.9.1 django-rest-swagger==2.1.2 djangorestframework==3.6.2 gunicorn==19.7.1 itypes==1.1.0 Jinja2==2.9.6 MarkupSafe==1.0 oauthlib==2.0.2 openapi-codec==1.3.1 packaging==16.8 pyparsing==2.2.0 python-openid==2.2.5 pytz==2017.2 requests==2.13.0 requests-oauthlib==0.8.0 simplejson==3.10.0 six==1.10.0 uritemplate==3.0.0 whitenoise==3.3.0 env is the virtualenv installed locally. When I enter in the root folder, team-app and run the command heroku local web, I get the following error, How to solve this issue? -
How to calculate the sum of a property
Hello everyone here is my question: models.py class Plant(models.Model) nominal_power = models.PositiveIntegerField() module_nominal_power= models.PositiveIntegerField() @property def no_modules(self): return round(self.nominal_power*1000/self.module_nominal_power) views.py def home(request): plants = Plant.objects.filter(user=request.user) total_power = plants.aggregate(sum=Sum('nominal_power')) total_no_modules = plants.aggregate(sum=Sum('no_modules'))['sum'] template = 'data/home.html' context = {'plants':plants, 'total_power':total_power, 'total_no_modules':total_no_modules} return render(request, template, context) And I get the error Cannot resolve keyword 'no_modules' into field.Cannot resolve keyword 'no_modules' into field. I undestand the meaning of the failure but how can I get the total number? -
How to pass parameters to ListView?
How to pass variables from done() to ListView? done() method of some object: def done(self) ... min_amount = 100 max_amount = 500 return redirect(reverse('board:search-result')) urls.py: ... url(r'^results$', SearchAdvertResultView.as_view(), name='search-result', ), ... views.py: ... class SearchAdvertResultView(ListView): template_name = "board/search_results.html" def get_queryset(self): return Adverts.objects.filter(amount__range=(min_amount, max_amount)) ... -
ImportError: No module named caching.base
I am running a project in django and I get this error: ImportError: No module named caching.base when django try to run this code: from caching.base import CachingManager, CachingMixin what should I do? what package should I install? -
filter by default with now() and earlier djangorestframework
I'm passing date parameters from angualrjs controller to my restapi, now the date parameter is not specified so I need to filter by default with now() and earlier on parameter which I'm sending to restapi so if I'm understanding correctly filter should be in the get function on the view, probably, like I said probably because I'm in a dilemma on this one, and asking from someone to explain to me how can I do this. You can check my controller and view down bellow. app = angular.module 'cms.sales' app.controller 'FilterContactsListCtrl', ['$scope', '$http', ($scope, $http) -> savedSuccessMessage = "Contact leads list was updated" savedFailMessage = "Failed to update contact leads list" $scope.selectDate = null $scope.init = (nextSelectedDate)-> if nextSelectedDate $scope.selectDate = nextSelectedDate else $scope.selectDate = "" $scope.doAction = () -> data = { select_date: $scope.selectDate } $http.post("/api/sales/lead_contact/", data).then( nextContactListUpdateSuccess, nextContactListUpdateFailed ) nextContactListUpdateSuccess = ()-> ClientNotifications.showNotification("Success", "Contact Leads list page was updated", "success") nextContactListUpdateFailed = () -> ClientNotifications.showNotification("Alert", "Failed to update contact leads list page", "alert") ] ModelViewSet: class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('vinclucms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('cms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) return queryset # rest of the view below ..... -
Getting Error when create superuser "TypeError: 'is_staff' is an invalid keyword argument for this function"
I am trying to create superuser with this command on linux: python manage.py createsuperuser I also tried with sudo. It gives the error to me . Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 168, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 149, in _create_user user = self.model(username=username, email=email, **extra_fields) File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/base_user.py", line 68, in __init__ super(AbstractBaseUser, self).__init__(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 555, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) TypeError: 'is_staff' is an invalid keyword argument for this function Please Let me know if anybody knows the solution of this problem. Thanks -
Bootstrap-django click event for a particular node
How to write a onclick event for a particular node in a bootstrap tree?? Following is my treview def get_context_data(self, **kwargs): 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, 'tags':[orglocationss.name], 'nodes': [ { 'text': processarea.name, 'tags':[processarea.name], 'nodes': [ { 'backcolor': ["red"], 'text': processasset.name, 'tags':[processasset.name], 'nodes': [{ 'text': processareafilter.name, 'tags':[processareafilter.name] }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 } How to write click event for processareafilter. Expecting for help..Thanks!! -
Set model's field via onlick (django)
first of all, sorry for my english :D this is my code: models.py class Photos(models.Model): username = models.CharField(max_length=50) caption = models.CharField(max_length=150, blank=True, null=True) img = models.ImageField(upload_to = 'userProfile/static/img', null=True, blank=True) update_date = models.DateTimeField(default=timezone.now) category = models.CharField(max_length=50, blank=True, null=True) likes_count = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'photos' and this is a part of html code that my js code produces <div class="container_card"> <img class="container_card_image" onclick="..." src="/static/img/1/uploads/img1.jpg"> </div> I want that when you click on the image, 'likes_count' is incremented without refresh the page (like instagram or like all social network). Then, if i use <a href="{% url 'like' value=user.id %}> <img ...> </a> and a view defined in this way, it increases the likes_count but is not good because it refesh the page for each click urls.py urlpatterns = [ ... url(r'^(?P<value>\w+)$', views.like, name='like'), ] views.py def like(request, value): photo = Photos.objects.get(pk=value) photo.likes_count += 1 photo.save() return redirect('home') Is there a way to get what I want? -
django content type getting two values
hello im trying to make a comment section for my blog. im struggling with the content_type a bit. here is my views.py (there is a second form but I cut it ou so its not to long) def mypost(request, slug=None): instance = get_object_or_404(Post, slug=slug) share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } comment_form = CommentForm(request.POST or None, initial=initial_data) if comment_form.is_valid(): c_type = comment_form.cleaned_data.get("content_type") #print ('type: ',c_type) content_type = ContentType.objects.get(model=c_type) obj_id = comment_form.cleaned_data.get("object_id") content_data = comment_form.cleaned_data.get ("content") new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data, ) comment = instance.comment context = { "title": instance.title, "instance": instance, "share_string": share_string, "articles": articles, 'form': form, 'comment':comment, "comment_form":comment_form } return render(request, "my_profile/mypost.html", context) and in my Post model I have this @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) print('the content type is: ',content_type) return content_type it all seems to work also the print values give me the right answers but when I try to upload a comment I get get() returned more than one ContentType -- it returned 2! so this line in views content_type = ContentType.objects.get(model=c_type) is causing the problem somehow but I don't know where the problem is. when I … -
solving from django by example, i wanted post by slug not by date
i am beginner in django, i am solving problem from django by example, i wanted post by slug not by date so made couple changes, example localhost:8000/blog/slug models.py class Post(models.Model): STATUS_CHOICES=( ('draft','Draft'), ('published','Published') ) published = PublishedManager() #Post title title=models.CharField(max_length=250); #slug is intended for used in url slug can be used for the date and slug #for post slug=models.SlugField(max_length=250,unique_for_date='publish') #author used to define many to one relationship post is written by user and user can wrote many post author=models.ForeignKey(User,related_name='blog_post') #body of post body=models.TextField() #publish is datetime publish=models.DateTimeField(default=timezone.now) #created is indicate for when the post is created date will save automatically as we creating object created= models.DateTimeField(auto_now_add=True) #updated ia indicate when lat time post is updated updated=models.DateTimeField(auto_now=True) #show status of post we use choices parameter Status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') objects = models.Manager() # The default manager. def get_absolute_url(self): #return reverse('blog:post_detail',args=[self.publish.year,self.publish.strftime('%m'),self.publish.strftime('%d'),self.slug]) return reverse('blog:post_detail1',args=[self.slug,]) class Meta: ordering=('-publish',) def __str__(self): return self.title class comment(models.Model): post = models.ForeignKey(Post,related_name='comments') name=models.CharField(max_length=80) email=models.EmailField() body=models.TextField() created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now=True) active=models.BooleanField(default=True) class Meta: ordering =('created',) def __str__(self): return 'comment by {} on {}'.format(self.name,self.post) urls.py url(r'^(?P<post>[-\w]+)/$',views.post_detail1,name='post_detail1') views.py def post_detail1(request,post): #post = get_object_or_404(Post,slug=post,Status='published',publish_year=year,publish_month=month,publish_day=day) post = get_object_or_404(Post, slug=post,Status='published') comments=post.comments.filter(active=True) if (request.method=='POST'): #A comment was posted comment_form=CommentForm(data=request.POST) #if comment_form is valid create the commnet but dont push in database … -
Django redirects with languages and urlresolvers.reverse
I'm trying to test a redirect to a login page but my desired expected test condition can't match the response.location because of the language settings. For example, I want to do the following. self.assertRedirects(response, "{0}?next={1}".format(reverse('auth_login'), reverse('profile')), status_code=302, target_status_code=302) but the error is AssertionError: Response redirected to '/accounts/login/?next=/en/profile', expected '/en/accounts/login/?next=/en/profile' I don't know what the best practice is for this? Should I: Hard code the expected url to '/accounts/login/?next=/en/profile' which is what seems to be implied by the django docs. Make a custom reverse_no_il8n as suggested here that uses regex to chop off the language code from urlresolvers.reverse Something else? -
Online judge system Django
I did web-site by using django. I want to add online judge system to my web-site. User send solution (cpp, java and other files) via my site like a codeforces.com and other. How to do it? -
Getting Primary Key from database (Python / Django)
I'm trying to use Hashids which works when I manually input the number to encode, but doesn't work if I try to get it to encode the Primary Key from each table row. models.py from hashids import Hashids from django.db import models class AddToDatabase(models.Model): hashids = Hashids() slug = models.CharField(default=hashids.encode(pk), max_length=12) The above says pk is undefined, regardless of what I try to import. -
Dajngo form widgets and the choice is not one of available choices
Hello friends, I want to ask you for help. I'm trying to change the default value of the "true / false" checkboxes to another. Unfortunately. I recive a form error: “the choice is not one of available choices”. Please tell me what have I done wrong ? models.py CHECKBOX_CHOICES = (('1', 'The first choice'), ('2', 'The Second Choice')) class Order(models.Model): paid = models.CharField(max_length=350, choices=CHECKBOX_CHOICES) forms.py from django import forms from .models import Order class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['paid'] widgets = { 'paid': forms.CheckboxSelectMultiple() } create.html <form action="." method="post" class="order-form"> {{ form.as_ul }} <p><input type="submit" value="Submit"></p> {% csrf_token %} </form> rendered html <ul id="id_paid"> <li><label for="id_paid_0"><input type="checkbox" name="paid" value="" checked="" id="id_paid_0"> ---------</label> </li> <li><label for="id_paid_1"><input type="checkbox" name="paid" value="1" id="id_paid_1"> The first choice</label> </li> <li><label for="id_paid_2"><input type="checkbox" name="paid" value="2" id="id_paid_2"> The Second Choice</label> </li> </ul> It's important to me, even though it's a little thing, Any hints or suggestions would be welcome. -
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 …