Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tastypie Resource from a Model Object
I have an instance of a Django Model, say a p:Person and I have a PersonResource class. Can I generate tastypie json response of that object p ? -
Django: Extended user model using OneToOne Field. How do I make a sign up form to fill in all fields
So I've made a OneToOne Field extension of the Django user model and I am trying to get make a registration form. This is my form so far: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile class RegistrationForm(UserCreationForm): email = forms.EmailField(required = True) def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = '' self.fields['password2'].help_text = '' class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit = True): user = super(RegistrationForm, self).save(commit = False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user In my model extension I added fields called teacher, which is a yes or no, and School name. This is the model: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user') teacher = models.BooleanField(default = False) school = models.CharField(max_length = 50) How can I get these to appear in the form when someone registers on the site? -
Django admin site URL routing issues/inconsistencies
I am working on a website on Django 1.10, and I am trying to set up my admin site so the URL is at "/pcari/admin" instead of "/admin" Here is my root urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ # Admin site url(r'^admin/', admin.site.urls), # Regular site url(r'^pcari/', include('pcari.urls')), ] Here is my app urls.py: from django.conf.urls import url from django.contrib import admin from . import views app_name = 'pcari' urlpatterns = [ # Admin site url(r'^admin/', admin.site.urls), # User-facing views url(r'^$', views.index, name='index'), ... ] This setup technically works in that if I visit "127.0.0.1:8000/pcari/admin" I get the admin site, but I also get the admin site if I visit "127.0.0.1:8000/admin", which is something I do not want. However, if I remove the "url(r'^admin/', admin.site.urls)," line from the root urls.py file, I get a weird error when I try to access "127.0.0.1:8000/pcari/admin": NoReverseMatch at /pcari/admin/ u'admin' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/pcari/admin/ Django Version: 1.10.5 Exception Type: NoReverseMatch Exception Value: -
How to modify django-mailjet to send html only?
I have modified django to send html emails instead of plain text and this works fine. Now I want to use mailjet as my email backend. So I have to modify the backends.py, right? https://github.com/kidig/django-mailjet/blob/master/django_mailjet/backends.py Can you please help me to modify it? I am new to django/programming. I want to send html only, not both. -
Create User-Specific Redirect After Login in django
I have three types of people in my Django application Admin, Staff and Parent . how can I set up log-in for them as they will have different views after logging in using django registration? my code so far is this : in settings.py LOGIN_REDIRECT_URL = '/app/login_redirect' LOGIN_URL = '/app/accounts/login/' LOGOUT_URL = '/app/accounts/logout/' and in views.py: def login_redirect(request): if request.user.is_authenticated() and not request.user.is_superuser: return HttpResponseRedirect(reverse("dashboard")) elif request.user.is_superuser: return HttpResponseRedirect(reverse("dashboard")) -
How to add custom styling to Forms created with Django CreateView
I am very new to Django. Following some tutorials I have managed to create a form using the Python Generic Views (CreateView) I have a 'Question' Model class Question(models.Model): title = models.CharField(max_length=200) body = models.TextField(max_length=2000) category = models.CharField(max_length=50) votes = models.IntegerField(default=0) asked_date = models.DateTimeField(default=datetime.now) and using this model I have created a View Class class QuestionCreate(CreateView): model = Question fields = ['title', 'body', 'category'] This does generate a nice HTML form. But how do I pass CSS attributes to each field? -
How to Get Categories of Django Osacr product?
I have a list of product. I want to get the category(categories) it is associated with. What i have done is : pro = [] #holds list of all the products for p in pro: for procat in p.get_categories(): print(procat) but it returns with Error: 'ManyRelatedManager' object is not iterable I got the method from here DJANGO OSCAR -
Django Model Password Field Security
I am creating a sports app which allows users to create their own leagues and invite their friends to play. Ideally I would like to password protect the league. This is the table as it currently stands: class StraightRedPersonalLeague(models.Model): seasonid = models.IntegerField(primary_key = True) personalleaguelongname = models.CharField(max_length=36) personalleagueshortname = models.CharField(max_length=24) leaguepassword = ???? leagueispublic = models.NullBooleanField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='personalleague_seasonUserSelection') class Meta: managed = True db_table = 'straightred_personalleague' I have had a search on stackoverflow and found the following: How to create Password Field in Model django The answer wasn't accepted but has had some upvotes. Is it safe to store the password as a charfield? If so I assume the forms.PasswordInput is the part that is doing all the "magic" regards security. Any advice on this security issue would be appreciated. -
I have created a REST API using Django.How do I now use this API for a site?
I have successfully created an API for a blog using Django but how do I use it (to create a website including the HTML and CSS), all the tutorials point towards creating an API not towards using/utilizing it. Any set of tutorials or any guideline is highly appreciated. -
Connect to a schema other than the default schema in redshift
I need to connect my django app to a schema that is other than the default schema in redshift. When I connect it to default schema, the connection is successfull. when I connect it to a schema that is not the default it gives an error message saying "django.db.utils.OperationalError: FATAL: database "test" does not exist DATABASES = { 'default': { 'NAME': 'test', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'test', 'PASSWORD': '######', 'HOST': '############.redshift.amazonaws.com', 'PORT': #### } } -
redis is running but I'm getting "Error 111 connecting to localhost:6379. Connection refused"
Hi I 'm using django + redis + celery and I m getting lots of errors saying Cannot connect to redis://localhost:6379//: Error 111 connecting to localhost:6379. Connection refused The issue here is that I checked the uptime of my redis-server process and it has been up when the errors happened. Any idea what's going on? what can I check to see what's happening? Thanks! -
AttributeError:moudle 'sign.views' has no attribute 'login_action'
(Python 3.6.1, Django 1.11.1, PyCharm) When I use cmd entered my project and use manage.py to runserver it,the following information come up: the screenshot of the error AttributeError:module'sign.views'has no attribute'login_action' urls.py as follows: from django.conf.urls import url from django.contrib import admin from sign import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^index/$',views.index), url(r'^login_action/$',views.login_action), ] views.py as follows from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return render(request,"index.html") # 登录函数定义 def login_action(request): if request.method == 'post': username = request.POST.get('username','') password = request.POST.get('password','') if username == 'admin'and password == 'admin123': return HttpResponse( '恭喜您,登录成功!') else: return render(request,'index.html',{'error':'用户名或者登录密码错误!'}) and 'index.html' as follows <html> <head> <title>欢迎登陆点米年会发布会系统</title> </head> <body> <h1>年会签名系统登陆(WELCOM TO DIAN MI)</h1> <form method="post" action="/login_action/"> <input name="username" type="text" placeholder="用户名"><br> <input name="password" type="password" placeholder="登录密码"><br> <button id="btn" type="submit"> 登陆</button> {{error}}<br> </form> </body> </html> I have searched such problems on the internet,here is the reason for the error from the most netizens : need to delete the pyc file,but I am to new to learn the python and I cannot find the file even though I have used the search function on my computer . Dear friends,can some one can help me to solve such problem? Frame diagram of the project -
Django rest filter custom fields
I am converting a unix date to a string date and passing it as a custom read only field. What would be the best way to use django-filter to be able to filter this custom field? The error i get is Cannot resolve keyword 'convert_time' into field. Choices are: .. Models class ``` class AccountT(models.Model): created_date_t = models.BigIntegerField(blank=True, null=True) def convert_time(self): result = time.strftime("%D", time.localtime(self.created_date_t)) return result ``` Serializer Class ``` class AccountTSerializer(serializers.ModelSerializer): created_date = serializers.ReadOnlyField(source='convert_time') class Meta: model = AccountT fields = ('othermodelfield','othermodelfield', 'created_date', ) ``` ListAPiView ``` class AccountTListView(generics.ListAPIView): serializer_class = AccountTSerializer queryset = AccountT.objects.all() filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,) filter_fields = ('othermodelfield','created_date_t') ``` -
SolrCore Initialization Failures: trouble reloading core
Somebody help. I am getting "org.apache.solr.common.SolrException:org.apache.solr.common.SolrException: Could not load conf for core account: Plugin Initializing failure for [schema.xml] fieldType. Schema file is solr/account\conf\schema.xml" when I try to reload my core. Dont know what the problem is. I am using solr 4.10.4. Here is my solrconfig.xml <?xml version="1.0" encoding="utf-8" ?> <config> <luceneMatchVersion>LUCENE_36</luceneMatchVersion> <requestHandler name="/select" class="solr.StandardRequestHandler" default="true" /> <requestHandler name="/update" class="solr.UpdateRequestHandler" /> <requestHandler name="/admin" class="solr.admin.AdminHandlers" /> <requestHandler name="/admin/ping" class="solr.PingRequestHandler"> <lst name="invariants"> <str name="qt">search</str> <str name="q">*:*</str> </lst> </requestHandler> </config> thanks -
Python; Django adding characters to path name causing OS error 22
I've been trying to get django to render a template I created. At first it said that the template does not exist, however once I fixed the error it is now adding characters to the path and not finding the template because of that. The path should be: C:\\Users\\ABC\\Desktop\\science_crowd\\Lightweight_Django\\placeholder\\home.html However the error says that it cannot find: C:\\Users\\Benjamin\\Desktop\\science_crowd\\Lightweight_Django\\placeholder\\:\\home.html It added a colon and another backslash for no reason. The settings for this project is as follows: ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '127.0.0.1').split(',') BASE_DIR = os.path.dirname(os.path.abspath(__file__)) settings.configure( DEBUG = DEBUG, SECRET_KEY = SECRET_KEY, ALLOWED_HOSTS = ALLOWED_HOSTS, ROOT_URLCONF = __name__, MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ), TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': os.path.join(BASE_DIR, 'templates'), 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ "django.contrib.auth.context_processors.auth", ], }, }, ], STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ), STATIC_URL = '/static/', ) The view that is trying to render the template: def index(request): example = reverse('placeholder', kwargs = {'width': 50, 'height': 50}) context = { 'example': request.build_absolute_uri(example) } dir = os.path.join(BASE_DIR, 'templates') return render(request, 'home.html', context = context) Thank you so much for your help! -
Extending Django Wagtail Documents Class to Include an Image
I am using Django Wagtail 1.10.1. My site has hundreds of documents organized by tags. I am inserting the documents into my templates with {% document_snippets tags__slug='chapter-documents' %} and it works great. But how can I, if possible, extend the Documents class to allow me to assign an image, so when the documents are listed on the page, I can show the image instead of the document title? -
Getting long error with django, manage.py runserver
I need help! I'm learning python django to try and run a website and I'm trying to setup a blog and suppose to migrate, but when I try manage.py runserver and makemigrations, I get this mess: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1041e9c80> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 255, in check warnings.extend(check_resolver(pattern)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 414, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from '/Users/mingma/apps/mysite/blog/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in … -
Amazon S3 - Storing image files from Django - Don't upstream uploaded images by the user
I have the custom User model in which I've add a avatar field class User(AbstractBaseUser, PermissionsMixin): # email # username # first_name # last_name avatar = models.ImageField( upload_to='avatars', blank=True, null=True, verbose_name='Photo' ) I've install the following packages via pip install: boto3==1.4.4 django-boto==0.3.11 django-storages==1.5.2 django-storages-redux==1.3.2 Pillow==4.0.0 I am using the following Amazon S3 configurations in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third party apps 'storages', ] STATIC_URL = '/assets/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "assets"), ) #Amazon S3 Storage AWS_STORAGE_BUCKET_NAME = get_env_variable('AWS_STORAGE_BUCKET_NAME') AWS_ACCESS_KEY_ID = get_env_variable('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = get_env_variable('AWS_SECRET_ACCESS_KEY') # Tell django-storages that when coming up with the URL for an item in S3 storage, keep # it simple - just use this domain plus the path. # (If this isn't set, things get complicated). # This controls how the `static` template tag from `staticfiles` gets expanded, if you're using it. We also use it in the next setting. AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME # For media files to S3 STATICFILES_LOCATION = 'assets' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' I have the custom_storages.py file, in which I have some classes to storage … -
Django Wagail error: column wagtailusers_userprofile.preferred_language does not exist
I upgraded Wagtail to version 1.10.1 and now when I try to log into admin I get column wagtailusers_userprofile.preferred_language does not exist error. The error seems obvious, but I am not sure how to fix it; I assumed the Wagtail upgrade would have handled it. Below is the traceback. Thank you. Environment: Request Method: GET Request URL: http://127.0.0.1:8001/admin/ Django Version: 1.11.2 Python Version: 3.5.0 Installed Applications: ['app', 'home', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_summernote', 'rest_framework', 'wagtail.contrib.settings', 'wagtail.contrib.modeladmin', 'wagtail.wagtailcore', 'wagtail.wagtailadmin', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailsites', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'wagtail.contrib.wagtailsitemaps', 'wagtail.contrib.wagtailroutablepage', 'wagtail.contrib.wagtailstyleguide', 'wagtailmenus', 'compressor', 'taggit', 'modelcluster', 'docs'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware'] Traceback: File "/Users/rooster/.pyenv/versions/3.5.0/envs/alpha_omega/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py" in __get__ 385. rel_obj = getattr(instance, self.cache_name) During handling of the above exception ('User' object has no attribute '_wagtail_userprofile_cache'), another exception occurred: File "/Users/rooster/.pyenv/versions/3.5.0/envs/alpha_omega/lib/python3.5/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) The above exception (column wagtailusers_userprofile.preferred_language does not exist LINE 1: ...gtailusers_userprofile"."rejected_notifications", "wagtailus... ^ ) was the direct cause of the following exception: File "/Users/rooster/.pyenv/versions/3.5.0/envs/alpha_omega/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/rooster/.pyenv/versions/3.5.0/envs/alpha_omega/lib/python3.5/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/Users/rooster/.pyenv/versions/3.5.0/envs/alpha_omega/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/rooster/.pyenv/versions/3.5.0/envs/alpha_omega/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) … -
How do you write out the value of a dictionary key using Django with Python?
I want to know how yu can incorporate it into the html. What I have right now is the following. {% for u in list %} {{ u }} <br> {% endfor %} And what I want is something along these lines- {% for u in list %} {{ u }} <br> {{ u.value }} <br> {% endfor %} Thanks guys! EDIT: A sample would look like the following- Apple 10 --- Banana 4 --- Orange 3 --- Pear 1 --- -
Django registration view not validating form?
Would anyone know why the following form is not validating: forms.py: class UserRegistrationForm(UserCreationForm): required_css_class = 'required' username = forms.CharField(label='Username') email = forms.EmailField(label='Email') password = forms.CharField(label='Password') password2 = forms.CharField(label='Password2') class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') def __init__(self, *args, **kwargs): super(UserRegistrationForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={'placeholder': 'Username'}) self.fields['username'].required = True self.fields['username'].error_messages = {'required': 'Please enter your username'} self.fields['email'].widget = EmailInput(attrs={'placeholder': 'Email'}) self.fields['email'].required = True self.fields['email'].error_messages = {'required': 'Please enter your email'} self.fields['first_name'].widget = TextInput(attrs={'placeholder': 'Forename'}) self.fields['first_name'].required = True self.fields['first_name'].error_messages = {'required': 'Please enter your first name'} self.fields['last_name'].widget = TextInput(attrs={'placeholder': 'Surname'}) self.fields['last_name'].required = True self.fields['last_name'].error_messages = {'required': 'Please enter your last name'} self.fields['password'].widget = PasswordInput(attrs={'placeholder': 'Password'}) self.fields['password'].required = True self.fields['password'].error_messages = {'required': 'Please enter your Password'} self.fields['password2'].widget = PasswordInput(attrs={'placeholder': 'Confirm password'}) self.fields['password2'].required = True self.fields['password2'].error_messages = {'required': 'Please confirm your Password'} def cleaned_username(self): username = self.cleaned_data.get('username') username_qs = User.objects.filter(username=username) if username_qs.exists(): raise forms.ValidationError("I'm sorry, that username already exists.") def cleaned_email(self): email = self.cleaned_data.get('email') email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("I'm sorry, this email has already been taken.") def cleaned_password2(self): password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password != password2: raise forms.ValidationError("Your passwords do not match.") templates.html: <form class="contact-form" name="contact-form" method="POST" action="." enctype='multipart/form-data'> <div class="form-group"> {% csrf_token %} <input … -
Django runserver or Django-RQ runworker lead to AttributeError: module 'signal' has not attribute 'SIGKILL'
Full output for python manage.py runserver: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0475D588> Traceback (most recent call last): File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_rq\__init__.py", line 3, in <module> from .decorators import job File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_rq\decorators.py", line 2, in <module> from rq.decorators import job as _rq_job File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\rq\__init__.py", line 11, in <module> from .worker import SimpleWorker, Worker File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\rq\worker.py", line 88, in <module> class Worker(object): File "C:\Users\Vladimir\AppData\Local\Programs\Python\Python36-32\lib\site-packages\rq\worker.py", line 361, in Worker def kill_horse(self, sig=signal.SIGKILL): AttributeError: module 'signal' has no attribute 'SIGKILL' and the output for python manage.py rqworker: … -
Django: have admin take image file but store it as a base64 string
I was tasked with creating an admin view such that a user could input an image file, which however would be stored as a base64 string as a model field rather than exist in a static files dir on our server. I'm unclear on how exactly this process would be done, should I be intercepting the POST request from the admin view and pre-processing it to be stored in the field? Should I be overwriting the save method of the base form? I'm a little confused by the different methods and have been unable to produce a working result. Here's my setup: models.py from django.db import models class Product(models.Model): organization = models.ForeignKey(Organization) name = models.CharField(max_length=50) logo = models.TextField() admin.py from django.contrib import admin from .models import Product class ProductAdmin(admin.ModelAdmin): exclude = ('logo',) admin.site.register(Product, ProductAdmin) misc.py #how i'd process an image? from PIL import Image from base64 import b64encode def image_to_b64(image_file): imgdata = Image(image_file) encoded = b64encode(open(imgdata, 'rb')) return encoded -
Unninstall app A that app B have a dependency in one old migration
I am trying to uninstall django-cities but in my app "places" i have a model called Venue, that in the migration 0001 had a ForeingKey to cities.Subregion model of django-cities, but i don't need this app|relation anymore. I proced to delete of INSTALLED_APPS but i have this error: Traceback (most recent call last): File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/d/.virtualenvs/beplay/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 274, in build_graph raise exc django.db.migrations.exceptions.NodeNotFoundError: Migration places.0001_initial dependencies reference nonexistent parent node (u'cities', u'0010_adjust_unique_attributes') Ok, then i delete this dependencies and uninstall the django-cities and all works for me, but when someone else have to install the project, on migrate raise this error: ValueError: Related model u'cities.Subregion' cannot be resolved because, i delete from requirements.txt and is still referenced in migration 0001 yet: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Venue', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('name', models.CharField(max_length=255)), ('phone', models.CharField(blank=True, max_length=255, null=True)), ('mobile', models.CharField(blank=True, max_length=255, null=True)), ('email', models.EmailField(blank=True, … -
The right way to use use choices in django
I have my choices as follows but i get an error stating choices must be an iterable containing actual value and readable name my model.py class mymodel(models.Model): MY_CHOICES =( ('corperation1','corperation'), ('Liablility2','Liablility'), ) Company_type = MultiSelectField(choices=MY_CHOICES,max_choices=1,max_length=2)