Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail 2.2.2, django 2.1.1 compatibility issues
Wagtail github site says that wagtail is compatible with django 2.1.x. I am trying to setup a project with pipenv. When I install wagtail via pipenv it installs django version 2.0.8 If I try to update django to 2.1.1 console gives: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. Could not find a version that matches django<2.1,==2.1.1,>=1.11 Besides the error it installs django 2.1.1. But then when I runserver... I get error: AttributeError: module 'django.contrib.auth.views' has no attribute 'login' So is wagtail 2.2.2 compatible with django 2.1.x ? -
How can I dynamically change the storage of Django FileField()?
Basically I got the following model where some uploaded documents will be public and some others private. To decide when the doc is private or not, when creating the instance, I set the field is_public=True/False, then I will be able to choose the right direction within the AWS S3 bucket. So I want to be able to change the storage to PrivateMediaStorage() when is_public=False from my_project.storage_backends import PrivateMediaStorage class Document(models.Model): file = models.FileField(upload_to="uploaded_documents/%d-%m-%Y") # file = models.FileField(upload_to="uploaded_documents/%d-%m-%Y", # storage=PrivateMediaStorage()) uploaded_by = models.ForeignKey(UserProfile,blank=True,null=True) nb_download = models.IntegerField(default=0) is_public = models.BooleanField(default=False) Here is the storage class in case it's important. from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False -
trouble loading a simple hello world on django 2.1
I'm entirely new to Django. Here I'm trying to create my first project following every detailed step mentioned in here. But yet I face this error by entering http://localhost:8000/polls/ : using the urlconf defined in mysite.urls, django tried these url patterns, in this order: 1. admin/ I was wondering if any of you guys ever encountered the same or have something to say about it. Thanks. -
Highlighted post in Django templates
I've created this model: class PostModel(models.Model): post_title = models.CharField(max_length=70) post_short_description = models.TextField(max_length=200) post_contents = models.TextField() post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_author = models.ForeignKey(AuthorModel, on_delete=models.CASCADE) post_keyconcept = models.ManyToManyField(KeyConceptModel) slug = models.SlugField(verbose_name="Slug", unique="True") post_highlighted = models.BooleanField(default=False) def __str__(self): return self.post_title def get_absolute_url(self): return reverse("singlepostManuscriptusView", kwargs={"slug": self.slug}) class Meta: verbose_name = "Articolo" verbose_name_plural = "Articoli" I want use post_highlighted for put in a div only the article or the articles that have response true. How I can set up the "for cicle"? Here there is the cicle for show the list of posts: {% for posts in object_list %} <div id="bloghome" class="container"> <h1><a href="{{ posts.get_absolute_url }}">{{ posts.post_title }}</a></h1> <p>{{ posts.post_short_description|safe|linebreaks }}</p> <p>Pubblicato il <strong>{{ posts.post_publishing_date|date }}</strong></p> <h5>Keywords:</h5> {% for keyword in object_list.all %} <button type="button" class="btn btn-outline-warning btn-sm">{{ keyword }}</button> {% endfor %} </div> <hr> {% empty %} <h1>Go to the admin panel and create your first post!</h1> {% endfor %} -
Django - how to create membership models with foreign keys and manytomanyfield
I am trying to create a django membership models with 2 model classes: Target and Group. I want to have targets attributable to certain groups, but also to be able to query which targets are in which group. This is what I have so far and I am able to see that "targets" is a field of Group but it shows up as empty in the query set when I access Group.objects.get(pk=1) through a variable. I also want both groups and targets to be attributable to certain users. Here are my models, what am I doing wrong? I've tried doing this a few different ways so far: class Target(models.Model): first_name = models.CharField(max_length=50, default='Target First name') last_name = models.CharField(max_length=50, default='Target last name') email = models.EmailField(max_length=100, default='email@example.com') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) date_time = models.DateTimeField(auto_now=True) group = models.ForeignKey(Group, on_delete=models.DO_NOTHING, null=True, blank=True) def __str__(self): return self.email def __unicode__(self): return self.email class Group(models.Model): group_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50, default='Group name') created_date = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(null=True, blank=True) targets = models.ManyToManyField(Target, related_name='targets', blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) def __str__(self): return self.name def __unicode__(self): return self.name -
Using django-filter with django-tables2, how do I annotate a queryset?
I am using django-filter and django-tables2 to pull data from a SQLite3 database. The database has 15+ fields of sales order information were they may be multiple lines (Line field) per sales order. I would like to render a table that does the equivalent of 'Group By' sales order and sum the ExtAmount field. I know I should use the annotate function but I am unsure where to implement this with django-filter/django-tables2. In SQL I used the below to get what I need: SELECT SalesOrder, Customer, Count(Line) AS Lines, Round(Sum(ExtAmount), 2) AS Amount FROM backlog_backlogData GROUP BY SalesOrder Order By Sum(ExtAmount) DESC limit 100 As of now, the view renders the three fields from tables.py but without grouping SalesOrder. Which is great, but I can't seem to find traction of where I need to annotate. I've read through the docs and searched through other questions and I just can't seem to understand how to use django-filter/django-table2. The only place I have found 'annotate' referenced in the django-filter docs is with the ModelMultipleChoiceFilter filter reference. Any help would be great! #models.py from django.db import models class backlogData(models.Model): Shipto = models.IntegerField() Customer = models.CharField(max_length=200) City = models.CharField(max_length=200, null=True) ST = models.CharField(max_length=200, null=True) … -
Static files in Django 1.8
My static files are inside the main django folder (BASE_DIR). It works fine, until I turn off the DEBUG. The error occurs because the 'static' function returns empty if the DEBUG is off. What should I do to work around this problem when settings.DEBUG=False? Thanks any help. urls.py urlpatterns = [ url(r'^$', redirect), url(r'^webContextRoot/', include(base)), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True STATIC_URL = '/riserweb/static/{version:}/'.format(version=VERSION) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'resources/static'), ) -
Django choking on special character in model name
I'm using a legacy MSSQL database with my Django application, and one of the column names contains a "%". As a result, Django is looking for a format variable whenever the model is called. I've isolated the issue to know it breaks on this field within my model: fg_field = models.DecimalField(db_column="FG%", max_digits=15... And the error message I get is: sql = sql % tuple('?' * len(params)) TypeError: not enough arguments for format string When I note out this field in the model, the application works fine... so I know it has to do with this naming convention. Can I do anything on the Django side to stop this from happening? -
Where to insert data into a django form before validation?
I have a modelForm created from a Model: class Client(models.Model): name = models.CharField(max_length=30) domain_url = models.CharField(max_length=128, unique=True) schema_name = models.CharField(max_length=63, unique=True, validators=[_check_schema_name]) I am not showing the schema_name for editing, as I want this to be automatically generated somewhere between form submission and validation. class SetupForm(forms.ModelForm): '''Setup form for the new instance domain_url and schema_name are charfield ''' class Meta: model = Client fields = ['name', 'domain_url', ] I want to modify the domain_url and create a schema_name from it. I still want the regular form validations to run though. So where can I add the schema_name to the data for cleaning? -
Prepopulating fields of user edit form (also: passing {{user}} into a javascript function?)
Basically, I'm trying to make an edit profile modal with fields that are already prepopulated by the user's original data. I passed django models into my javascript files by using these brackets {{}} but it doesn't seem to work for {{user}} (as in request.user). This is what I did for simple fields: <div class="field"> <label>Email</label> <input value={{user.email}} type="email" name="email" placeholder="Email"> </div> {{user.email}} successfully is set as the default value for the input. Is there a different way to prepopulate fields? If there is, let me know and I might not have to deal with this next situation. My naive solution works for text fields but if I have a multiselect like: <div class="field"> <label>Native Language</label> <select name="nativelanguage" id="nativedrop" class="ui fluid search selection dropdown"> <option value="">Language</option> <option value="English">English</option> <option value="Spanish">Spanish</option> <option value="French">French</option> </select> </div> my solution no longer works. I want to pass {{ user }} into a javascript function like myFunction({{ user }}) but it seems that this is not possible. Could anyone give me advice on how to prepopulate fields or fix the second issue below? Thanks! -
Kerberos Double Hop Delegation with Django on IIS
I need to pass the credentials (Integrated Windows Authentication) from a django website on IIS onto a backend SQL server so that it runs under the proper user context. This is how my setup looks so far: Running SQL Server on sql_sever.domain.com under a service account domain\svc_sqlserver Running Django website on app_server.domain.com using IIS under a service account domain\svc_appserver with Windows authentication and ASP.Net Impersonation (Providers is set to Negotiate:Kerberos -> Negotiate -> NTLM ) with useAppPoolCredentials=True Connecting to SQL server from django using Windows authentication by setting Trusted_Connection=yes in the connection Configured SPNs for Kerberos authentication both for SQL Server and IIS as follows setspn -a HTTP/app_server domain\svc_appserver setspn -a HTTP/app_server.domain.com domain\svc_appserver setspn -a MSSQLSvc/sql_server.domain.com:PORT domain\svc_sqlserver setspn -a MSSQLSvc/sql_server.domain.com:INSTANCE domain\svc_sqlserver setspn -a MSSQLSvc/sql_server.domain.com domain\svc_sqlserver Trusted both svc_sqlserver and svc_appserver for delegation to MSSQLSvc services and additionally for domain\svc_appserver I added HTTP services too (from the above list) Result: Kerberos authentication works on SQL Server. Confirmed by looking at auth scheme of connected users Kerberos authentication works on Django website. Confirmed by inspecting WWW-Authenticate response header and Authorization request header (Negotiate is being correctly used) Sql server runs only under the context of domain\svc_appserver when it should be running under … -
SSL manage.py runserve 0:8000
I am running code manage.py runserve 0:8000 but I would like to display it as https. I'm using nginx . I have installed the certificate in the appropriate folders in nginx. I can see the secured nginx default page when I browsed to mywebsite.com (without port 8000) but I get a blank page when I add port 8000 to it. I have tried multiple options below but still unable to get mywebsite:8000 to work on secured ssl page. Any thought? Below are what I have tried so far manage.py runserver_plus 2.manage.py sslserver 3.All sort of Django extensions -
Django SQLite3 to PostgreSQL - duplicate key error on OnetoOne User Model
I'm having some trouble with migrating from SQLite3 to Postgres on Django. Essentially I'm following this thread (Django: What are the best practices to migrate a project from sqlite to PostgreSQL). There's been a similar error that I've used the TRUNCATE command on and got past, but now I'm hitting a duplicate key error for my own model. The model client is a OnetoOne relationship with Django's built in user. It just asks for a few additional details like business type and join date. And the migration is coming up with an error. The client, primary key 1 is my superuser with code: user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, blank=True) And I'm getting this error: django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\*******\dump.json': Could not load clauses.Client(pk=1): duplicate key value violates unique constraint "clauses_client_clientusername_id_******_uniq" Could someone point me the right way? Thanks! -
Editing an object with HTML form instead of Django model form
I am trying to edit my objects using HTML form instead of Django model form. I need to know how to make the view for this (See my incomplete view below in bold) Intro: I have a very simple html (invisible )form in the right column of my Index.html. when the user clicks on Locate me button. The form automatically fills the users latitude and longitude details and clicks submit(the user does not see the form). I use jQuery to achieve this <form method="post" action="#"> <input id="jsLat" type="text" placeholder="latittude" name="LAT"> <input id="jsLon" type="text" placeholder="longitude" name="LON"> <button type="submit" id="submit">Submit</button> </form> My models are class UserLocation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) lat = models.FloatField(blank=True, null=True) lon = models.FloatField(blank=True, null=True) point = models.PointField(srid=4326, default='SRID=4326;POINT(0.0 0.0)') My incomplete view(I need help completing this) @login_required def edit_location(request): if request.method == 'POST': form = ??????????? #don't know how to call the HTML form lat = request.POST.get('LAT') #lat is a field in the model see above lon = request.POST.get('LON')#lon is a field in the model see above form.save(commit=False)(# Not sure if I can use this with HTML form) point = lat (some operation) lon form.save() return redirect("home") -
syntax error in urls.py when calling sitemaps
been looking for a solution for this for the past hour and I'm at a loss. Everything looks correct but I keep getting a syntax error. my code: from django.conf.urls import include, url from django.contrib import admin from django.contrib.sitemaps.views import sitemap from blog.sitemaps import PostSitemap sitemaps = { 'posts' : PostSitemap } urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'blog/', include('blog.urls')), url(r'^tinymce/', include('tinymce.urls')) url(r'^sitemap\.xml$', sitemap, {'sitemaps':sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] the error: File "/home/cliff/environments/djablog/mysite/mysite/urls.py", line 29 url(r'^sitemap\.xml$', sitemap, {'sitemaps':sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ^ SyntaxError: invalid syntax -
TypeError at /admin/auth/user/
I get such an error when I try to delete a user from admin panel TypeError at /admin/auth/user/ 'bool' object is not callable models.py class PROFILE(models.Model): kullanıcı = models.OneToOneField(User,on_delete=True) birthday = models.DateField(verbose_name="Birthday", blank=False,null=False) gender = models.CharField(max_length=15, blank=False,null= False,choices=gender) language = models.CharField(max_length=20, blank=False,null=False, verbose_name="language",choices=languages) def set_token(self): self.token = ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789') for i in range(15)]) def save(self, *args, **kwargs): super(PROFILE, self).save(*args, **kwargs) self.set_token() class Meta: verbose_name_plural = 'PROFILE' ordering= ["id"] def __str__(self): return "{}".format(self.kullanıcı.username) class Q(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) ... class Meta, __str__ .... Firstly 'kullanıcı' was 'user' but I changed because of the possibility of conflict django. But still I have a this problem -
Trying to make it work Regex/url/views on Django
I'm new with Python and Django and I'm trying to make a url regex using PyCharm, but I have no clue why it doesn't work. I have this example... from django.contrib import admin from django.urls import path from .views import (home, client_detail,) urlpatterns = [ path(r'^$', home), path(r'^/cliente/(?P<id>\d+)/$', client_detail), path(r'admin/', admin.site.urls), ] And I have a views.py that has the below code inside it: from django.http import HttpResponse def home(request): return HttpResponse('HOME') def client_detail(request, id): return HttpResponse(id) The question is: When I write path(r'^/cliente/(?P<id>\d+)/$', client_detail) instead path(r'/cliente/<id>', client_detail), I receive the print error below Can someone please tell me what I'm missing? Thanks in advance! :) Error -
How To Define A Docusign Event/Envelope Notification Python API
For my company, I've been creating a webapp that will make the creation and signing of a letter of agency easier. I am almost completely finished with it. However, the only issue that I am experiencing is that, after the envelope is created, the email is never received by the recipient asking for the signature. I have checked under docusign's manage tab, and the envelope is listed there, with the correct recipient email address. I've attempted to resend it multiple times, and the email is still never received, although it's listed as being sent. The code that I'm using is as follows: username = "myDocusignUsername" integrator_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" base_url = "https://demo.docusign.net/restapi" oauth_base_url = "account-d.docusign.com" redirect_uri = "http://myredirecturi" private_key_filename = "path/to/pKey.txt" user_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" client_user_id = 'recipient@gmail.com' # Add a recipient to sign the document signer = docusign.Signer() signer.email = "recipient@gmail.com" signer.name = "Recipient Name" signer.recipient_id = '1' signer.client_user_id = client_user_id sign_here = docusign.SignHere() sign_here.document_id = '1' sign_here.recipient_id = '1' sign_here.anchor_case_sensitive = 'true' sign_here.anchor_horizontal_alignment = 'left' sign_here.anchor_ignore_if_not_present = 'false' sign_here.anchor_match_whole_word = 'true' sign_here.anchor_string = 'Signature of individual authorized to act on behalf of customer:' sign_here.anchor_units = 'cms' sign_here.anchor_x_offset = '0' sign_here.anchor_y_offset = '0' sign_here.tab_label = 'sign_here' sign_here.IgnoreIfNotPresent = True; tabs = … -
How can i trigger a Python script in background from HTML tag button, in Django?
please how can i run a python script from my django plateform? like i have a custom html page and i have a button tag () from which i would like to trigger the python code i've written on PDF's (wonderful parser). Actually, if the user of this app clicks on this parse it button, i triggers my python script stored in my static folder, and prints back the extracted texts and images in the table below: I greatly need your helps and possible ideas. Thanks before ! -
django: customizing related_name='%(class)s' to use an underscore in beween two words
I have an abstract model and two child models such as: class Invoice(models.Model): user = models.ForeignKey("User", related_name='%(class)s') class Meta: abstract=True class SaleInvoice(Invoice): field_sale = models.CharField(max_length=255) class PurchaseInvoice(Invoice): field_purchase = models.CharField(max_length=255) Now the reverse name for the child models would be saleinvoice and purchaseinvoice. But what I need is sale_invoice and purchase_invoice. How to achieve this? An underscore in between CamelCase. -
How to add a label to a Django admin field
I am trying to add some helper text to the admin for data entry people who will take over. Something like: "Check the dropdown for a category before adding a new one." Is django admin customization capable of doing this? -
Docker SDK for Python not running in my dockerized Django app
I'm working in a Django project, and I want to use the Docker SDK for Python to create some services. My django app is dockerized, it's a clone of this repository. This is the Dockerfile: FROM python:3.6.0 RUN wget http://rubies.travis-ci.org/ubuntu/14.04/x86_64/ruby-2.3.1.tar.bz2 \ && tar xvjf ruby-2.3.1.tar.bz2 \ && cp -rp ruby-2.3.1/* /usr/local/ \ && rm -rf ruby-2.3.1.tar.bz2 ruby-2.3.1/ RUN mkdir /code WORKDIR /code RUN easy_install -U pip RUN pip install -U pip setuptools ADD requirements.txt /code/requirements.txt RUN pip install -r requirements.txt And this is the docker-compose file: version: "2" services: postgres: extends: file: base.yml service: postgres app: extends: file: base.yml service: app environment: - DJANGO_SETTINGS_MODULE=service.settings.dev command: python manage.py runserver_plus 0.0.0.0:8000 build: args: - DJANGO_ENV=dev links: - postgres ports: - "8000:8000" I have added docker==3.5.0 to the requirements file. After to run the commands docker-compose build and docker-compose up I have the django project running perfectly. My problems start when I try to follow the steps described here, after the installation of the [docker==3.5.0] library. import docker client = docker.from_env() client.containers.run("ubuntu", "echo hello world") When I try to run the third line, I'm getting the following error: raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', FileNotFoundError(2, 'No such file or directory')) I think that … -
Django m2m field remove method not working
I have a model: class Vote(models.Model): text = models.CharField(max_length=300) voters = models.ManyToManyField(CustomUser, blank=True, related_name="voters") voters_voted = models.ManyToManyField(CustomUser, blank=True, related_name="voted") game = models.ForeignKey(Game, on_delete=models.CASCADE) in_favour = models.PositiveIntegerField(default=0) against = models.PositiveIntegerField(default=0) def save(self, *args, **kwargs): super().save(*args, **kwargs) queryset = self.game.players for player in queryset: self.voters.add(player) And a voting form, which has the following form_valid method: def form_valid(self, form): game = Game.objects.get(id=foo) vote = Vote.objects.get(id=bar) if form.cleaned_data['choice'] == 'Y': vote.in_favour += 1 else form.cleaned_data['choice'] == 'N': vote.against += 1 vote.voters.remove(self.request.user) #This line doesn't work vote.voters_voted.add(self.request.user) vote.save() return super().form_valid(form) The purpose of this is to keep track of which users have voted, which are eligible to vote, and what the voting is (in favour/against). Everything in this code works perfectly, except for the line that removes users from the voters group when they submit the form (vote.voters.remove(self.request.user)). The following line, that adds the user to the voted group (vote.voters_voted.add(self.request.user)) works perfectly. I have tried putting a second vote.save() in between these two lines, but that didn't make any difference. I don't understand why the second line works, but the first doesn't! -
Python / Django pdfkit wkhtmltopdf UnknownContentError
I'm getting a UnknownContentError when generating a PDF document from a project URL (https://ourcodeworld.com/articles/read/241/how-to-create-a-pdf-from-html-in-django) - using pdfkit (wkhtmltopdf). pdf = pdfkit.from_url('http://127.0.0.1:8000/cb/open_detailed_research_outputs/', False, options) The URL is valid and displays the way it should in the browser. Could someone please advise where I'm going wrong. -
Django count related objects with condition
I want to filter the results before counting. In below code, I am counting the total number of workers for each Ticket Counter. class TicketCounterList(ListAPIView): queryset = TicketCounter.objects.filter(ticket_counter_is_deleted=False) .annotate(num_workers=Count('workers')) serializer_class = TicketCounterSerializer workers in the above code is the related_name from another model (Workers model). What I want to do is, I want to be able to filter workers with a condition is_deleted= True rather than counting all workers. Is it possible? I am using Django 1.11.13