Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show Django template with a camera stream
I'm trying to build a simple website in Python with Django. I want to load and show a template, and then show, on top of the template's background, the images acquired from the webcam for few seconds. Finally, the last image is saved on hard disk. The problem is that the template is loaded and showed only after the camera code finishes. This is the code: from django.shortcuts import render def takePicture(request): l = render(request,'pepper/picture.html') camstream() return l camstream() is the method that activates the stream from the camera, and it works as expected. It uses pygame, following this tutorial. Any suggestion? -
Django 1.9.2: Remove field from model very long
I have more than 2 million objects for the model. When I added a new field, the migration went fast I created another migration where I delete 4 fields - migration hangs for several hours How can I speed up the process? Does it depend on the number of objects? My migration for delete: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('multisession', '0008_add'), ] operations = [ migrations.RemoveField( model_name='mymodel', name='field1', ), migrations.RemoveField( model_name='mymodel', name='field2', ), migrations.RemoveField( model_name='mymodel', name='field3', ), migrations.RemoveField( model_name='mymodel', name='field4', ), ] -
Python decode unknown character
I'm trying to decode the following: UKLTD� For into utf-8 (or anything really) but I cannot workout how to do it and keep getting errors like 'ascii' codec can't decode byte 0xae in position 8: ordinal not in range(128) I'm reading from a csv and have the following: with open(path_to_file, 'rb') as f: reader = csv.reader(f) for row in reader: order = Order( ... product_name = row[11].encode('utf-8'), ... ) order.save() I would be happy right now to just ignore the character if I have keep the rest of the string. -
Django with nginx and gunicorn
I have deployed django with gunicorn and nginx, and it works fine, if the django app is served on the root url, with this configuration: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:my_app.sock; } } However when I try to serve the django app on another url, it doesn't work. If I try to access http://domain/my_app/admin/ django tells me it cannot find the view. This is nginx config: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location /my_app { include proxy_params; proxy_pass http://unix:/var/my_app/app.sock; } } How could I make this work? I was not able to find any solution to specify something like a "BASE_URL" so far. Thanks -
How should I add django import export on the User Model
I am trying to enable django import export on the django user model. I have tried defining a model admin class, unregistering the user model and then registering the new user admin class. But it doesn't work. my admin.py looks like this - from django.contrib.auth.admin import UserAdmin as BaseAdmin class UserResource(resources.ModelResource): model = User fields = ('first_name', 'last_name', 'email') class UserAdmin(BaseAdmin, ImportExportModelAdmin): resource_class = UserResource admin.site.unregister(User) admin.site.register(User, UserAdmin) I want to know how can I achieve this? Is there some other way I can apply django import export on the user model? -
Step wise django tutorial reference from basic to advance
Actually i've completed basics of python including OOP concepts, can anyone refer me to the best resource to learn django , as i m completely new to it. -
Django Rest Framework ModelSerializer all fields not working properly
I'm trying to get all the fields and functions from my model. It works well with the fields but it doesn't get the functions. models.py snippet: email = models.EmailField(_('Email'), null=True, blank=True) @property def function_name(self): return ... serializers.py snippet: class ModelNameSerializer(serializers.ModelSerializer): class Meta: model = ModelName fields = '__all__' If i call serializers.data from views.py, i get the field email but not the return value of the function. If i do fields = ('function_name',), then i get the return value of the function but not anymore all the other fields. How can i get all fields and functions from my model? I hope that i could explain my problem. -
django mobile number regular expression
I have seen many of the phone example as well as third party package for thie mobile number field. but what i want is this: +country_code , or space (these 3 are optional) phone_number(min range number= 8, max is 13) EG: +65, 98654578 based on one of the example and it work but not to what i wanted. : What's the best way to store Phone number in Django models phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list The one i made is this : mobile_regex = RegexValidator(regex=r'^\+?1?\d{1-3}?\,?\s?\d{8-15}$', message="Phone number must not consist of space and requires country code. eg : +6591258565") But it doesnt work. Did i do something wrong? please help me -
IndentationError: unindent does not match any outer indentation level model.py line 36
I am new in python as well as Django. i got error (IndentationError: unindent does not match any outer indentation level) line 36 model.py below is my code class Load_ProviderRegistration(models.Model): def number(): // i got error in this line no = Load_ProviderRegistration.objects.count() if no == None: return 1 else: return no + 1 Load_Provider_id = models.IntegerField(unique=True,default=number) Load_Provider_name = models.CharField(max_length=50) address = models.CharField(max_length=100) contact = models.CharField(max_length=13) -
django + apscheduler - How to configure APScheduler to use django db connection data in settings.py?
I have a working Django project with its database and model tables.Now, I want to integrate APScheduler and save APScheduler job in the same database as other tables, using the Django database connection. I have read the User Guide which gives examples of hardcoding db connection string into code: from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.mongodb import MongoDBJobStore from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor jobstores = { 'mongo': MongoDBJobStore(), 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 3 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc) But the config data I already have it in Django setting file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxx', 'USER': "manager", 'PASSWORD': "xxxxxxxx", 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } Can I just use Django connection? I don't want to write these data into another properties file to maintain two files. -
django-celery-beat not using defined time period
I am using django celery beat to define periodic tasks. Everything works well. But I have got this problem. When I turn on the beat, it keeps sending the task to the worker multiple times in a second. Here is the log record, [2017-12-22 14:20:21,950: DEBUG/MainProcess] db.tasks.check_next_service sent. id->d0ac2127-83bd-419a-b345-07630ec6af3d [2017-12-22 14:20:21,956: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:21,963: DEBUG/MainProcess] db.tasks.check_next_service sent. id->952a8f7e-270a-4a0f-8339-bdf7788f97b3 [2017-12-22 14:20:21,970: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:21,982: DEBUG/MainProcess] db.tasks.check_next_service sent. id->07bd7748-7ce9-4bb4-80f3-875482785c02 [2017-12-22 14:20:21,986: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:21,990: DEBUG/MainProcess] db.tasks.check_next_service sent. id->46f5dbf4-552e-4757-805d-c164cee21c1a [2017-12-22 14:20:22,004: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:22,017: DEBUG/MainProcess] db.tasks.check_next_service sent. id->8cb0bb26-88bc-4bf5-acfb-2f7a61338c92 [2017-12-22 14:20:22,022: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:22,031: DEBUG/MainProcess] db.tasks.check_next_service sent. id->d864c19b-b42f-4e18-9f0d-95b5718514b4 [2017-12-22 14:20:22,043: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) [2017-12-22 14:20:22,051: DEBUG/MainProcess] db.tasks.check_next_service sent. id->e4629a95-936b-4c12-8ce8-7368c060a75f [2017-12-22 14:20:22,060: INFO/MainProcess] Scheduler: Sending due task check next service (db.tasks.check_next_service) See, it sends the task almost 10 times within a second whereas I have declared the interval to be every 1 minute. I have seen this issue, https://github.com/celery/celery/issues/943 and also set CELERY_UTC_ENABLE to TRUE. STill the problem persists. … -
django CBV generic DetailView redirect if object does not exist
I have a DetailView which displays userprofile if the current logged in user has a userprofile created. If the user does not have a profile created, i need an else condition. Since im new to django and python, and even newer to CBV, i cannot figure out my next step. I'm hoping there is a way in def get_object() to redirect to UserProfile. Without a userprofile present it results in Related Object DoesNotExist error. How can i write an else or except condition to redirect to ProfileView (form to create profile) PS: UserProfile is to Create a profile, UserProfileView is to View a created profile, UserProfileUpdate is to Update an existing profile. Models.py class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) phone = models.CharField(max_length=128, unique=True, null=True, validators=[validators.RegexValidator( r'^(?:\+?(\d{2}))?(\d{10})$', _('Enter a valid phone number. Type without space or special charecter.') )]) objects = UserManager() REQUIRED_FIELDS = ['first_name'] USERNAME_FIELD = 'email' def __str__(self): return self.email class UserProfile(models.Model): """User Profile""" user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=128) state = models.CharField(max_length=128) city = models.CharField(max_length=128) landmark = models.CharField( max_length=128, help_text='Enter a landmark closest to you') address_line_1 = models.CharField( max_length=128, help_text='House name/Flat No') address_line_2 = models.CharField( max_length=128, help_text='Street Name/No') address_line_3 = models.CharField( … -
How to create Real-time collaborative whiteboard in Django?
I'm implementing a online tutorial website in Django. One option is to implement an interactive whiteboard section. I tried the whiteboard 0.1.1 (Link) . But I was hoping someone could guide me with the best option. Thanks. -
Django 2.0 - test using fixtures from dumpdata gives utf8mb4 encoding errors
I am using utf8mb4 encoding for my mySQL database. All my Django apps work correctly with it even with Cyrillic characters. But when I run ./manage.py test <module> and try to load a fixture dumped from the same database, I get errors regarding the encoding. One of the errors is: Could not load advert.Region(pk=1): (1366, "Incorrect string value: '\\xD0\\x9F\\xD0\\xBB\\xD0\\xBE...' for column 'region_name' at row 1") Then I set DEFAULT_CHARSET in the Django settings and the error changed to LookupError: Problem installing fixture '<path>/test_db_one.xml': unknown encoding: utf8mb4 As you can see I have specified the format of the fixture to be XML as it has better handling of the encoding. My setting module has the following properties: DEFAULT_CHARSET = 'utf8mb4' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'autoplusplus_dev', 'USER': 'autoplusplus_django', 'PASSWORD': '1029', 'HOST': 'localhost', 'PORT': '3306', 'STORAGE_ENGINE': 'INNODB', 'OPTIONS': {'charset': 'utf8mb4'}, 'TEST_CHARSET': 'utf8mb4', } } I have mysqlclient 1.3.12 installed -
Error with list_route: POST methods in Viewset
I am making a function Add Friend which user can Create one Friendship Request object to another user user URL:http://localhost:8000/api/v1/users/{username}/add_friend/ but I get error when making. Hope you guys help me! Code in Urls.py from .views import (AddFriendUserAPIView) urlpatterns = [ url(r'^(?P<username>[\w-]+)/add_friend/$', AddFriendUserAPIView.as_view({'post': 'add_friend'}), name='add_friend'), ] Code in Views.py class AddFriendUserAPIView(ReadOnlyModelViewSet): serializer_class = FriendRequestSerializer queryset = FriendshipRequest.objects.all() @list_route(methods=['POST']) def add_friend(self, request): add_qs = FriendshipRequest.objects.get_or_create(from_user=self.request.user, to_user=self.user, message='') serializer = self.get_serializer(add_qs) return Response(serializer.data) Code in serializers.py class FriendRequestSerializer(ModelSerializer): class Meta: model = FriendshipRequest fields = ( 'id', 'from_user', 'to_user', 'message', ) Error log by Trackback Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\viewsets.py" in view 90. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) Exception Type: TypeError at /api/v1/users/duongnuhabang/add_friend/ Exception Value: add_friend() got an unexpected keyword argument 'username' Request Information -
write persian in slug and use it in address bar in django
i use django and in my models i want to write persian in slugfield (by using utf-8 or something else) and use the slug in address of page i write this class for model class Category(models.Model): name = models.CharField(max_length=20, unique=True) slug = models.SlugField(max_length=20, unique=True) description = models.CharField(max_length=500) is_active = models.BooleanField(default=False) meta_description = models.TextField(max_length=160, null=True, blank=True) meta_keywords = models.TextField(max_length=255, null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) def __str__(self): return self.name def category_posts(self): return Post.objects.filter(category=self).count() but there is nothing in slug column after save and i don't know what am i write in url to show persian can you tell me what do i do? and i use django 1.9 and python 3.6 -
How to create a choice field from many to many connection
In my Django model I have a many to many connection. I would also like to have the option of selecting a primary diagnosis from the connected diagnoses. class Case(models.Model): diagnoses_all_icd_10 = models.ManyToManyField('ICD10') How can I create a choice field that displays only the associated diagnoses for selection? It is important that the solution also works in the Django admin. -
Saving data VS calculating data again and again
As a beginner coder and developer in python and Django I am facing a structure question that will help me and could potentially help other beginner as well. I have a survey application, which ask a user to answer a list of question from 0-100 and then some calculation are made on the background and retrieve scores on charts. My question is do you think I should store each user score in my data base or should it calculate each time the page is loaded ? Thx you -
Getting error `set object is not subscriptable` while trying to add user authenticated via social_django to a Group
I am trying to add a user authenticated by Microsoft Azure Active Directory using social_django to a User Group. Here is my pipleline.py from django.db.models import signals from django.dispatch import Signal from social.pipeline.user import * from django.contrib.auth.models import User, Group from social.utils import module_member def new_users_handler(sender, user, response, details, **kwargs): user.groups.add(Group.objects.get(name='Customer')) user_details.connect(new_users_handler, sender=None) Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', # 'social.apps.django_app.default', ] AUTHENTICATION_BACKENDS = ( 'social.backends.azuread.AzureADOAuth2', ) #settings.py SOCIAL_AUTH_PIPELINE = { 'pipeline.new_users_handler' } Here is the complete output TypeError at /complete/azuread-oauth2/ 'set' object is not subscriptable Request Method: GET Request URL: http://127.0.0.1:8000/complete/azuread-oauth2/?code=&state=&session_state= Django Version: 1.11 Exception Type: TypeError Exception Value: 'set' object is not subscriptable Exception Location: /home/sudheer/self/venv/sso/lib/python3.5/site-packages/social_core/backends/base.py in run_pipeline, line 110 Python Executable: /home/sudheer/self/venv/sso/bin/python Python Version: 3.5.2 Python Path: ['/home/sudheer/self/testsso', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-i386-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/sudheer/self/venv/sso/lib/python3.5/site-packages'] Server time: Fri, 22 Dec 2017 08:40:23 +00 -
Django:name 'Post' is not defined in InteractiveConsole
I am very new to Django, and was trying to develop a blog based on it. After the commands of python manage.py makemigrations and python manage.py migrate worked well, I got into the InteractiveConsole to execute Post.objects.all() and got a NameError. >>> Post.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'Post' is not defined Besides, when running localhost:8000, Server gave another NameError. NameError at / name 'Post' is not defined Request Method: GET Request URL: http://localhost:8000/ Django Version: 2.0 Exception Type: NameError Exception Value: name 'Post' is not defined Exception Location: D:\experiment\blogproject\blog\views.py in index, line 6 Python Executable: d:\experiment\blogproject_env\Scripts\python.exe Python Version: 3.6.3 Python Path: ['D:\\experiment\\blogproject', 'd:\\experiment\\blogproject_env\\Scripts\\python36.zip', 'd:\\experiment\\blogproject_env\\DLLs', 'd:\\experiment\\blogproject_env\\lib', 'd:\\experiment\\blogproject_env\\Scripts', 'd:\\professional soft\\python3.6.3\\Lib', 'd:\\professional soft\\python3.6.3\\DLLs', 'd:\\experiment\\blogproject_env', 'd:\\experiment\\blogproject_env\\lib\\site-packages'] Server time: 星期五, 22 十二月 2017 16:08:10 +0800 and the following was my views.py. from django.shortcuts import render from django.http import HttpResponse def index(request): post_list = Post.objects.all().order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) In case, there is the Post code in models.py. class Post(models.Model): title = models.CharField(max_length=70) body = models.TextField() created_time = models.DateTimeField() modified_time = models.DateTimeField() excerpt = models.CharField(max_length=200, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title Thank u so much! -
ast.literal_eval - loop over string elements in a list
Goal: I want to extract longlat tuples in the map key from a request.POST below. <QueryDict: {'map': ['(38.70053557156445, 149.81571853160858)', '(38.70060091643143, 149.8153966665268)'], 'csrfmiddlewaretoken': ###}> Problem: I used ast.literal_eval to extract the tuples but somehow only 2nd tuple is returned. markers = request.POST position = ast.literal_eval(markers['map']) I also tried looping over map with but this is giving me SyntaxError: unexpected EOF while parsing on tuple parentheses. for idx, val in enumerate(markers['map']): position = ast.literal_eval(markers['map'][idx]) Finally, I tried list(map(ast.literal_eval, markers['map'])), but this returns the same SyntaxError as above. -
Django Celery retry current task with failed data set only
I have the following code from utils import SendSMS from celery.exceptions import * @celery.task(bind=True, max_retries=3) def send_sms(self,sms_list): failed_items = [] for sms_item in sms_list: status = SendSMS( **sms_item ) if status in ['Timeout','Error']: failed_items.append( sms_item ) if len(failed_items) > 0: raise self.retry(failed_items) return "sms(s) send successfully." i want to retry the task but with different data set, with only failed data set i mean how can i achieve this line: raise self.retry(failed_items) ? Thanks in advance. -
Update many to many relation record without removing any existing valid records
Django : 1.11 Python : 3.4 I have a model Pattern that is many to many with Shape through PatternShape class Pattern(ProductVariantParent): name = models.CharField(_('Pattern Name'), max_length=100) serial_number = models.CharField( _('Pattern Number'), max_length=100, unique=True) shape_names = models.ManyToManyField(Shape, through='PatternShape') class PatternShape(models.Model): pattern = models.ForeignKey( Pattern, on_delete=models.CASCADE, related_name='patterns') shape_name = models.ForeignKey( Shape, on_delete=models.CASCADE, related_name='shape_names') I would like to be able to update the list of shapes associated with a single pattern without doing unnecessary deletion I could do a process like this: pattern_instance.shape_names.clear() for shape_instance in new_list_of_shape_data: PatternShape.objects.create( pattern=pattern_instance, shape_name=shape_instance) However, this will mean that unchanged pattern_shape records will be deleted and then subsequently added. Of course, brand new pattern_shape records will definitely be added and no longer valid pattern_shape records will be deleted. I wonder if there is a more elegant way to do this using Django ORM without resorting to mass delete and then adding back. -
random.choice not acting random at all
I have been working on a silly magic item creator that makes use of diffrent lists with stuff that can happen, feelings, coluers and so on. i have been using random.choice to pick from these lists but somehow the items generated do not really seem random at all. when i run it 10 times in a row i get stuff like: A feather that causes horrible visions of an impending disaster, when starring at it A lamp that makes you feel drunk when you lick a person who has something you want A feather that makes you feel drunk when you lick a person who has something you want A dagger that makes you feel drunk when you lick a person who has something you want A feather that causes horrible visions of an impending disaster, when starring at it A lamp that glows white when you touch a person thinking of you A book that makes you feel drunk when you lick a person who has something you want A cane that makes you feel drunk when you lick a person who has something you want A marble that makes you feel drunk when you lick a person who … -
DJANGO HIVE CONNECTIVITY
DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'sampletest', 'OPTIONS': { 'driver': '/opt/cloudera/hiveodbc/lib/64/libclouderahiveodbc64.so', 'dsn': 'Hive1', 'host_is_server': True, }, } } Above is the Django settings for the connectivity with the Hive database; Here I am facing an issue when I run the project which is given below: django.db.utils.Error: ('HY000', u"[HY000] [Cloudera][Hardy] (80) Syntax or semantic analysis error thrown in server while executing query. Error message from server: Error while compiling statement: FAILED: ParseException line 1:7 character '@' not supported here\nline 1:8 character '@' not supported here (80) (SQLExecDirectW)") The query where it is occurring is actually a standard query "SELECT @@TRANCOUNT" which is triggered by Django while connectivity Please suggest solution. Thanks in Advance.