Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to install Django in a virtual environment managed by pyenv from Ansible
I would like to build development environment with Vagrant and Ansible. The composition is Pyenv + Python 3.6 + Django When you execute AnsibleScript below - name: install django pip: name: django version: "{{ django_version }}" virtualenv: "{{ work_dir }}" virtualenv_command: pyenv become: false An error occurs. fatal: [127.0.0.1]: FAILED! => {"changed": false, "failed": true, "msg": "Failed to find required executable pyenv in paths: /usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/vagrant/bin"} Is there a solution? -
Does someone know how to implement Jquery Datatables in a Django framework?
I am trying to create a datatable using Datatables and Django, however I am lost. The most I get my web page to display is the json data. Below are my models: from __future__ import unicode_literals from django.db import models class LikeDefectMatrix(models.Model): area = models.TextField(db_column='AREA', blank=True, null=False, primary_key=True) # Field name made lowercase. type = models.TextField(db_column='TYPE', blank=True, null=True) # Field name made lowercase. defect_name = models.TextField(db_column='DEFECT_NAME', blank=True, null=True) # Field name made lowercase. update = models.TextField(db_column='UPDATE', blank=True, null=True) # Field name made lowercase. code = models.BigIntegerField(db_column='CODE', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Like_Defect_Matrix' Here are my views: from .models import LikeDefectMatrix from django.http import HttpResponse from django.core import serializers # Create your views here. def postsjson(request): object_list = LikeDefectMatrix.objects.all() json = serializers.serialize('json', object_list) return HttpResponse(json, content_type='application/json') this is my base.html file: {% load staticfiles %} <!DOCTYPE html> <html lang = "en"> <head> Example <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery.dataTables.min.css'%}" /> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery.dataTables.min.js' %}"></script> </head> <body> <div id="page-wrapper"> <div class="container-fluid"> {% block body %} {% endblock body %} </div> </div> </body> {% block js … -
/ and /blog are not not showing any of the content from Posts. I believe the issue has something to do with get_absolute_url() and reverse
While /blog doesn't show any of the posts, / is showing empty bootstrap modules for every post - so it knows how many posts there are and therefore something is coming through. I believe the issue started when I attempted to add another module to base.html The directory structure is as follows: - src [Folder] - content [Folder] - migrations [Folder] - __init__.py - admin.py - apps.py - models.py - tests.py - views.py - main [Folder] - settings [Folder] - __init__.py - base.py - migrations [Folder] - __init__.py - db.sqlite3 - models.py - urls.py - views.py - wsgi.py - posts [Folder] - migrations [Folder] - templatetags [Folder] - __init__.py - admin.py - apps.py - forms.py - models.py - tests.py - urls.py - utils.py - views.py - templates - base.html - blogbase.htm models.py - posts is as follows: from __future__ import unicode_literals from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save from django.utils import timezone from django.utils.safestring import mark_safe from django.utils.text import slugify from markdown_deux import markdown from comments.models import Comment from .utils import get_read_time # Create your models here. # MVC MODEL VIEW CONTROLLER #Post.objects.all() #Post.objects.create(user=user, title="Some time") class … -
Error: 'bool' object has no attribute 'startswith' when I use django-smart-select
I recieved the error 'bool' object has no attribute 'startswith' when I changed two fields in model "Location". I tried to use django-smart-select.(ChainedForeignKey) from smart_selects.db_fields import ChainedForeignKey class ListOfContinents(models.Model): id_Continent = models.AutoField(primary_key=True) Continent = models.CharField(max_length=200,unique=True) def __str__(self): return '%s' % self.Continent class ListOfCountries(models.Model): id_Country = models.AutoField(primary_key=True) Continent = models.ForeignKey(ListOfContinents, default=0, to_field='Continent',db_column='Continent') Country=models.CharField(max_length=200,unique=True) def __str__(self): return '%s' % self.Country class Location(models.Model): #Continent=models.CharField(max_length=200,null=True, verbose_name='Континент') #Country=models.CharField(max_length=200,null=True, verbose_name='Страна') Continent=models.ForeignKey(ListOfContinents,to_field='Continent',db_column='Continent',verbose_name='Континент',null=True) Country = ChainedForeignKey(ListOfCountries,chained_field="Continent", chained_model_field="Continent", show_all=False, auto_choose=True, sort=True, verbose_name='Страна', db_column='Country', to_field='Country', null=True) Forms.py class LocationForm (forms.ModelForm): class Meta: model = Location fields = ('Continent','Country') def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_id = 'id-unitForm' # self.helper.form_class = 'blueForms' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-1' self.helper.field_class = 'col-lg-4' self.helper.form_method = 'post' # self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary')) self.helper.add_input(Button('cancel', 'Cancel', css_class='btn-default', onclick="window.history.back()")) super(CaseForm, self).__init__(*args, **kwargs) Full error text: 'bool' object has no attribute 'startswith' site-packages\crispy_forms\templates\bootstrap3\uni_form.html, error at line 4 Line 4: {% if include_media %} {{ form.media }} {% endif %} Please help me to solve thos error. Thanks! -
How to display multiple value parameter in django rest framework swagger?
Versions: coreapi==2.3.1 Django==1.11.2 django-rest-framework==0.1.0 django-rest-swagger==2.1.2 django-silk==1.0.0 djangorestframework==3.6.3 API endpoint: /search?filter=("pages")?filter=("people") In my SwaggerSchemaView I have defined the filter field as follows: coreapi.Field(name="filters", description="=search(query)", location="query", type="array", required=True) Swagger looks like this: now when i provide the values in the value box, it results in the api of format: /search?filter=("pages"),("people") How can I make swagger respect the format I want that is /search?filter=("pages")?filter=("people") -
Django REST - create object with PrimaryKey
Model: class Company(models.Model): name = models.CharField(max_length=200, blank=True, default='') created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, related_name='companies') class Meta: ordering = ('-created',) And I use the built-in User model Serializers class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name', 'created') class UserSerializer(serializers.ModelSerializer): companies = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'date_joined', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'companies') View: @csrf_exempt def companies_create(request): if request.method == 'POST': data = JSONParser().parse(request) serializer = CompanySerializer(data=data) print(serializer) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) How should a JSON file be sent to the server (does it include all fields in the Company + user_id model)? How do I attach a User object before saving in a view? -
Urls and file organization in a Django project
I am developing a website with django, and I don't know how I should structure my project. Let's say that my project tree is: main ├───_main | ├── __init__.py | ├── settings.py | ├── urls.py | └── wsgi.py ├───_accounts | ├── models.py | ├── forms.py | ├── urls.py | ├── views.py | └── ... └───_website ├──_static | └──_website | ├── css (...) | └── js (...) ├──_templates | └──_website | └── (html files...) ├── urls.py ├── views.py └── ... I have two apps ('accounts' and 'website') in my project 'main'. The 'accounts' app implements the user model and the authentication process. The 'website' app controls non-model related stuff, like home page and so on. Of course, there will be more apps... At this moment, all the web files (html, css, js...) are stores in 'website' (static / templates folders), and website/urls.py handles all urls. # website/urls.py from django.conf.urls import url, include from .views import index from accounts.views import LoginView, LogoutView, RegisterView urlpatterns = [ url(r'^$', index, name="index"), # Accounts url(r'^login/', LoginView.as_view(), name="login"), url(r'^logout/', LogoutView.as_view(), name="logout"), url(r'^register/', RegisterView.as_view(), name="register"), ] It makes sense to me that user-related web files like login form, register form, etc., should be store in static and … -
Google API and Django getting 400 error when trying to copy a folder
I am trying to copy a folder using the google api, python and django and have managed to get things working with an adaptation of the code found here https://developers.google.com/drive/v3/web/quickstart/python But when I try to copy a folder I get: https://www.googleapis.com/drive/v3/files/FileId/copy?alt=json returned "Bad Request"> import os import logging import httplib2 from pprint import pprint from googleapiclient.discovery import build from django.contrib.auth.decorators import login_required from django.conf import settings from django.http import HttpResponseBadRequest from django.http import HttpResponseRedirect from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import JsonResponse from django.db.utils import IntegrityError from .models import Entries, CredentialsModel from oauth2client.contrib import xsrfutil from oauth2client.client import flow_from_clientsecrets from oauth2client.contrib.django_util.storage import DjangoORMStorage from .pipeline_lib import pipeline_lib as pipeline FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope=['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.metadata'], redirect_uri='http://somedomain.com:8000/workflow/oauth2callback') @login_required def index(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid == True: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build("drive", "v3", http=http) newfile = {'title': 'New Master 123', 'parents': [{'id': 'folderId'}]} result = service.files().copy(fileId='folderId',body=newfile).execute() pprint(result) # results = service.files().list(pageSize=10,fields="nextPageToken, files(id, name)").execute() # items = results.get('files', []) # if not items: # print('No files found.') # … -
Linking buttons to objects in Django
I am trying to make a simple todo list app with Django but I can't figure out how to delete entries. here is my code Views.py: def todo_view(request): print('todo') tasks = models.Todo.objects.all().filter(user=request.user) if request.method == 'POST': print('POST = {}'.format(request.POST)) print('Post') form = forms.Todo(request.POST) if request.POST.get('task'): print('add-task') if form.is_valid(): print('valid') task = form.cleaned_data.get('task') done = False urgency = 'todo' user = request.user todo = models.Todo(task=task, done=done, urgency=urgency, user=user) todo.save() else: print('del') for task in tasks: print(task.id) if task.id in request.POST: print(task.id) model = models.Todo.objects.get(pk=task.id).delete() else: form = forms.Todo() dictionary = { 'tasks': tasks, 'form': form, } return render(request, 'account/todo.html', dictionary) template: {% for task in tasks %} <form method="post" name="delete-task"> {% csrf_token %} <p> {{ task }} <button type="submit" name="{{ task.id }}">Delete</button> </p> </form> {% endfor %} <form method="post" name="task"> {% csrf_token %} {{ form.task }} <button type="submit">Add</button> </form> i am able to add tasks however it fails to delete tasks. also the print statements I used for debugging, they are unimportant to the rest of the code. -
How can i have two separate log formats for django and celery?
Is it possible to have different log formats for celery tasks and django? What I want is two different log formats. In celery logs i want additional task_id and processName parameters. Below is my django logger settings, class LoggerSettingsMixin(object): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[%(asctime)s] [rid:%(request_id)s] [crid:%(client_request_id)s] [aid:%(actor_id)s] [%(levelname)s] [%(lineno)d:%(name)s] - %(message)s' }, 'celery': { 'format': '[%(asctime)s] [%(processName)s] [%(levelname)s] [%(lineno)d:%(name)s] - %(message)s' }, }, 'filters': { 'request_id': { '()': 'request_id.logging.RequestIdFilter' }, 'client_request_id': { '()': 'apps.commons.logging_filters.ClientRequestIdFilter' }, 'actor_id': { '()': 'apps.commons.logging_filters.ActorFilter' }, 'task_id': { '()': 'apps.commons.logging_filters.CeleryTaskIdFilter' } }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'filters': ['request_id', 'actor_id', 'client_request_id', 'task_id'], 'formatter': 'default', }, 'celery': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'celery', } }, 'loggers': { 'statsd': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'celery': { 'handlers': ['celery'], 'level': 'INFO', 'propagate': False, }, 'celery.redirected': { 'handlers': ['celery'], 'level': 'INFO', 'propagate': False, }, '': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, } } } Below is my signals, where i am trying to override the celery root logger , @after_setup_logger.connnect def setup_logger(**options): logger = get_logger('') logger.handlers = [] logger.addFilter(ActorFilter()) logger.addFilter(ClientRequestIdFilter()) logger.addFilter(CeleryTaskIdFilter()) logger.addFilter(RequestIdFilter()) formatter = logging.Formatter('[%(asctime)s] [%(processName)s][rid:%(request_id)s [crid:%(client_request_id)s] [aid:%(actor_id)s] [taskid:%(task_id)s] [%(levelname)s] [%(lineno)d:%(name)s] - %(message)s') handler … -
Making an automatic id in a certain format in a Django model
I'm trying to make a field in a model that is automatically created whenever an instance is in a certain way. Here is the relevant code: models.py class Student(models.Model): # This first field is what I'm focusing on student_id = models.CharField(max_length=128, unique=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) ssn = USSocialSecurityNumberField(null=False) gender = models.CharField(max_length=128, choices=GENDER_CHOICES) dob = models.DateField(auto_now=False, auto_now_add=False, db_column="date of birth") address = models.CharField(max_length=128) city = models.CharField(max_length=128) state = USStateField(choices=STATE_CHOICES, default='NJ') zipcode = USZipCodeField(blank=True) country = CountryField(default='US', blank=True) home_phone = models.CharField(max_length=128) cell_phone = models.CharField(max_length=128) email = models.EmailField(max_length=254, validators=[validate_email]) background = models.CharField(max_length=128, choices=BACKGROUND_CHOICES) # This field is relevant location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') workforce = models.CharField(max_length=128, choices=WORKFORCE_CHOICES, default='--') source = models.CharField(max_length=128, choices=SOURCE_CHOICES, default='individual') refer_by = models.CharField(max_length=128, choices=REFER_BY_CHOICES, default='no refer') last_status = models.CharField(max_length=128, choices=LAST_STATUS_CHOICES, default='followup') newsletter = models.BooleanField() created_by = models.CharField(max_length=128) # This field is relevant date = models.DateField(auto_now=False, auto_now_add=False) notes = models.TextField() I want to make the student_id field different by making it created automatically in a certain format: AASSSYYMMDD AA is 'AV' when the student is paid, and 'PS' when student hasn't. I'm defaulting it to 'PS' for now so no need to worry about it. SSS is the first three letters of the location in uppercase YYMMDD is … -
Filter selectbox in Django Admin to Children that don't have Parents
This might be an odd request, but I'm not sure how else to handle my situation. I've got 3 models (actually a bunch more, but 3 applicable to this issue), and am modeling a piece of networking equipment. class Customer(models.Model): name = models.CharField(max_length=30) account = models.IntegerField() agreement = models.CharField(max_length=12) port = models.ForeignKey('Port') radusergroup = models.CharField(max_length=20, choices=PROFILES) active = models.BooleanField(default=True) def __str__(self): return str("{}\t{}".format(self.agreement, self.name)) signals.post_save.connect(create_radcheck, sender=Customer) class Node(models.Model): equipno = models.IntegerField() equipname = models.CharField(max_length=30) network = models.ForeignKey('Network') ipaddr = models.CharField(max_length=15) vlan = models.IntegerField() device_num = models.IntegerField() device_type = models.ForeignKey('Type') def __str__(self): return str("{} ({})".format(self.equipname, self.device_type)) signals.post_save.connect(create_ports, sender=Node) class Port(models.Model): node = models.ForeignKey('Node', on_delete=models.CASCADE) number = models.IntegerField() name = models.CharField(max_length=20) key = models.CharField(max_length=30) def __str__(self): return str("{}:{}".format(self.node.equipname, self.name)) I have a post_save signal that creates "Port" Objects for the number of ports on the "Node", and then has a parent relationship to the "Node". When I want to create a "Customer", part of that process is to select the port that the customer will be attached to. This appears as a selectbox. Everything works great, except that I'd like to only see ports that haven't already been assigned to a "Customer". This is a one to one relationship, so perhaps I … -
Custom forms of user register and user profile? Django
Hello I have a form that works, but I want to customize the style and warning messages. The next is my code: forms.py from django import forms from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2') class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = ('empresa', 'direccion', 'numero_interior', 'numero_exterior', 'colonia', 'estado', 'ciudad', 'municipio', 'cp', 'rfc', 'email2', 'email3', 'avatar') view.py def registro(request): if request.method == 'POST': uf = UserForm(request.POST, prefix='user') upf = UserProfileForm(request.POST, prefix='userprofile') if uf.is_valid() * upf.is_valid(): user = uf.save() userprofile = upf.save(commit=False) userprofile.user = user userprofile.save() return HttpResponseRedirect('/') else: uf = UserForm(prefix='user') upf = UserProfileForm(prefix='userprofile') return render(request, 'app/register.html', dict(userform=uf, userprofileform=upf), RequestContext(request)) register.html {% extends "app/base_users.html" %} {% block content %} {% if user.is_authenticated %} <p>Ya estas registrado</p> {% else %} <div> <h2>Registro de Empresas</h2> </div> <div class="container"> <div class="row"> <div class="col-md-4 offset-md-2 profile"> <form method="POST" action="" class="form-inline" role="form" name="frm" id="formulario"> {% csrf_token %} {{userform}} {{userprofileform}} <input type="submit"> </form> </div> </div> </div> {% endif %} {% endblock %} </body> </html> Currently it works, but I would not like to customize it more, especially the errors and helps of … -
How to access to URL parameter inside of get_queryset in Django?
Supposing, I've got a URL pattern like this: urlpatterns = [ ... url(r'^mylist/(?P<offset>\d+)/$', MylistView.as_view(), name='mylist'), ... ] My view class: class MylistView(ListView): template_name = 'mylist.html' def get_queryset(self, *args, **kwargs): offset = ... # What should I type here? entries = models.MylistEntry.all()[offset:offset+10] return entries How do I access to the URL parameter offset within the method get_queryset? I've checked the variables args and kwargs are empty. Thanks for advance! -
Difference between Django validate and a validator
From the Django docs The validate() method on a Field handles field-specific validation that is not suitable for a validator. This implies that validate() is different than a validator. What is the difference? I'm curious because I'm using a custom validate on a custom form field. It raises a ValidationError, but the code keeps running and calls Django's validate and clean afterwords and doesn't do anything with the ValidationError that I raised. -
I am getting NoReverseMatch at /blog u'posts' is not a registered namespace error after adding some functionality to my project
I have a project with that consists of a main page that has a blog feature and a text editing feature. In adding the text editing feature I seem to have disrupted almost all of the functionality of the blog app. The only thing that is rendering on / is empty bootstrap modules with none of the blog content (the link also bounces back to / no as well. /blog, which used to go to a list_view returns a NoReverseMatch at /blog u'posts' is not a registered namespace error as do any of the /blog/slug which went to detail views. I can still create blog posts however through the django admin. I know I am doing something wrong and could use some help as to where I screwed this up The directory structure is as follows The directory stucture is as follows: - src [Folder] - content [Folder] - migrations [Folder] - __init__.py - admin.py - apps.py - models.py - tests.py - views.py - main [Folder] - settings [Folder] - __init__.py - base.py - migrations [Folder] - __init__.py - db.sqlite3 - models.py - urls.py - views.py - wsgi.py - posts [Folder] - migrations [Folder] - templatetags [Folder] - __init__.py - … -
Create Django Survey Forms from Frontend
I am developing GoogleSurvey forms like app and I need to have frontend users build surveys. I need little guideline to get started. What I need is to built a view that can generates forms like Django-admin and then same forms could be used at site to collect data from other end users. Please advise. -
Django - Checkboxes & ManytoMany relationships in TemplateView
I have a app where users can register their company and then select a number of settings from a list. Both the company and services are different models. class Company(models.Model): name = models.CharField(max_length=100) (...) class Service(models.Model): name = models.CharField(max_length=100) linked_companies = ManyToManyField(Company, blank=True) What I want is to have a large list of services, with checkboxes behind their names, so the owner can quickly select the services that he wants to connect to his model. This used to be done through the admin interface, but due popular demand this feature is moved to 'the front'. The problem is that I do not know how to fit this into the traditional (generic) view/form combinations that we' ve been using so far, since two different models are involved. I am trying a more custom solution, but have hit a wall and I am wondering if you could help me. I have created a html page that should display both the list of services and a 'save' button. <form action="." method="POST" class="post-form">{% csrf_token %} <ul> {% recursetree services %} <li> <label><input type="checkbox" name='service' value={{ node.pk }}><h3>{{ node.name }}</h3></label> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> … -
Django 404 error with TemplateView
I have urls in app and when I go to article-report url I see django error page with urls for article, but there is no url for article-report. main.urls.py from rest_framework import routers from main.views import (ArticleViewSet) from django.views.generic import TemplateView router = routers.DefaultRouter() router.register(r'article-report', TemplateView.as_view(template_name = 'report.html'),'report') router.register(r'article', ArticleViewSet) urlpatterns = router.urls P.S. Pycharm underlines django,TemplateView and rest_framework in import lines. But in other examples It doesnt matter -
Integrity Error with null=True on field
This is stumping me. I create a model where the field is nullable null=True, but my database throws an IntegrityError. It works on my development machine... Here's the abbreviated traceback: IntegrityError: null value in column "score_updated_on" violates not-null constraint Here is the model: class Lead(models.Model): created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) ... score = models.DecimalField(decimal_places=3, max_digits=7, blank=True, null=True) score_updated_on = models.DateTimeField(blank=True, null=True) active = models.BooleanField(default=True) I have run all migrations. I went into psql and ran ALTER TABLE leads_lead ALTER COLUMN score_updated_on DROP NOT NULL;. No change. Nuke it all and reinitialize the DB? That's days of work, but this process can't continue unless I can accept null values. -
How to edit field in django admin panel
I have admin panel in Django 1.8 with my code in admin.py file: class PeriodAdmin(admin.ModelAdmin): list_display = ('id', 'date_start', 'date_end', 'description', 'note', 'is_published', 'is_actual', 'type', ) search_fields = ('id', 'note', 'description', 'description_en',) fields = ['type', ] My problem is, how to switch type field in to editable field. I can not found this is documentation. Please for any hint. -
Nginx, gunicorn, django, ubuntu - not displaying images
fellow humans I just set up a server on digitalocean and deployed my app. Everything else works fine including my javascript and css. but for some reasons beyond me, uploaded images by a user aren't displaying I think i got a lead but still dont know where to go. would really appreciate it if you could point me to the right direction so here is my image model(upload_to) class Image(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created') title = models.CharField(max_length=2000) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True, null=True) created = models.DateField(auto_now_add=True, db_index=True) users_like = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='images_liked', blank=True) and here is my nginx conf server { listen 80; server_name 67.207.87.22; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/kingiyk/stylplus/static/; } location /media/ { alias /home/kingiyk/stylplus/media/; } location / { include proxy_params; proxy_pass http://unix:/home/kingiyk/stylplus/stylplus.sock; } } When i upload an image, it gets saved to /home/kingiyk/stylplus/images/2017/07/26 stylplus/images is the image app I think the '2017/07/26' part is as a result of my upload_to being 'images/%Y/%m/%d (year/month/day). Although the upload is succesful, but the image does not display i have no problem with my css and javascript. Now i am guessing there is a conflict … -
Not seeing performance increase running django test /w postgresql on ramdrive
For a django project, the tests are running slower and slower as the models grow and the number of migrations as well. A single unittest i have timed now at 200s. I followed this post: http://tech.marksblogg.com/test-django-on-ram-drive.html to work on a ramdrive only for the testing but strangly enough i'm not seeing any improvement.... So i expect something is not going as it should... I have debugged some and did see the TABLESPACE statements being generated towards postgres, for instance: ... CREATE TABLE ""django_content_type"" (""id"" serial NOT NULL PRIMARY KEY USING INDEX TABLESPACE ""ram_disk"", ""name"" varchar(100) NOT NULL, ""app_label"" varchar(100) NOT NULL, ""model"" varchar(100) NOT NULL) TABLESPACE ""ram_disk""",,,,,,,,," Could it be that postgresql rejects it? And how can i test/see if the ram drive is actually being used? Paul -
Django Model Fields Indexing
I only know that indexing is helpful and it queries faster. What is the difference between following two? 1. class Meta: indexes = [ models.Index(fields=['last_name', 'first_name',]), models.Index(fields=['-date_of_birth',]), ] 2. class Meta: indexes = [ models.Index(fields=['first_name',]), models.Index(fields=['last_name',]), models.Index(fields=['-date_of_birth',]), ] -
django rest framework - browsable api remove delete
I have the following view: def retrieve(self, request, pk=None, **kwargs): try: instance = self.get_object() self.check_object_permissions(self.request, instance) serializer = PasswordFolderSerializer(instance, context={'request': request}) return Response(serializer.data) except Http404: return Response(status=status.HTTP_404_NOT_FOUND) When not logged in I will get a 403 which is good however the "DELETE" button still shows in the browsable API. how do I get rid of this? Here is my permission: class CanRetrievePasswordFolder(permissions.DjangoObjectPermissions): def has_permission(self, request, view): if request.user is None: return False else: return True def has_object_permission(self, request, view, obj): access_levels = ['Owner', 'Admin', 'Read'] if get_permission_level(request, obj) is None: return False else: level = AccessLevel.objects.get(pk=get_permission_level(request, obj).level_id).name if request.method in permissions.SAFE_METHODS: return True else: for access in access_levels: if level == access: return True else: return False