Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve data from one to many relations in django?
I am making my personal website using django 1.10 Here is models of skill app: from __future__ import unicode_literals from django.db import models # Create your models here. class Skill(models.Model): name = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __unicode__(self): return self.name def __str__(self): return self.name class Subskill(models.Model): skill = models.ForeignKey(Skill, on_delete=models.CASCADE) name = models.CharField(max_length=256) link = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __unicode__(self): return self.name def __str__(self): return self.name And view: from django.shortcuts import render from skill.models import Skill,Subskill # Create your views here. def home(request): skill = Skill.objects.all() subskill =Subskill.objects.all() context = {'skills':skill, 'subskills':subskill} return render(request, 'skill.html', context) This is my template page: skill.html {% block skill %} {% for subskill in subskills %} {{subskill.skill.name}} {{subskill.name}} {% endfor %} {% endblock skill %} Let assume, there is a skill named web design which has two subskill named html and css. I want to render in view page as like as skill name and it's two child name: Web design Html CSS But it renders as like Web design Html Web design CSS Please help me about this issue. -
How to sync the PostgreSQL database script changes with Django back-end
I have been given a new project with website running on Django back-end. This uses the PostgreSQL database. The changes I have completed on my local system. My client has given me a live remote machine with proper FTP, SSH and database access. He also created a database dump file and provided it to me. I have completed the necessary code and database changes. But now I don't know how to sync these database changes back to the server. I am fairly new to Django and PostgreSQL stuff and don't know how to accomplish this task. Yours help will be much appreciated in this. Thanks -
When {% csrf_token %} may be inconvenient?
Django 1.10 In the documentation we can read: While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. https://docs.djangoproject.com/es/1.10/ref/csrf/#ajax The mentioned "above method" is about adding {% csrf_token %} to forms. And it is said in the documentation that more convenient may be: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); Well, I can't catch in which case {% csrf_token %} may be inconvenient. I tried: <form action="" method="post">{% csrf_token %} function post_create(){ $.ajax({ method: "POST", url: '{{ object.get_frame_date_create_url }}', data: $("#object_form").serialize(), success: add_post_data, error: fail, }); } Seems to be working. The result of $("#object_form").serialize() looks like this: "csrfmiddlewaretoken=NFgXO1gsHJbi0N1IUb5ZPQ2rno2RGBrRR8kxboewWDC63sm2hxlvXtUtyviCSoZ1&date=2015-01-01&precision=F&frame=1" What must I remember here? How can I forget to pass csrfmiddlewaretoken? It is just an ordinary field of the form. Hidden from users, but not from the programmer. Is it supposed that there are cases when it is necessary to manually touch every field in the form and send it separately. I can't imagine that. … -
Using queryset manager with prefetch_related
I have been succesfully using this brilliant technique to keep my code DRY encapsulating ORM relations in querysets so that code in views is simple and not containing foreign key dependency. But this time I face the following issue best descriped by code: View: vendors_qs = vendors_qs.select_related().prefetch_related('agreement_vendors') Model class AgreementVendorsQuerySet(models.query.QuerySet): def some_filter(self, option): result = self.filter(.....) return result And a template: {% for vendor in vendors_qs %} <tr> ... <td> {% for vend_agr in vendor.agreement_vendors.all %} {{vend_agr.serial_number}} {% endfor %} <td> </tr> {% endfor %} The question is, how and where do I apply the some_filter to vendor agreements given that it is fetched as prefetch_related relation. Do I have to apply the filter in the template somehow or in the view itself ? If I didn't put the question clearly enough, I will ask your questions to clarify further... -
AccessToken matching query does not exist
I am creating a an API for registering user based on oauth token. My app has functionality like registration and login, adding restaurant etc. I created user registration part but i get error while login. I want login based on token. I have used django-oauth-toolkit for this and DRF. What i have done is Login based on token class UserCreateAPI(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [AllowAny] class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): access_token = AccessToken.objects.get(token=request.POST.get('access_token'), expires__gt=timezone.now()) # error is shown here data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) For creating user with a token class UserCreateSerializer(ModelSerializer): class Meta: model = User extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() if user_obj: expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="Foodie") expires = datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user_obj, application=application, token = generate_token(), expires=expires, scope=scopes) return validated_data I have excluded fields part and validation part … -
jquery autocomplete not working on cloned rows dynamic formset django
I am using Jquery autocomplete and is working fine in the first row. the dynamically added rows are not having autocomplete. I am new here. Here is the code for dynamic formset: function addForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); var row = $('.dynamic-form:first').clone(); $(row).removeAttr('id').insertBefore($('.dynamic-form:last')).children('.hidden').removeClass('hidden'); $(row).children().not(':last').children().each(function() { updateElementIndex(this, prefix, formCount); $(this).val(''); }); $(row).find('.delete-row').click(function() { deleteForm(this, prefix); }); $('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1); return false; } Here is the code for initializing the autocomplete: $('.autocomplete).each(function() { var datacontent = $("#"+this.id).attr('data-content'); $("#"+this.id).autocomplete({ source: datacontent, // json format select: function(event, ui) { $("#"+this.id+"_id").val(ui.item.value); $("#"+this.id).val(ui.item.label); return false; }, change: function(event, ui) { if ($("#"+this.id).val().length == 0) { $("#"+this.id+"_id").val(''); } } }); }); -
Django aggregate, use of AND/OR operators in when condition
With the following queryset I would like to add and / or condition in the when clause, but I get syntax error. Is it possible to do it in a single queryset or should I split? Game.objects.prefetch_related('schedule').filter(Q(team_home_id=625) | Q(team_away_id=625), schedule__date_time_start__lte=timezone.now()) .aggregate( wins=Sum(Case(When( score_home__gt=F('score_away') & team_home_id=625 | score_away__gt=F('score_home') & team_away_id=625, then=1), default=0, output_field=IntegerField() )), ) -
How to uninstall django-watson library clearly
I want use search library in django So i decide to use django-watson(it tell me easy install, easy use) I command git clone https://github.com/etianen/django-watson.git in my django projects and insert watson in my settings.py. INSTALLED_APPS when I command python manage.py migrate django can't find watson so I decide uninstall django-watson and reinstall I command rm -rf django-watson and command migrate (check about when i was uninstall library migrate has no problem) python manage.py migrate suddenly it show me error for me Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/hanminsoo/.pyenv/versions/study_alone/lib/python3.5/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Users/hanminsoo/.pyenv/versions/3.5.1/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'django-watson' I think it has … -
python Django: unable to understand the heirarchy of this class
I have the following code of models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title What does class Post(models.Model) means: Can someone explain how to understand with java syntax: Is it similar to Class Post extends models.Model -
django cannot connect to redshift
I'm having difficulty running the python manage.py migrate utility script/process in a django project using redshift. % pip freeze boto==2.42.0 boto3==1.4.0 botocore==1.4.45 ... Django==1.10 ... psycopg2==2.6.2 ... s3transfer==0.1.1 Start a basic redshift cluster using these instructions. % django-admin startproject mysite % cd mysite Edit the DATABASE settings in mysite/settings.py to the following. DATABASES = { 'default': { 'NAME': 'examplecluster', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'masteruser', 'PASSWORD': '<masteruser password>', 'HOST': 'jdbc:redshift://examplecluster.chhtfnotsqcm.us-west-1.redshift.amazonaws.com:5439/dev', 'PORT': 5439 } } Then run the manage.py script with migrate. % python manage.py.migrate django.db.utils.OperationalError: could not translate host name "jdbc:redshift://examplecluster.chhtfnotsqcm.us-west-1.redshift.amazonaws.com:5439/dev" to address: nodename nor servname provided, or not known I can connect to my redshift cluster fine using sql workbench j with the above settings, however interacting with the cluster via the manage.py utility fails so obviously I'm missing something but I don't know what. Any ideas are welcome. -
view must be callable or a list/tuple in the case of include().')
This is My First Django Studying, and Here is Error The Error is view must be a callable or a list/tuple in the case of include(). My user url.py is: from django.conf.urls import url urlpatterns = [ url(r'^signup/$', 'users.views.signup', name='signup'), url(r'^login/$', 'users.views.login', name='login'), url(r'^logout/$', 'users.views.logout', name='logout'), url(r'^reset_password/(?P<user_id>([0-9])+)/(?P<token>([0-9])+)/$', 'users.views.reset_password' , name='reset_password'), url(r'^forget_password/$', 'users.views.forget_password ] and my view.py is: import json import random from .forms import UserForm, UserInfoForm from .models import ResetPassToken, UserInfo from django.core.mail import EmailMessage from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.shortcuts import render, redirect from django.http import HttpResponse, Http404 from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login as login_auth, logout as auth_logout def signup(request): errors = {} if request.method == 'POST': user_form = UserForm(request.POST) user_info_form = UserInfoForm(request.POST) if not errors: new_user = user_form.save(commit=False) new_user.username = new_user.email new_user.save() new_user_info = user_info_form.save(commit=False) new_user_info.user = new_user new_user_info.save() auth_user = authenticate(username=new_user.username, password=request.POST['password']) login_auth(request, auth_user) return render(request, 'info.html', {'page_title': "ثبت نام", 'message_title': "ثبت نام موفق", 'message': "ثبت نام شما با موفقیت انجام شد."}) else: for key in errors: if errors[key] == ["This field is required."]: errors[key] = ['لطفاً این قسمت را وارد فرمایید.'] else: user_form = UserForm() user_info_form = UserInfoForm() return render(request, 'signup.html', {'errors': errors, 'user_form': user_form, 'user_info_form': user_info_form}) and … -
pyinstaller 3.2 with django 1.10.1
System: windows 7 64 bit, python 3.5, anaconda 3 (64 bit) , djagno 1.10.1 I'm trying to compile my django project in 2 ways: First: [Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies manage.py Second according to this soloution: [Anaconda3] c:\compilation\Gui>pyinstaller --name=gui --exclude-module=PyQt4 --exclude-module=matplotlib --clean --win-private-assemblies --runtime-hook=pyi_rth_django.py manage.py When I try to run the output: c:\compilation\Gui\dist\gui>gui.exe runserver I get (for the 2 versions I get the same output): c:\compilation\Gui\dist\gui>gui.exe runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000000044E9D90> Traceback (most recent call last): File "site-packages\django\utils\autoreload.py", line 226, in wrapper File "site-packages\django\core\management\commands\runserver.py", line 113, in inner_run File "site-packages\django\utils\autoreload.py", line 249, in raise_last_exception File "site-packages\django\utils\six.py", line 685, in reraise File "site-packages\django\utils\autoreload.py", line 226, in wrapper File "site-packages\django\__init__.py", line 27, in setup File "site-packages\django\apps\registry.py", line 85, in populate File "site-packages\django\apps\config.py", line 116, in create File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'django.contrib.admin.apps' Please advice. -
Create token while registering user
I am developing an API from Django Rest Framework. I dont get into how to create a token when registering user and login through that token. I have followed this link to create a token when registering user, but no avail. I get name error 'random_token_generator' not defined. Do i have to write custom random_token_generator or it is pre built in django-oauth-toolkit. So my question is How can i generate token while registering user and use that token for login access? My code Serializers.py class UserCreateSerializer(ModelSerializer): email = EmailField() username = CharField() first_name = CharField(required=False) last_name = CharField(required=False) password = CharField() confirm_password = CharField() class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'confirm_password' ] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() if user_obj: expire_seconds = oauth2_settings.user_settings['ACCESS_TOKEN_EXPIRE_SECONDS'] scopes = oauth2_settings.user_settings['SCOPES'] application = Application.objects.get(name="Tushant") expires = datetime.now() + timedelta(seconds=expire_seconds) access_token = AccessToken.objects.create(user=user_obj.username, application=application, token = random_token_generator(request), expires=expires, scope=scopes) return validated_data views.py class UserCreateAPI(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes … -
python logging not working when i run full test suite
python logging is not logging anything to streamio when i run full test suite, although when i run tests individually it works perfectly. Seems low memory issue to me but not sure how to resolve it, can anyone give some tip on this, following is my code. class MyTest(TestCase): def setUp(self): super(MyTest, self).setUp() self.stream = StringIO() self.handler = logging.StreamHandler(self.stream) self.log = logging.getLogger('mylogger') self.log.setLevel(logging.INFO) for handler in self.log.handlers: self.log.removeHandler(handler) self.log.addHandler(self.handler) self.addCleanup(self.log.removeHandler, self.handler) self.addCleanup(self.handler.close) def testLog(self): self.log.info("stringified json") self.handler.flush() self.assertTrue(self.stream.getvalue(), 'stringified json') -
How to use metronic ajax datatables in django project
I have worked on various of php project in which to represent data in a table format in admin panel I always use metronic ajax datatables because it fulfills all of my requirements and it is very much compatible with PHP code, The searching, sorting and representing data in table format is very easy in metronic ajax datatables. But as now I am working on django project, I am facing various of issues while implementing ajax datatables. I want to ask are there any other source using which I can implement datatables same as metronic datatables Or should I move with metronic datatables continue trying to implement this ?? -
Rename response fields django rest framework serializer
I'm calling a simple get API using djangorestframework. My Model is class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField("Category Name", max_length = 30) category_created_date = models.DateField(auto_now = True, auto_now_add=False) category_updated_date = models.DateField(auto_now = True, auto_now_add=False) def __str__(self): return self.category_name serializer.py class CategorySerializer(serializers.ModelSerializer) : class Meta: model = Category fields = ['category_id', 'category_name'] def category_list(request): if request.method == 'GET': categories = Category.objects.all() serializer = CategorySerializer(categories, many=True) return Response(serializer.data) It's working fine when i hit request on the URL and returning following response. [ { "category_id": 1, "category_name": "ABC" } ] i want to change the response field names as it's for my DB only and don't want to disclose in response. If i change the name in serializer class than it's giving no field match error. Also i want to customise other params like above response in response object with message and status like below. { status : 200, message : "Category List", response : [ { "id": 1, "name": "ABC" } ] } Need a proper guide and flow. Experts help. -
Why am I getting the error: "Error: Render_to_response not defined"; Django
I'm learning Django, and I found a very basic example online on how to display tables using templates. I followed the code exactly, but for some reason I get the error: Error: Render_to_response not defined Here is my views.py: from django.shortcuts import render def display(request): return render_to_response('template.tmpl', {'obj':models.Book.objects.all()}) Here is my urls.py: from django.conf.urls import url from . import views urlpatterns = [ # /table/ url(r'^$', views.display, name='display'), ] Here is my template.tmpl: <table> <tr> <th>author</th> <th>title</th> <th>publication year</th> </tr> {% for b in obj %} <tr> <td>{{ b.author }}</td> <td>{{ b.title }}</td> <td>{{ b.publication_year }}</td> </tr> {% endfor %} </table> Here is my models.py: from django.db import models class Book(models.Model): author = models.CharField(max_length = 20) title = models.CharField(max_length = 40) publication_year = models.IntegerField() I've looked online for some help with this error, but all the problems seem to be much more complicated than the one I'm facing. Is there something I'm missing? -
How to access a specific object already displayed in template?
I am creating a django view that that does the action of liking a picture. However, the issue I am having is I can not seem to access the id of the specific picture the user liked. I have tried to do it through url patterns but i got the error "like_photo() takes 2 arguments one given" when feedclass_id is passed in the like_photo view. Having said that, I would rather process the information without any change of the url. I am also getting the error "get() returned more than one FeedClas -- it returned 9"! when the pk is changed to 1 for example. The user has uploaded 9 photos by the way. So the main question is, how can work this code to update the likes of each individual photo when the submit button is clicked. My code is below. class FeedClas(models.Model): image = models.FileField(upload_to='folder') title = models.CharField(max_length=200, blank=True) likes = models.IntegerField(default=0) user_posted = models.ForeignKey( User, on_delete=models.CASCADE, related_name="phot" ) num_comments = models.IntegerField(default=0) date_pub = models.DateTimeField(auto_now_add=True) is_liked = models.BooleanField(default=False) HERE IS MY VIEW: def like_photo(request): user = request.user.id #get all photos that belong to this user photos = Feedclas.objects.get(user_posted_id=user) photo = Feedclas.objects.get(pk="here is where I am having the trouble") … -
i did make a webservice using get and post and i need to know how to make in post function
i want to create a api for adding as well as fetching the data from database and the following is my code. here is my models.py which contains the fields of database. i did install the restapiframework and add it in to the installed apps models.py from django.db import models class Stock(models.Model): ticker = models.CharField(max_length=10) open = models.FloatField() close = models.FloatField() volume = models.IntegerField() def __Str__(self): return self.ticker views.py from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Stock from .serializers import StockSerializer #List all stocks or create a new one #stocks/ class StockList(APIView): def get(self, request): stocks = Stock.objects.all() serializer =StockSerializer(stocks, many=True) return Response (serializer.data) def post(self, request): #pass form = self.form_class(request.POST) settings.py INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', # 'payments', 'rest_framework', 'companies.apps.CompaniesConfig', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] -
Best way to create Django instances while manipulating/hiding fields from caller?
Suppose I have the following Django class: from django.db import models class Person(models.Model): name = models.CharField(max_length=254) year_of_birth = models.IntegerField() I can create an instance of the model by doing the following: p = Person.object.create(name="Mahmoud", year_of_birth=1985) However, I don't want the calling function outside the Person class to know the internal details of the class. And I also don't want them to have to calculate their year of birth. I just want them to enter their age (21), and I want to write a method that takes care of the rest for them automatically. This is a common need I have throughout my Django application. Is there a preferred pattern to solve this problem? I'm doing it by creating the following static method in the Person class: import datetime @staticmethod def create(name, age): return Person.objects.create(name=name, year_of_birth=datetime.datetime.now().year-age) And then I call it like this: p = Person.create(name="Mahmoud", age=21) Is this the proper/pythonic way to handle this situation? -
How to set pixel dynamically in custom-thumbnail-image-field in Django?
I got example of creating custom ThumbnailImageField from certain book(Korean), and tried to apply it my project. Here is the example of ThumbnailImageField itself from book. fields.py from django.db.models.fields.files import ImageField, ImageFieldFile from PIL import Image, ImageOps import os def _add_thumb(s): parts = s.split(".") parts.insert(-1, "thumb") if parts[-1].lower() not in ['jpeg', 'jpg']: parts[-1] = 'jpg' return ".".join(parts) class ThumbnailImageFieldFile(ImageFieldFile): def _get_thumb_path(self): return _add_thumb(self.path) thumb_path = property(_get_thumb_path) def _get_thumb_url(self): return _add_thumb(self.url) thumb_url = property(_get_thumb_url) def save(self, name, content, save=True): super(ThumbnailImageFieldFile, self).save(name, content, save) img = Image.open(self.path) size = (570, 390) img.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( img, (int((size[0] - img.size[0]) / 2), int((size[1] - img.size[1]) / 2))) background.save(self.thumb_path, 'JPEG') # Remove original image if os.path.exists(self.path): os.remove(self.path) def delete(self, save=True): if os.path.exists(self.thumb_path): os.remove(self.thumb_path) super(ThumbnailImageFieldFile, self).delete(save) class ThumbnailImageField(ImageField): attr_class = ThumbnailImageFieldFile def __init__(self, thumb_width=570, thumb_height=390, *args, **kwargs): self.thumb_width = thumb_width self.thumb_height = thumb_height super(ThumbnailImageField, self).__init__(*args, **kwargs) And applying it to my album model. models.py from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone from django.utils.text import slugify from album.fields import ThumbnailImageField def upload_location(instance, file_name): return "album/{}-{}/{}".format( instance.day, instance.week, file_name ) class Album(models.Model): DAYS = ( ('Sun', '일요일'), ('Mon', '월요일'), ) name = models.CharField(max_length=50) description = … -
Looping through django model and inserting values
I have a model product : class Product (models.Model): fk_subcat2=models.ForeignKey(SubCategory2) fk_seller=models.ForeignKey(User) name=models.CharField("Product Name",max_length=100) quantity=models.IntegerField("Product Quantity",default=0) active= models.BooleanField("Product Active or Not", default=False) price=models.FloatField("Price", default=0.0) selling_price=models.FloatField("Selling Price", default=0.0) tax=models.FloatField("Tax", default=0.0) shipping_charges=models.FloatField("Shipping Charge", default=0.0) cod_options=models.BooleanField("Cash on delivery options" , default=False) brand= models.CharField("Brand/Manufacturer",max_length=100) uid = models.CharField(max_length=50, editable=False, unique=True, default=get_unique_id_str) date_created = models.DateTimeField('Date created', default=timezone.now) date_updated= models.DateTimeField('Date updated',auto_now=True,auto_now_add=False) def __unicode__(self): return self.name I made an excel sheet for bulk uploading of products. Now what I want is dynamic product save i.e. I want to loop through the model fields(except fk_subcat2 and fk_seller) and insert values in it. What I have done is : for i in range(7): data1=b[i] prod=Product(fk_subcat2=category_instance, fk_seller=request.user) prod.data1=c[i].value prod.save() where b[] contains all the model fields(e.g. : name,quantity,price etc etc) and c[] contains values related to b[] (e.g. : Apple iphone 5s,5,300 $ etc etc).. Tried using this procedure but it never works.Might be having problem with the name prod.data1. Any solutions ????? Thanks -
Numpy Convolve not working with multiprocessing - Python
I have a django application, that uses multiprocessing. I have to update the application to use numpy.convolve. The problem is it does not work with multiprocessing, and throws exceptions, like "too many indices". Please suggest me a solution asap. -
(Django) my detailed pages aren't showing content (DetailView)
List view works but when I click on one of the objects in the page it just shows nothing but my template. What am I doing wrong? Here are my code files. urls.py from django.conf.urls import url from django.views.generic import ListView, DetailView from imgboard.models import Images from . import views urlpatterns = [ #url(r'^$', views.index, name='index'), url(r'^$', ListView.as_view(queryset=Images.objects.all(), template_name="imgboard/home.html")), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Images, template_name="imgboard/girlsdetailed.html")), url(r'^contact/$', views.contact, name='contact'), ] models.py class Images(models.Model): name_person = models.CharField(max_length=70) instagram = models.CharField(max_length=200) img_url = models.CharField(max_length=500) def __unicode__(self): return self.name_person class Meta: verbose_name_plural = 'Images' views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic.detail import DetailView import datetime from imgboard.models import Images # assuming its already in templates/ folder: def index(request): return render(request, 'imgboard/home.html') def current_datetime(request): datenow = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % datenow return HttpResponse(html) def contact (request): return render(request, 'imgboard/basic.html', {'content':['If you would like to contact me, please e-mail me', 'pfftdammitchris@gmail.com']}) home.html {% extends "imgboard/header.html" %} {% block content %} {% include "imgboard/includes/listview_code.html" %} {% endblock %} listview_code.html {% block content %} {% for xoo in object_list %} <p><a href="/imgboard/{{xoo.id}}">{{xoo.name_person}}</a></p> {% endfor %} {% endblock %} girlsdetailed.html {% extends "imgboard/header.html" %} {% block content %} <h1>{{ xoo.name_person }}</h1> <p>{{xoo.instagram}}</p> <p>{{xoo.img_url}}</p> {% … -
Django:Complex queryset filter for FK related models
I have many models in this way: Model 1: key=models.charfield() .... Model 2: ..... key=fk(model1, ralated_name='model2key') model 3: ..... key=fk(Model 2, related_name='model3key') models 4: ..... key=FK(model 3, related_name='model4key') Now i have to write a queryset, for model 4 where i need data filtering considering model 1 = something. How to do it?