Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is going wrong with my wsgi setup?
I'm trying to setup uwsgi (and nginx eventually), but right now am stuck on uwsgi. I'm getting the following error when I try to run the server normally: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? And this is the output from running command uwsgi --http :8000 --module Hellfish.wsgi: *** Starting uWSGI 2.0.17 (64bit) on [Tue Jul 3 18:34:40 2018] *** compiled with version: 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2) on 03 July 2018 20:44:01 os: Darwin-16.7.0 Darwin Kernel Version 16.7.0: Fri Apr 27 17:59:46 PDT 2018; root:xnu-3789.73.13~1/RELEASE_X86_64 nodename: Whodinis-MacBook-Pro.local machine: x86_64 clock source: unix detected number of CPU cores: 4 current working directory: /Users/whodini/Desktop/who/Web/Hellfish detected binary path: /Users/whodini/Desktop/who/Web/Hellfish/env/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 709 your memory page size is 4096 bytes detected max file descriptor number: 256 lock engine: OSX spinlocks thunder lock: disabled (you can enable it with --thunder-lock) uWSGI … -
django template filter for type value or models
I don't know how to show only one category link, since search returns both blog posts and resource posts. I made links do what they need to do, but now I have to show only link that belongs to result type. What would be solution for that in django template? Code of template(just part of code): {% for r in result %} <div class="content"> <h3 class="title-blue-slider"> <a href="{{ r.get_absolute_url }}" > {{ r.title|safe }}</a> </h3> <div class="post-entry"> <div style="font-size: 12px;"> {{ r.date|date:"jS" }} {{ r.date|date:"F Y" }} {{ r.author }} <a href="{% url 'blog:blog-category' r.category.slug 1 %}">{{ r.category }}</a> <a href="{% url 'resources:resources-list' r.category.slug 1 %}">{{ r.category }}</a> </div> {{ r.text|safe|striptags|truncatewords:52 }} </div> </div> For now I put both urls one beside other. Here is code for models.py, blog and resources respectively Blog.models from django.db import models from django.template.defaultfilters import striptags from django.template.defaultfilters import truncatewords from django.utils.encoding import python_2_unicode_compatible from dmr.models.core_models import Published, MetaData, RichText, Author @python_2_unicode_compatible class BlogAuthor(Author): about = models.TextField(blank=True) image = models.ImageField( blank=True, null=True, upload_to='authors') ADMIN_DISPLAY = ['name', 'company', 'position'] def __str__(self): return self.name @python_2_unicode_compatible class BlogCategory(Published, MetaData): title = models.CharField( max_length=250, unique=True) slug = models.SlugField( max_length=205) description = models.TextField( blank=True) ADMIN_DISPLAY = ['title', 'meta_widget', 'get_posts_count', 'published', … -
from social.apps.django_app.views import NAMESPACE
this is my first question hope ill do it well! actually am doing project using python3.6, Django==2.0.7 & thos guys:- certifi==2018.4.16 chardet==3.0.4 defusedxml==0.5.0 dj-database-url==0.4.1 Django==2.0.7 django-bootstrap3==7.0.1 django-braces==1.13.0 django-oauth-toolkit==1.2.0 django-rest-framework-social-oauth2==1.0.4 djangorestframework==3.8.2 gunicorn==19.6.0 idna==2.7 oauthlib==2.1.0 Pillow==5.1.0 psycopg2==2.7.1 PyJWT==1.6.4 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2018.5 requests==2.19.1 requests-oauthlib==1.0.0 six==1.11.0 social-auth-app-django==1.1.0 social-auth-core==1.7.0 urllib3==1.23 whitenoise==3.2.1 I got an error said:- from .oauth2_grants import SocialTokenGrant File "/Users/user/Desktop/myvirtualenv/foodtasker/lib/python3.6/site-packages/rest_framework_social_oauth2/oauth2_grants.py", line 13, in <module> from social.apps.django_app.views import NAMESPACE ImportError: cannot import name 'NAMESPACE' the question is how I can fix the issue and where I can import NAMESPACE. thanks a lot -
How can I query a ManyToMany relation table for a custom field
As can be seen in the code below, I have an intermediate model that defines a custom date field. How can I reference the date_assigned field in the relation model. I am trying find out the number of tenders that were assigned to a keyword on a particular date as per the date_assigned field in the relation model. This is final result I am aiming for. class Keywords(models.Model): keyword = models.CharField(max_length=150) class Meta: verbose_name_plural = ('Keywords') ordering = ['keyword', ] def __str__(self): return self.keyword #This is the model that stores the tender. class tender(models.Model): tenderCategory = models.ManyToManyField(category, blank=False) #this field holds the tender category, e.g. construction, engineering, human resources etc. tenderProvince = models.ForeignKey(Province, default=1, blank=False) #this is the province the tender was advertised from. keywordTags = models.TextField(blank=False) #this field holds keywords for the tender as per the tender title or as determined by the tender capturer. buyersName = models.CharField(max_length=100) #this is the name of the Buyer e.g. Dept. of Transport, Transnet, Dept of Agriculture etc. summary = models.TextField(blank=False) #this is the tender title as per the Buyer. refNum = models.CharField(max_length=100) #tender ref number as per the Buyer. issueDate = models.DateTimeField(blank=True, null=True) #date the tender was published closingDate = models.DateTimeField(blank=True, null=True) … -
Set Original Filename as default title field in Django Model
I'm using the Django Admin Site to manage my uploads. I would know if it's possible to set the original filename title as default title of an Image class. Models.py: class Multimedia(models.Model): id_multimedia = models.AutoField(primary_key=True) titulo = models.CharField(max_length=80, blank=True, null=True) descripcion = models.TextField(blank=True, help_text='Descríbeme...') path = models.FilePathField(path='media', allow_folders=True) album = models.ForeignKey(Album, on_delete=models.CASCADE) fecha_creacion = models.DateTimeField(auto_now_add=True) keyword = models.ManyToManyField('Keyword', help_text="Selecciona las palabras clave para etiquetar.") def __str__(self): return self.titulo class Imagen(Multimedia): #titulo = models.CharField(max_length=100) image_width = models.PositiveSmallIntegerField(default=640) image_height = models.PositiveSmallIntegerField(default=480) fichero_imagen = models.ImageField(verbose_name='Archivo de imagen', upload_to='files/img', width_field='image_width', height_field='image_height') thumbnail = ImageSpecField(source='fichero_imagen', processors=[ResizeToFill(600, 300)], format='JPEG', options={'quality': 60}) I want to upload an image and leave the title field blank instead of give a title. Then, set the Multimedia.titulo as the original upload filename. I have hear about prepopulated fields, but I don't know if it is possible. Thanks in advance. -
self.model() in django custom UserManager
So, I'm fairly new to Django. Notwithstanding the fact that my code works after following the Django docs 'Customizing authentication in Django', I don't get how the self.model(...) in their example actually works, where it comes from and how it functions with 'self'. This is the example found at the bottom of the docs. from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') -> user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user ... -
Python list as javascript array is adding extra text
Hi I created a python array like this urlnamesend=[] baseurlImage='https://s3.amazonaws.com/ais-django/' for i in urlname: urlnamesend.append(baseurlImage + i['image']) now I want to use this is django template in javascript but its giving some thing like this , like adding &#39 in every link . How I can get rid ? ['https://s3.amazonaws.com/Events/Test1/1.jpg&#39;, 'https://s3.amazonaws.com/Events/Test1/2.jpg&#39;, 'https://s3.amazonaws.com/Test1/3.jpg',] -
How to format the labels of choices in a choice field from a Django form?
I want to change the text shown in the choices of a Django form select Choice Field. Here's some example code: CHOICES = ( ('T1', 'Thing 1'), ('T2', 'Thing 2') ) class ExampleForm(forms.Form): field = forms.ChoiceField( widget = forms.Select(), choices = CHOICES, ) I'm not sure if any other code is required to solve the problem, but when I render this form into the template, the values of CHOICES will be shown in the choice field dropdown. What I want is to put both the key and the value as what is shown in the dropdown while still equaling the key in the back end. Like this: Field: -------------- | v| -------------- -------------- |T1 - Thing 1| |T2 - Thing 2| -------------- Is there a way to have this formatting done in the forms.py code? -
How does Django keep using the correct files when I checkout a Git branch?
How does Django and/or my webserver keep straight which files it should be using when I switch Git branches? My understanding is that when I checkout a branch in Git that the actual file system is modified. Is this true? If yes, how does Django and the webserver keep the files in tact that existed when I started the server? For Example: Create views.py on master branch return HttpResponse("<h1>Hello world!</h1>") Start server (using daphne): daphne -b 0.0.0.0 -p 9000 my_app.asgi:application my app output: Hello world! Make modifications in views.py (development branch) return HttpResponse("<h1>Thanks for Visting!</h1>") Page refresh Output does not change: Hello world! Bring down server Ctrl + C Start server (using daphne): daphne -b 0.0.0.0 -p 9000 my_app.asgi:application New Output Thanks for Visting! I understand hot reloading is a feature, but how does Django and the web server avoid using the modified files on the new branch? -
Django model choice field naming convention
What is the naming convention for the names of a choice field. class Student(models.Model): ACTIVE= 'active' INACTIVE= 'inactive' NOT_AVAILABLE= 'not-available' STATUS_CHOICES = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (NOT_AVAILABLE, 'Not available'), ) status = models.CharField( max_length=15, choices=STATUS_CHOICES , default=INACTIVE, ) What naming convention should I choose for the NOT_AVAILABLE field? not-available or not_available -
Mongodb with django using djongo?
If I use mongodb in django project with the help of djongo third-party api should I have to use commands migrate and makemigrations again n again when ever I make changes in my models?? -
Django; Is it possible to change db to other db while creating project?
I'm new to Django and I've been using default sqlite3 db for my project, but now I try to use postgreqsl for my project. I'm wondering if there's a way to switch db to other type of db while creating a project. Or do I have to dump all objects in current db? I tried to make migrations after chaning DATABASE in settings.py. -
set a default value in user form django
I need an additional default value in user form but it will not be asked from user it will be saved in every user's data by default but how can I do it? This is my form from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, min_length=6) confirm_password = forms.CharField(widget=forms.PasswordInput(), min_length=6) first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField(max_length=254) -
Show all objects in SearchQuerySet when no_query_found
I'm trying to return all objects in the SearchQuerySet whenever the user first navigates to the search page (and so has not yet entered a query). According to the docstring for no_query_found method of the SearchForm: def no_query_found(self): """ Determines the behavior when no query was found. By default, no results are returned (``EmptySearchQuerySet``). Should you want to show all results, override this method in your own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``. """ return EmptySearchQuerySet() So, following these instructions, I have tried: class MySearchForm(SearchForm): def no_query_found(self): return self.searchqueryset.all() However, this returns an empty list as a result. It seems that I'm having a similar issue to this one. I'm wondering if this has been fixed and if not what is the best way to return all objects in the relevant searchqueryset so that I can show users all results before they search. If it's useful, my view is basically: MySearchView(haystack.generic_views.SearchView): form_class = MySearchForm One more note, everything works fine when I enter a search string, so this is an isolated issue (i.e. I have run rebuild_index etc.). -
Django - pagination and sorting list
I want to make view which display list of model objects in table. I want to add sorting feature. There is possibility to do sorting like here: https://codepen.io/imarkrige/pen/vgmij in Django? I mean this Arrows in column names. Where on click is changing asc to desc. Next thing is to keep sorted table while changing page. What I did for now is sort field, but it's not saving while changing pages. My basic generic view contains: {% block pagination %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page= {{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{{ request.path }}?page={{ page_obj.next_page_number }}">next</a> {% endif %} </span> </div> {% endif %} {% endblock %} my view: class VotesList(generic.ListView): model = Vote template_name = 'votes-list.html' paginate_by = 5 def get_queryset(self): order = self.request.GET.get('orderby', 'created_date') new_context = Vote.objects.order_by(order) return new_context def get_context_data(self, **kwargs): context = super(VotesList, self).get_context_data(**kwargs) context['orderby'] = self.request.GET.get('orderby', 'created_date') return context My template: {% block content %} {% if vote_list %} <form method="get" action="{% url 'votes-list' %}"> <p>Sortuj: <input type="text" value={{orderby}} name="orderby"/></p> <p><input type="submit" name="submit" value="Zatwierdź"/></p> </form> <table id="vote_list"> <thead> <tr> … -
Python/Django. Parse html with tags
I want to write a script that takes the values of several elements from html and makes groups with these names. I decided to put elements in the html tag for easy parsing. For example: <group-item>group name 3</group-item> but I also wrote a django tag to check - is person in the group. {% if request.user|has_group:"students" %} #some #html <group-item>students</group-item> {% endif %} This tag get the user and the name of the group to whom it can be shown. My base command try to get html as string, but django tag does not allow. class Command(BaseCommand): help = 'import groups' def handle(self, *args, **options): html = render_to_string('index.html') #... variable 'html' will be without that inside on django tag. Pls help! -
How to create a unique table that is linked to another table?
I am creating a project in Django. I want to create a column that will hold a list of activities (sports, educational etc. and each with a unique id and a name) that the user took part in. -
How can you select_related on a pre-fetched model?
Is it possible to select_related models that are foreign keys of a model that you are prefetching? An example set of models: class Book(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey('Author', related_name='books') publisher = models.ForeignKey('Publisher') class Author(models.Model): name = models.CharField(max_length=50) type = models.IntegerField() # choices= omitted for brevity class Publisher(models.Model): name = models.CharField(max_length=50) And then the query: authors = Author.objects.filter(type=10) authors = authors.prefetch_related('books') # I tried both of these (but not at the same time): authors = authors.select_related('publisher') # doesn't work authors = authors.select_related('books__publisher') # also doesn't work In both cases, I get a FieldError: Invalid field name(s) given in select_related This makes sense, as neither publisher or books__publisher are associated with the starting model (Authors). But I'm not sure how to indicate I want to do a select_related on the prefetched model (Books) instead of the starting model (Author). I did look at the Prefetch objects, but I couldn't see how those would help. -
Using Django ArrayField to Store Dates and Value
I'm currently having a hard time wrapping my head around Django's Array Field. What i'm hoping to do is have an array that looks something like this: Price(close=[ [1/1/2018, 3.00], [1/2/2018, 1.00], ]) It's basically an array that stores a date followed by a corresponding value tied to that date. However, thus far my model looks like this: class Price(models.Model): close = ArrayField( models.DecimalField(max_digits=10, decimal_places=4), size=365, ) I am not certain how to create an array with two different types of fields, one DateTime, the other decimal. Any help would be much appreciated. -
nginx SSL configuration is not working
server { #listen 80; listen 443 ssl; server_name server-uat.fg.rbc.com; ssl_certificate cert\server-uat-chain.cer; ssl_certificate_key cert\server-uat_fg_rbc_com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; location / { proxy_pass http://server-uat.fg.rbc.com:3034/; proxy_read_timeout 90; proxy_redirect http://server-uat.fg.rbc.com:3034/ https://server-uat.fg.rbc.com:3034; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-for $remote_addr; port_in_redirect off; proxy_redirect off; } #location / { # return 301 https://$host$request_uri; # } } above nginx config for ssl is not working. need directions or solution to redirect user from http to https -
How to use django-guardian in customized user model
I am using django-guardian to check the user's object permission. And in my special case, I have extended user model. In my models.py I have extended user model like this: enter image description here And in my object model, I have added a Meta class for permission: enter image description here After doing makemigrations and migrate, when I run below test in python manage.py shell, it always calls the has_perm function in my user model and returns the value of that function. How do I fix this problem? Or is there any useful tutorial of how to use guardian in a customized user model? -
Radio button redirect url not working
I have two signup pages, student view, and parent view. The default signup url is on the student page http://127.0.0.1:8000/account/student-sign-up/. However, when the parent button is pressed the page redirects to an unknown url at http://127.0.0.1:8000/account/student-sign-up/parent_sign_up.html. I was wondering how to make the button redirect to just http://127.0.0.1:8000/account/parent-sign-up, without the student-sign-up prefix. HTML <!-- Radio check 1 --> <div class="form-check form-check-inline radio"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="radios" id="radio1" onclick="document.location.href='student_sign_up.html'" checked /> Individual </label> </div> <!-- Radio check 2 --> <div class="form-check form-check-inline radio"> <label class="form-check-label"> <input class="form-check-input" type="radio" name="radios" id="radio2" onclick="document.location.href='parent_sign_up.html'" /> Parent of a child under 13 </label> </div> urls.py urlpatterns = [ path('login/', views.login_view, name='login'), path('student-sign-up/', views.student_sign_up, name='student_sign_up'), path('parent-sign-up/', views.parent_sign_up, name='parent_sign_up'), path('teacher-sign-up/', views.teacher_sign_up, name='teacher_sign_up'), path('reset-password/', views.reset_password, name='reset_password'), path('reset-password-after/', views.reset_password2, name='reset_password_after'), -
Why is my autocomplete not working?
I'm trying to have a user field autocomplete and have followed these instructions: http://flaviusim.com/blog/AJAX-Autocomplete-Search-with-Django-and-jQuery/ but I can not get this to work. The field itself does nothing and the /get_users url returns SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data It must be something simple I'm missing, any help would be appreciated. My code: TEMPLATE search_test.html: <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> <script> $(function() { $("#users").autocomplete({ source: "{% url 'get_users' %}", minLength: 2, }); }); </script> <div class="ui-widget"> <label for="users">Users: </label> <input id="users"> </div> VIEWS: def user_search(request): return render(request, '/search_test.html', {}) def get_users(request): if request.is_ajax(): q = request.GET.get('term', '') users = User.objects.filter(username__icontains=q) results = [] for user in users: user_json = {} user_json['id'] = user.id user_json['label'] = user.username user_json['value'] = user.username results.append(user_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) URLS: url(r'^search_test/$', views.user_search), url(r'^get_users/', views.get_users, name='get_users'), -
Prefetch for Django Model properties
I have a problem with optimising my prefetching of a models properties. But let's start with the code first,that makes it easier to explain my problem class Tournament(models.Model): name = models.CharField(...) @property def active_teams(self): return self.teams.exclude(state=TeamStateTypes.inactive) @property def total_count_teams(self): return self.active_teams.count() class Team(models.Model): tournament = models.ForeignKey( Tournament, ... related_name='teams' ) My problem is that i have multiple of these countslike total_count_teams. When a request now retrieves a Tournament, this leads to many SQL queries, which makes it slow. To improve the performance i tried to prefetch the stuff, but the SELECT COUNT(*) queries still persist Tournament.objects.all().prefetch_related('teams') Is this idea even feasible or how do I optimize/do this? -
Django / Ajax / Datatable
I am trying to use following code in order to make a GET request to my django-based local server & render the obtained JSON-formatted data as a table: $(document).ready(function (){ var rows_selected = []; var table = $('#example').DataTable({ 'ajax': $("#active_subscriptions_url").attr("data-ajax-target"), 'cache': true, 'columnDefs': [{ 'targets': 0, 'searchable':false, 'orderable':false, 'width':'1%', 'className': 'dt-body-center', 'render': function (data, type, full, meta){ return '<input type="checkbox">'; } }], 'order': [1, 'asc'], 'cache': true, 'rowCallback': function(row, data, dataIndex){ // Get row ID var rowId = data[0]; // If row ID is in the list of selected row IDs if($.inArray(rowId, rows_selected) !== -1){ $(row).find('input[type="checkbox"]').prop('checked', true); $(row).addClass('selected'); } } }); Unfortunately, it can not properly refer to the data, because each time this AJAX function adds a timestamp ad the end of a url: http://127.0.0.1:8000/accounts/?_=1530637137189 I can not get rid of it - I have tried using 'cache' paremeter in Ajax, but it does not work. Moreover, I ve tried to extend my urls.py with following position: url(r'^accounts/(?P<timestamp>\?_=[0-9]*)/$', ShowSubscriptions.as_view(), name='show_subscriptions'), But it does not match the coming request at all.